askii-cli 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Xg=Object.create;var go=Object.defineProperty;var ey=Object.getOwnPropertyDescriptor;var ty=Object.getOwnPropertyNames;var ry=Object.getPrototypeOf,ny=Object.prototype.hasOwnProperty;var $=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),iy=(t,e)=>{for(var r in e)go(t,r,{get:e[r],enumerable:!0})},sy=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ty(e))!ny.call(t,i)&&i!==r&&go(t,i,{get:()=>e[i],enumerable:!(n=ey(e,i))||n.enumerable});return t};var Me=(t,e,r)=>(r=t!=null?Xg(ry(t)):{},sy(e||!t||!t.__esModule?go(r,"default",{value:t,enumerable:!0}):r,t));var yo=$((Ri,Jc)=>{(function(t,e){typeof Ri=="object"&&typeof Jc<"u"?e(Ri):typeof define=="function"&&define.amd?define(["exports"],e):e(t.WHATWGFetch={})})(Ri,(function(t){"use strict";var e=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},r={searchParams:"URLSearchParams"in e,iterable:"Symbol"in e&&"iterator"in Symbol,blob:"FileReader"in e&&"Blob"in e&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in e,arrayBuffer:"ArrayBuffer"in e};function n(w){return w&&DataView.prototype.isPrototypeOf(w)}if(r.arrayBuffer)var i=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],s=ArrayBuffer.isView||function(w){return w&&i.indexOf(Object.prototype.toString.call(w))>-1};function a(w){if(typeof w!="string"&&(w=String(w)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(w)||w==="")throw new TypeError('Invalid character in header field name: "'+w+'"');return w.toLowerCase()}function l(w){return typeof w!="string"&&(w=String(w)),w}function c(w){var E={next:function(){var P=w.shift();return{done:P===void 0,value:P}}};return r.iterable&&(E[Symbol.iterator]=function(){return E}),E}function u(w){this.map={},w instanceof u?w.forEach(function(E,P){this.append(P,E)},this):Array.isArray(w)?w.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):w&&Object.getOwnPropertyNames(w).forEach(function(E){this.append(E,w[E])},this)}u.prototype.append=function(w,E){w=a(w),E=l(E);var P=this.map[w];this.map[w]=P?P+", "+E:E},u.prototype.delete=function(w){delete this.map[a(w)]},u.prototype.get=function(w){return w=a(w),this.has(w)?this.map[w]:null},u.prototype.has=function(w){return this.map.hasOwnProperty(a(w))},u.prototype.set=function(w,E){this.map[a(w)]=l(E)},u.prototype.forEach=function(w,E){for(var P in this.map)this.map.hasOwnProperty(P)&&w.call(E,this.map[P],P,this)},u.prototype.keys=function(){var w=[];return this.forEach(function(E,P){w.push(P)}),c(w)},u.prototype.values=function(){var w=[];return this.forEach(function(E){w.push(E)}),c(w)},u.prototype.entries=function(){var w=[];return this.forEach(function(E,P){w.push([P,E])}),c(w)},r.iterable&&(u.prototype[Symbol.iterator]=u.prototype.entries);function h(w){if(!w._noBody){if(w.bodyUsed)return Promise.reject(new TypeError("Already read"));w.bodyUsed=!0}}function f(w){return new Promise(function(E,P){w.onload=function(){E(w.result)},w.onerror=function(){P(w.error)}})}function d(w){var E=new FileReader,P=f(E);return E.readAsArrayBuffer(w),P}function p(w){var E=new FileReader,P=f(E),q=/charset=([A-Za-z0-9_-]+)/.exec(w.type),W=q?q[1]:"utf-8";return E.readAsText(w,W),P}function m(w){for(var E=new Uint8Array(w),P=new Array(E.length),q=0;q<E.length;q++)P[q]=String.fromCharCode(E[q]);return P.join("")}function g(w){if(w.slice)return w.slice(0);var E=new Uint8Array(w.byteLength);return E.set(new Uint8Array(w)),E.buffer}function y(){return this.bodyUsed=!1,this._initBody=function(w){this.bodyUsed=this.bodyUsed,this._bodyInit=w,w?typeof w=="string"?this._bodyText=w:r.blob&&Blob.prototype.isPrototypeOf(w)?this._bodyBlob=w:r.formData&&FormData.prototype.isPrototypeOf(w)?this._bodyFormData=w:r.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)?this._bodyText=w.toString():r.arrayBuffer&&r.blob&&n(w)?(this._bodyArrayBuffer=g(w.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(w)||s(w))?this._bodyArrayBuffer=g(w):this._bodyText=w=Object.prototype.toString.call(w):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof w=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},r.blob&&(this.blob=function(){var w=h(this);if(w)return w;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 w=h(this);return w||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(r.blob)return this.blob().then(d);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var w=h(this);if(w)return w;if(this._bodyBlob)return p(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(m(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r.formData&&(this.formData=function(){return this.text().then(S)}),this.json=function(){return this.text().then(JSON.parse)},this}var b=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function D(w){var E=w.toUpperCase();return b.indexOf(E)>-1?E:w}function v(w,E){if(!(this instanceof v))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');E=E||{};var P=E.body;if(w instanceof v){if(w.bodyUsed)throw new TypeError("Already read");this.url=w.url,this.credentials=w.credentials,E.headers||(this.headers=new u(w.headers)),this.method=w.method,this.mode=w.mode,this.signal=w.signal,!P&&w._bodyInit!=null&&(P=w._bodyInit,w.bodyUsed=!0)}else this.url=String(w);if(this.credentials=E.credentials||this.credentials||"same-origin",(E.headers||!this.headers)&&(this.headers=new u(E.headers)),this.method=D(E.method||this.method||"GET"),this.mode=E.mode||this.mode||null,this.signal=E.signal||this.signal||(function(){if("AbortController"in e){var V=new AbortController;return V.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&P)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(P),(this.method==="GET"||this.method==="HEAD")&&(E.cache==="no-store"||E.cache==="no-cache")){var q=/([?&])_=[^&]*/;if(q.test(this.url))this.url=this.url.replace(q,"$1_="+new Date().getTime());else{var W=/\?/;this.url+=(W.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})};function S(w){var E=new FormData;return w.trim().split("&").forEach(function(P){if(P){var q=P.split("="),W=q.shift().replace(/\+/g," "),V=q.join("=").replace(/\+/g," ");E.append(decodeURIComponent(W),decodeURIComponent(V))}}),E}function C(w){var E=new u,P=w.replace(/\r?\n[\t ]+/g," ");return P.split("\r").map(function(q){return q.indexOf(`
3
- `)===0?q.substr(1,q.length):q}).forEach(function(q){var W=q.split(":"),V=W.shift().trim();if(V){var pe=W.join(":").trim();try{E.append(V,pe)}catch(me){console.warn("Response "+me.message)}}}),E}y.call(v.prototype);function x(w,E){if(!(this instanceof x))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 u(E.headers),this.url=E.url||"",this._initBody(w)}y.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},x.error=function(){var w=new x(null,{status:200,statusText:""});return w.ok=!1,w.status=0,w.type="error",w};var _=[301,302,303,307,308];x.redirect=function(w,E){if(_.indexOf(E)===-1)throw new RangeError("Invalid status code");return new x(null,{status:E,headers:{location:w}})},t.DOMException=e.DOMException;try{new t.DOMException}catch{t.DOMException=function(E,P){this.message=E,this.name=P;var q=Error(E);this.stack=q.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function B(w,E){return new Promise(function(P,q){var W=new v(w,E);if(W.signal&&W.signal.aborted)return q(new t.DOMException("Aborted","AbortError"));var V=new XMLHttpRequest;function pe(){V.abort()}V.onload=function(){var J={statusText:V.statusText,headers:C(V.getAllResponseHeaders()||"")};W.url.indexOf("file://")===0&&(V.status<200||V.status>599)?J.status=200:J.status=V.status,J.url="responseURL"in V?V.responseURL:J.headers.get("X-Request-URL");var De="response"in V?V.response:V.responseText;setTimeout(function(){P(new x(De,J))},0)},V.onerror=function(){setTimeout(function(){q(new TypeError("Network request failed"))},0)},V.ontimeout=function(){setTimeout(function(){q(new TypeError("Network request timed out"))},0)},V.onabort=function(){setTimeout(function(){q(new t.DOMException("Aborted","AbortError"))},0)};function me(J){try{return J===""&&e.location.href?e.location.href:J}catch{return J}}if(V.open(W.method,me(W.url),!0),W.credentials==="include"?V.withCredentials=!0:W.credentials==="omit"&&(V.withCredentials=!1),"responseType"in V&&(r.blob?V.responseType="blob":r.arrayBuffer&&(V.responseType="arraybuffer")),E&&typeof E.headers=="object"&&!(E.headers instanceof u||e.Headers&&E.headers instanceof e.Headers)){var ve=[];Object.getOwnPropertyNames(E.headers).forEach(function(J){ve.push(a(J)),V.setRequestHeader(J,l(E.headers[J]))}),W.headers.forEach(function(J,De){ve.indexOf(De)===-1&&V.setRequestHeader(De,J)})}else W.headers.forEach(function(J,De){V.setRequestHeader(De,J)});W.signal&&(W.signal.addEventListener("abort",pe),V.onreadystatechange=function(){V.readyState===4&&W.signal.removeEventListener("abort",pe)}),V.send(typeof W._bodyInit>"u"?null:W._bodyInit)})}B.polyfill=!0,e.fetch||(e.fetch=B,e.Headers=u,e.Request=v,e.Response=x),t.Headers=u,t.Request=v,t.Response=x,t.fetch=B,Object.defineProperty(t,"__esModule",{value:!0})}))});var fu=$((nx,du)=>{"use strict";du.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var To=$((ix,pu)=>{var Rn=fu(),hu={};for(let t of Object.keys(Rn))hu[Rn[t]]=t;var M={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};pu.exports=M;for(let t of Object.keys(M)){if(!("channels"in M[t]))throw new Error("missing channels property: "+t);if(!("labels"in M[t]))throw new Error("missing channel labels property: "+t);if(M[t].labels.length!==M[t].channels)throw new Error("channel and label counts mismatch: "+t);let{channels:e,labels:r}=M[t];delete M[t].channels,delete M[t].labels,Object.defineProperty(M[t],"channels",{value:e}),Object.defineProperty(M[t],"labels",{value:r})}M.rgb.hsl=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255,i=Math.min(e,r,n),s=Math.max(e,r,n),a=s-i,l,c;s===i?l=0:e===s?l=(r-n)/a:r===s?l=2+(n-e)/a:n===s&&(l=4+(e-r)/a),l=Math.min(l*60,360),l<0&&(l+=360);let u=(i+s)/2;return s===i?c=0:u<=.5?c=a/(s+i):c=a/(2-s-i),[l,c*100,u*100]};M.rgb.hsv=function(t){let e,r,n,i,s,a=t[0]/255,l=t[1]/255,c=t[2]/255,u=Math.max(a,l,c),h=u-Math.min(a,l,c),f=function(d){return(u-d)/6/h+1/2};return h===0?(i=0,s=0):(s=h/u,e=f(a),r=f(l),n=f(c),a===u?i=n-r:l===u?i=1/3+e-n:c===u&&(i=2/3+r-e),i<0?i+=1:i>1&&(i-=1)),[i*360,s*100,u*100]};M.rgb.hwb=function(t){let e=t[0],r=t[1],n=t[2],i=M.rgb.hsl(t)[0],s=1/255*Math.min(e,Math.min(r,n));return n=1-1/255*Math.max(e,Math.max(r,n)),[i,s*100,n*100]};M.rgb.cmyk=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255,i=Math.min(1-e,1-r,1-n),s=(1-e-i)/(1-i)||0,a=(1-r-i)/(1-i)||0,l=(1-n-i)/(1-i)||0;return[s*100,a*100,l*100,i*100]};function k0(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}M.rgb.keyword=function(t){let e=hu[t];if(e)return e;let r=1/0,n;for(let i of Object.keys(Rn)){let s=Rn[i],a=k0(t,s);a<r&&(r=a,n=i)}return n};M.keyword.rgb=function(t){return Rn[t]};M.rgb.xyz=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;let i=e*.4124+r*.3576+n*.1805,s=e*.2126+r*.7152+n*.0722,a=e*.0193+r*.1192+n*.9505;return[i*100,s*100,a*100]};M.rgb.lab=function(t){let e=M.rgb.xyz(t),r=e[0],n=e[1],i=e[2];r/=95.047,n/=100,i/=108.883,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,i=i>.008856?i**(1/3):7.787*i+16/116;let s=116*n-16,a=500*(r-n),l=200*(n-i);return[s,a,l]};M.hsl.rgb=function(t){let e=t[0]/360,r=t[1]/100,n=t[2]/100,i,s,a;if(r===0)return a=n*255,[a,a,a];n<.5?i=n*(1+r):i=n+r-n*r;let l=2*n-i,c=[0,0,0];for(let u=0;u<3;u++)s=e+1/3*-(u-1),s<0&&s++,s>1&&s--,6*s<1?a=l+(i-l)*6*s:2*s<1?a=i:3*s<2?a=l+(i-l)*(2/3-s)*6:a=l,c[u]=a*255;return c};M.hsl.hsv=function(t){let e=t[0],r=t[1]/100,n=t[2]/100,i=r,s=Math.max(n,.01);n*=2,r*=n<=1?n:2-n,i*=s<=1?s:2-s;let a=(n+r)/2,l=n===0?2*i/(s+i):2*r/(n+r);return[e,l*100,a*100]};M.hsv.rgb=function(t){let e=t[0]/60,r=t[1]/100,n=t[2]/100,i=Math.floor(e)%6,s=e-Math.floor(e),a=255*n*(1-r),l=255*n*(1-r*s),c=255*n*(1-r*(1-s));switch(n*=255,i){case 0:return[n,c,a];case 1:return[l,n,a];case 2:return[a,n,c];case 3:return[a,l,n];case 4:return[c,a,n];case 5:return[n,a,l]}};M.hsv.hsl=function(t){let e=t[0],r=t[1]/100,n=t[2]/100,i=Math.max(n,.01),s,a;a=(2-r)*n;let l=(2-r)*i;return s=r*i,s/=l<=1?l:2-l,s=s||0,a/=2,[e,s*100,a*100]};M.hwb.rgb=function(t){let e=t[0]/360,r=t[1]/100,n=t[2]/100,i=r+n,s;i>1&&(r/=i,n/=i);let a=Math.floor(6*e),l=1-n;s=6*e-a,(a&1)!==0&&(s=1-s);let c=r+s*(l-r),u,h,f;switch(a){default:case 6:case 0:u=l,h=c,f=r;break;case 1:u=c,h=l,f=r;break;case 2:u=r,h=l,f=c;break;case 3:u=r,h=c,f=l;break;case 4:u=c,h=r,f=l;break;case 5:u=l,h=r,f=c;break}return[u*255,h*255,f*255]};M.cmyk.rgb=function(t){let e=t[0]/100,r=t[1]/100,n=t[2]/100,i=t[3]/100,s=1-Math.min(1,e*(1-i)+i),a=1-Math.min(1,r*(1-i)+i),l=1-Math.min(1,n*(1-i)+i);return[s*255,a*255,l*255]};M.xyz.rgb=function(t){let e=t[0]/100,r=t[1]/100,n=t[2]/100,i,s,a;return i=e*3.2406+r*-1.5372+n*-.4986,s=e*-.9689+r*1.8758+n*.0415,a=e*.0557+r*-.204+n*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,i=Math.min(Math.max(0,i),1),s=Math.min(Math.max(0,s),1),a=Math.min(Math.max(0,a),1),[i*255,s*255,a*255]};M.xyz.lab=function(t){let e=t[0],r=t[1],n=t[2];e/=95.047,r/=100,n/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let i=116*r-16,s=500*(e-r),a=200*(r-n);return[i,s,a]};M.lab.xyz=function(t){let e=t[0],r=t[1],n=t[2],i,s,a;s=(e+16)/116,i=r/500+s,a=s-n/200;let l=s**3,c=i**3,u=a**3;return s=l>.008856?l:(s-16/116)/7.787,i=c>.008856?c:(i-16/116)/7.787,a=u>.008856?u:(a-16/116)/7.787,i*=95.047,s*=100,a*=108.883,[i,s,a]};M.lab.lch=function(t){let e=t[0],r=t[1],n=t[2],i;i=Math.atan2(n,r)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(r*r+n*n);return[e,a,i]};M.lch.lab=function(t){let e=t[0],r=t[1],i=t[2]/360*2*Math.PI,s=r*Math.cos(i),a=r*Math.sin(i);return[e,s,a]};M.rgb.ansi16=function(t,e=null){let[r,n,i]=t,s=e===null?M.rgb.hsv(t)[2]:e;if(s=Math.round(s/50),s===0)return 30;let a=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(r/255));return s===2&&(a+=60),a};M.hsv.ansi16=function(t){return M.rgb.ansi16(M.hsv.rgb(t),t[2])};M.rgb.ansi256=function(t){let e=t[0],r=t[1],n=t[2];return e===r&&r===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)};M.ansi16.rgb=function(t){let e=t%10;if(e===0||e===7)return t>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let r=(~~(t>50)+1)*.5,n=(e&1)*r*255,i=(e>>1&1)*r*255,s=(e>>2&1)*r*255;return[n,i,s]};M.ansi256.rgb=function(t){if(t>=232){let s=(t-232)*10+8;return[s,s,s]}t-=16;let e,r=Math.floor(t/36)/5*255,n=Math.floor((e=t%36)/6)/5*255,i=e%6/5*255;return[r,n,i]};M.rgb.hex=function(t){let r=(((Math.round(t[0])&255)<<16)+((Math.round(t[1])&255)<<8)+(Math.round(t[2])&255)).toString(16).toUpperCase();return"000000".substring(r.length)+r};M.hex.rgb=function(t){let e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let r=e[0];e[0].length===3&&(r=r.split("").map(l=>l+l).join(""));let n=parseInt(r,16),i=n>>16&255,s=n>>8&255,a=n&255;return[i,s,a]};M.rgb.hcg=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255,i=Math.max(Math.max(e,r),n),s=Math.min(Math.min(e,r),n),a=i-s,l,c;return a<1?l=s/(1-a):l=0,a<=0?c=0:i===e?c=(r-n)/a%6:i===r?c=2+(n-e)/a:c=4+(e-r)/a,c/=6,c%=1,[c*360,a*100,l*100]};M.hsl.hcg=function(t){let e=t[1]/100,r=t[2]/100,n=r<.5?2*e*r:2*e*(1-r),i=0;return n<1&&(i=(r-.5*n)/(1-n)),[t[0],n*100,i*100]};M.hsv.hcg=function(t){let e=t[1]/100,r=t[2]/100,n=e*r,i=0;return n<1&&(i=(r-n)/(1-n)),[t[0],n*100,i*100]};M.hcg.rgb=function(t){let e=t[0]/360,r=t[1]/100,n=t[2]/100;if(r===0)return[n*255,n*255,n*255];let i=[0,0,0],s=e%1*6,a=s%1,l=1-a,c=0;switch(Math.floor(s)){case 0:i[0]=1,i[1]=a,i[2]=0;break;case 1:i[0]=l,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=a;break;case 3:i[0]=0,i[1]=l,i[2]=1;break;case 4:i[0]=a,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=l}return c=(1-r)*n,[(r*i[0]+c)*255,(r*i[1]+c)*255,(r*i[2]+c)*255]};M.hcg.hsv=function(t){let e=t[1]/100,r=t[2]/100,n=e+r*(1-e),i=0;return n>0&&(i=e/n),[t[0],i*100,n*100]};M.hcg.hsl=function(t){let e=t[1]/100,n=t[2]/100*(1-e)+.5*e,i=0;return n>0&&n<.5?i=e/(2*n):n>=.5&&n<1&&(i=e/(2*(1-n))),[t[0],i*100,n*100]};M.hcg.hwb=function(t){let e=t[1]/100,r=t[2]/100,n=e+r*(1-e);return[t[0],(n-e)*100,(1-n)*100]};M.hwb.hcg=function(t){let e=t[1]/100,n=1-t[2]/100,i=n-e,s=0;return i<1&&(s=(n-i)/(1-i)),[t[0],i*100,s*100]};M.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};M.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};M.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};M.gray.hsl=function(t){return[0,0,t[0]]};M.gray.hsv=M.gray.hsl;M.gray.hwb=function(t){return[0,100,t[0]]};M.gray.cmyk=function(t){return[0,0,0,t[0]]};M.gray.lab=function(t){return[t[0],0,0]};M.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,n=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(n.length)+n};M.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}});var gu=$((sx,mu)=>{var $i=To();function F0(){let t={},e=Object.keys($i);for(let r=e.length,n=0;n<r;n++)t[e[n]]={distance:-1,parent:null};return t}function P0(t){let e=F0(),r=[t];for(e[t].distance=0;r.length;){let n=r.pop(),i=Object.keys($i[n]);for(let s=i.length,a=0;a<s;a++){let l=i[a],c=e[l];c.distance===-1&&(c.distance=e[n].distance+1,c.parent=n,r.unshift(l))}}return e}function T0(t,e){return function(r){return e(t(r))}}function A0(t,e){let r=[e[t].parent,t],n=$i[e[t].parent][t],i=e[t].parent;for(;e[i].parent;)r.unshift(e[i].parent),n=T0($i[e[i].parent][i],n),i=e[i].parent;return n.conversion=r,n}mu.exports=function(t){let e=P0(t),r={},n=Object.keys(e);for(let i=n.length,s=0;s<i;s++){let a=n[s];e[a].parent!==null&&(r[a]=A0(a,e))}return r}});var bu=$((ox,yu)=>{var Ao=To(),O0=gu(),Yr={},I0=Object.keys(Ao);function R0(t){let e=function(...r){let n=r[0];return n==null?n:(n.length>1&&(r=n),t(r))};return"conversion"in t&&(e.conversion=t.conversion),e}function M0(t){let e=function(...r){let n=r[0];if(n==null)return n;n.length>1&&(r=n);let i=t(r);if(typeof i=="object")for(let s=i.length,a=0;a<s;a++)i[a]=Math.round(i[a]);return i};return"conversion"in t&&(e.conversion=t.conversion),e}I0.forEach(t=>{Yr[t]={},Object.defineProperty(Yr[t],"channels",{value:Ao[t].channels}),Object.defineProperty(Yr[t],"labels",{value:Ao[t].labels});let e=O0(t);Object.keys(e).forEach(n=>{let i=e[n];Yr[t][n]=M0(i),Yr[t][n].raw=R0(i)})});yu.exports=Yr});var Eu=$((ax,Cu)=>{"use strict";var vu=(t,e)=>(...r)=>`\x1B[${t(...r)+e}m`,Du=(t,e)=>(...r)=>{let n=t(...r);return`\x1B[${38+e};5;${n}m`},wu=(t,e)=>(...r)=>{let n=t(...r);return`\x1B[${38+e};2;${n[0]};${n[1]};${n[2]}m`},Ui=t=>t,Su=(t,e,r)=>[t,e,r],Jr=(t,e,r)=>{Object.defineProperty(t,e,{get:()=>{let n=r();return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})},Oo,Qr=(t,e,r,n)=>{Oo===void 0&&(Oo=bu());let i=n?10:0,s={};for(let[a,l]of Object.entries(Oo)){let c=a==="ansi16"?"ansi":a;a===e?s[c]=t(r,i):typeof l=="object"&&(s[c]=t(l[e],i))}return s};function j0(){let t=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[r,n]of Object.entries(e)){for(let[i,s]of Object.entries(n))e[i]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[i]=e[i],t.set(s[0],s[1]);Object.defineProperty(e,r,{value:n,enumerable:!1})}return Object.defineProperty(e,"codes",{value:t,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",Jr(e.color,"ansi",()=>Qr(vu,"ansi16",Ui,!1)),Jr(e.color,"ansi256",()=>Qr(Du,"ansi256",Ui,!1)),Jr(e.color,"ansi16m",()=>Qr(wu,"rgb",Su,!1)),Jr(e.bgColor,"ansi",()=>Qr(vu,"ansi16",Ui,!0)),Jr(e.bgColor,"ansi256",()=>Qr(Du,"ansi256",Ui,!0)),Jr(e.bgColor,"ansi16m",()=>Qr(wu,"rgb",Su,!0)),e}Object.defineProperty(Cu,"exports",{enumerable:!0,get:j0})});var xu=$((lx,_u)=>{"use strict";_u.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),i=e.indexOf("--");return n!==-1&&(i===-1||n<i)}});var Pu=$((cx,Fu)=>{"use strict";var B0=require("os"),ku=require("tty"),Ne=xu(),{env:ue}=process,jt;Ne("no-color")||Ne("no-colors")||Ne("color=false")||Ne("color=never")?jt=0:(Ne("color")||Ne("colors")||Ne("color=true")||Ne("color=always"))&&(jt=1);"FORCE_COLOR"in ue&&(ue.FORCE_COLOR==="true"?jt=1:ue.FORCE_COLOR==="false"?jt=0:jt=ue.FORCE_COLOR.length===0?1:Math.min(parseInt(ue.FORCE_COLOR,10),3));function Io(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Ro(t,e){if(jt===0)return 0;if(Ne("color=16m")||Ne("color=full")||Ne("color=truecolor"))return 3;if(Ne("color=256"))return 2;if(t&&!e&&jt===void 0)return 0;let r=jt||0;if(ue.TERM==="dumb")return r;if(process.platform==="win32"){let n=B0.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in ue)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in ue)||ue.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in ue)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ue.TEAMCITY_VERSION)?1:0;if(ue.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ue){let n=parseInt((ue.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ue.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ue.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ue.TERM)||"COLORTERM"in ue?1:r}function L0(t){let e=Ro(t,t&&t.isTTY);return Io(e)}Fu.exports={supportsColor:L0,stdout:Io(Ro(!0,ku.isatty(1))),stderr:Io(Ro(!0,ku.isatty(2)))}});var Au=$((ux,Tu)=>{"use strict";var N0=(t,e,r)=>{let n=t.indexOf(e);if(n===-1)return t;let i=e.length,s=0,a="";do a+=t.substr(s,n-s)+e+r,s=n+i,n=t.indexOf(e,s);while(n!==-1);return a+=t.substr(s),a},$0=(t,e,r,n)=>{let i=0,s="";do{let a=t[n-1]==="\r";s+=t.substr(i,(a?n-1:n)-i)+e+(a?`\r
2
+ "use strict";var ey=Object.create;var yo=Object.defineProperty;var ty=Object.getOwnPropertyDescriptor;var ry=Object.getOwnPropertyNames;var ny=Object.getPrototypeOf,iy=Object.prototype.hasOwnProperty;var $=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),sy=(t,e)=>{for(var r in e)yo(t,r,{get:e[r],enumerable:!0})},oy=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ry(e))!iy.call(t,i)&&i!==r&&yo(t,i,{get:()=>e[i],enumerable:!(n=ty(e,i))||n.enumerable});return t};var je=(t,e,r)=>(r=t!=null?ey(ny(t)):{},oy(e||!t||!t.__esModule?yo(r,"default",{value:t,enumerable:!0}):r,t));var bo=$((Ri,Qc)=>{(function(t,e){typeof Ri=="object"&&typeof Qc<"u"?e(Ri):typeof define=="function"&&define.amd?define(["exports"],e):e(t.WHATWGFetch={})})(Ri,(function(t){"use strict";var e=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},r={searchParams:"URLSearchParams"in e,iterable:"Symbol"in e&&"iterator"in Symbol,blob:"FileReader"in e&&"Blob"in e&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in e,arrayBuffer:"ArrayBuffer"in e};function n(w){return w&&DataView.prototype.isPrototypeOf(w)}if(r.arrayBuffer)var i=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],s=ArrayBuffer.isView||function(w){return w&&i.indexOf(Object.prototype.toString.call(w))>-1};function a(w){if(typeof w!="string"&&(w=String(w)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(w)||w==="")throw new TypeError('Invalid character in header field name: "'+w+'"');return w.toLowerCase()}function l(w){return typeof w!="string"&&(w=String(w)),w}function c(w){var E={next:function(){var P=w.shift();return{done:P===void 0,value:P}}};return r.iterable&&(E[Symbol.iterator]=function(){return E}),E}function u(w){this.map={},w instanceof u?w.forEach(function(E,P){this.append(P,E)},this):Array.isArray(w)?w.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):w&&Object.getOwnPropertyNames(w).forEach(function(E){this.append(E,w[E])},this)}u.prototype.append=function(w,E){w=a(w),E=l(E);var P=this.map[w];this.map[w]=P?P+", "+E:E},u.prototype.delete=function(w){delete this.map[a(w)]},u.prototype.get=function(w){return w=a(w),this.has(w)?this.map[w]:null},u.prototype.has=function(w){return this.map.hasOwnProperty(a(w))},u.prototype.set=function(w,E){this.map[a(w)]=l(E)},u.prototype.forEach=function(w,E){for(var P in this.map)this.map.hasOwnProperty(P)&&w.call(E,this.map[P],P,this)},u.prototype.keys=function(){var w=[];return this.forEach(function(E,P){w.push(P)}),c(w)},u.prototype.values=function(){var w=[];return this.forEach(function(E){w.push(E)}),c(w)},u.prototype.entries=function(){var w=[];return this.forEach(function(E,P){w.push([P,E])}),c(w)},r.iterable&&(u.prototype[Symbol.iterator]=u.prototype.entries);function h(w){if(!w._noBody){if(w.bodyUsed)return Promise.reject(new TypeError("Already read"));w.bodyUsed=!0}}function f(w){return new Promise(function(E,P){w.onload=function(){E(w.result)},w.onerror=function(){P(w.error)}})}function d(w){var E=new FileReader,P=f(E);return E.readAsArrayBuffer(w),P}function p(w){var E=new FileReader,P=f(E),q=/charset=([A-Za-z0-9_-]+)/.exec(w.type),W=q?q[1]:"utf-8";return E.readAsText(w,W),P}function m(w){for(var E=new Uint8Array(w),P=new Array(E.length),q=0;q<E.length;q++)P[q]=String.fromCharCode(E[q]);return P.join("")}function g(w){if(w.slice)return w.slice(0);var E=new Uint8Array(w.byteLength);return E.set(new Uint8Array(w)),E.buffer}function y(){return this.bodyUsed=!1,this._initBody=function(w){this.bodyUsed=this.bodyUsed,this._bodyInit=w,w?typeof w=="string"?this._bodyText=w:r.blob&&Blob.prototype.isPrototypeOf(w)?this._bodyBlob=w:r.formData&&FormData.prototype.isPrototypeOf(w)?this._bodyFormData=w:r.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)?this._bodyText=w.toString():r.arrayBuffer&&r.blob&&n(w)?(this._bodyArrayBuffer=g(w.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(w)||s(w))?this._bodyArrayBuffer=g(w):this._bodyText=w=Object.prototype.toString.call(w):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof w=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},r.blob&&(this.blob=function(){var w=h(this);if(w)return w;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 w=h(this);return w||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(r.blob)return this.blob().then(d);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var w=h(this);if(w)return w;if(this._bodyBlob)return p(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(m(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r.formData&&(this.formData=function(){return this.text().then(S)}),this.json=function(){return this.text().then(JSON.parse)},this}var b=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function D(w){var E=w.toUpperCase();return b.indexOf(E)>-1?E:w}function v(w,E){if(!(this instanceof v))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');E=E||{};var P=E.body;if(w instanceof v){if(w.bodyUsed)throw new TypeError("Already read");this.url=w.url,this.credentials=w.credentials,E.headers||(this.headers=new u(w.headers)),this.method=w.method,this.mode=w.mode,this.signal=w.signal,!P&&w._bodyInit!=null&&(P=w._bodyInit,w.bodyUsed=!0)}else this.url=String(w);if(this.credentials=E.credentials||this.credentials||"same-origin",(E.headers||!this.headers)&&(this.headers=new u(E.headers)),this.method=D(E.method||this.method||"GET"),this.mode=E.mode||this.mode||null,this.signal=E.signal||this.signal||(function(){if("AbortController"in e){var V=new AbortController;return V.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&P)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(P),(this.method==="GET"||this.method==="HEAD")&&(E.cache==="no-store"||E.cache==="no-cache")){var q=/([?&])_=[^&]*/;if(q.test(this.url))this.url=this.url.replace(q,"$1_="+new Date().getTime());else{var W=/\?/;this.url+=(W.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})};function S(w){var E=new FormData;return w.trim().split("&").forEach(function(P){if(P){var q=P.split("="),W=q.shift().replace(/\+/g," "),V=q.join("=").replace(/\+/g," ");E.append(decodeURIComponent(W),decodeURIComponent(V))}}),E}function C(w){var E=new u,P=w.replace(/\r?\n[\t ]+/g," ");return P.split("\r").map(function(q){return q.indexOf(`
3
+ `)===0?q.substr(1,q.length):q}).forEach(function(q){var W=q.split(":"),V=W.shift().trim();if(V){var pe=W.join(":").trim();try{E.append(V,pe)}catch(me){console.warn("Response "+me.message)}}}),E}y.call(v.prototype);function x(w,E){if(!(this instanceof x))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 u(E.headers),this.url=E.url||"",this._initBody(w)}y.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},x.error=function(){var w=new x(null,{status:200,statusText:""});return w.ok=!1,w.status=0,w.type="error",w};var _=[301,302,303,307,308];x.redirect=function(w,E){if(_.indexOf(E)===-1)throw new RangeError("Invalid status code");return new x(null,{status:E,headers:{location:w}})},t.DOMException=e.DOMException;try{new t.DOMException}catch{t.DOMException=function(E,P){this.message=E,this.name=P;var q=Error(E);this.stack=q.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function B(w,E){return new Promise(function(P,q){var W=new v(w,E);if(W.signal&&W.signal.aborted)return q(new t.DOMException("Aborted","AbortError"));var V=new XMLHttpRequest;function pe(){V.abort()}V.onload=function(){var J={statusText:V.statusText,headers:C(V.getAllResponseHeaders()||"")};W.url.indexOf("file://")===0&&(V.status<200||V.status>599)?J.status=200:J.status=V.status,J.url="responseURL"in V?V.responseURL:J.headers.get("X-Request-URL");var De="response"in V?V.response:V.responseText;setTimeout(function(){P(new x(De,J))},0)},V.onerror=function(){setTimeout(function(){q(new TypeError("Network request failed"))},0)},V.ontimeout=function(){setTimeout(function(){q(new TypeError("Network request timed out"))},0)},V.onabort=function(){setTimeout(function(){q(new t.DOMException("Aborted","AbortError"))},0)};function me(J){try{return J===""&&e.location.href?e.location.href:J}catch{return J}}if(V.open(W.method,me(W.url),!0),W.credentials==="include"?V.withCredentials=!0:W.credentials==="omit"&&(V.withCredentials=!1),"responseType"in V&&(r.blob?V.responseType="blob":r.arrayBuffer&&(V.responseType="arraybuffer")),E&&typeof E.headers=="object"&&!(E.headers instanceof u||e.Headers&&E.headers instanceof e.Headers)){var ve=[];Object.getOwnPropertyNames(E.headers).forEach(function(J){ve.push(a(J)),V.setRequestHeader(J,l(E.headers[J]))}),W.headers.forEach(function(J,De){ve.indexOf(De)===-1&&V.setRequestHeader(De,J)})}else W.headers.forEach(function(J,De){V.setRequestHeader(De,J)});W.signal&&(W.signal.addEventListener("abort",pe),V.onreadystatechange=function(){V.readyState===4&&W.signal.removeEventListener("abort",pe)}),V.send(typeof W._bodyInit>"u"?null:W._bodyInit)})}B.polyfill=!0,e.fetch||(e.fetch=B,e.Headers=u,e.Request=v,e.Response=x),t.Headers=u,t.Request=v,t.Response=x,t.fetch=B,Object.defineProperty(t,"__esModule",{value:!0})}))});var hu=$((ix,fu)=>{"use strict";fu.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var Ao=$((sx,mu)=>{var Rn=hu(),pu={};for(let t of Object.keys(Rn))pu[Rn[t]]=t;var M={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};mu.exports=M;for(let t of Object.keys(M)){if(!("channels"in M[t]))throw new Error("missing channels property: "+t);if(!("labels"in M[t]))throw new Error("missing channel labels property: "+t);if(M[t].labels.length!==M[t].channels)throw new Error("channel and label counts mismatch: "+t);let{channels:e,labels:r}=M[t];delete M[t].channels,delete M[t].labels,Object.defineProperty(M[t],"channels",{value:e}),Object.defineProperty(M[t],"labels",{value:r})}M.rgb.hsl=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255,i=Math.min(e,r,n),s=Math.max(e,r,n),a=s-i,l,c;s===i?l=0:e===s?l=(r-n)/a:r===s?l=2+(n-e)/a:n===s&&(l=4+(e-r)/a),l=Math.min(l*60,360),l<0&&(l+=360);let u=(i+s)/2;return s===i?c=0:u<=.5?c=a/(s+i):c=a/(2-s-i),[l,c*100,u*100]};M.rgb.hsv=function(t){let e,r,n,i,s,a=t[0]/255,l=t[1]/255,c=t[2]/255,u=Math.max(a,l,c),h=u-Math.min(a,l,c),f=function(d){return(u-d)/6/h+1/2};return h===0?(i=0,s=0):(s=h/u,e=f(a),r=f(l),n=f(c),a===u?i=n-r:l===u?i=1/3+e-n:c===u&&(i=2/3+r-e),i<0?i+=1:i>1&&(i-=1)),[i*360,s*100,u*100]};M.rgb.hwb=function(t){let e=t[0],r=t[1],n=t[2],i=M.rgb.hsl(t)[0],s=1/255*Math.min(e,Math.min(r,n));return n=1-1/255*Math.max(e,Math.max(r,n)),[i,s*100,n*100]};M.rgb.cmyk=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255,i=Math.min(1-e,1-r,1-n),s=(1-e-i)/(1-i)||0,a=(1-r-i)/(1-i)||0,l=(1-n-i)/(1-i)||0;return[s*100,a*100,l*100,i*100]};function F0(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}M.rgb.keyword=function(t){let e=pu[t];if(e)return e;let r=1/0,n;for(let i of Object.keys(Rn)){let s=Rn[i],a=F0(t,s);a<r&&(r=a,n=i)}return n};M.keyword.rgb=function(t){return Rn[t]};M.rgb.xyz=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;let i=e*.4124+r*.3576+n*.1805,s=e*.2126+r*.7152+n*.0722,a=e*.0193+r*.1192+n*.9505;return[i*100,s*100,a*100]};M.rgb.lab=function(t){let e=M.rgb.xyz(t),r=e[0],n=e[1],i=e[2];r/=95.047,n/=100,i/=108.883,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,i=i>.008856?i**(1/3):7.787*i+16/116;let s=116*n-16,a=500*(r-n),l=200*(n-i);return[s,a,l]};M.hsl.rgb=function(t){let e=t[0]/360,r=t[1]/100,n=t[2]/100,i,s,a;if(r===0)return a=n*255,[a,a,a];n<.5?i=n*(1+r):i=n+r-n*r;let l=2*n-i,c=[0,0,0];for(let u=0;u<3;u++)s=e+1/3*-(u-1),s<0&&s++,s>1&&s--,6*s<1?a=l+(i-l)*6*s:2*s<1?a=i:3*s<2?a=l+(i-l)*(2/3-s)*6:a=l,c[u]=a*255;return c};M.hsl.hsv=function(t){let e=t[0],r=t[1]/100,n=t[2]/100,i=r,s=Math.max(n,.01);n*=2,r*=n<=1?n:2-n,i*=s<=1?s:2-s;let a=(n+r)/2,l=n===0?2*i/(s+i):2*r/(n+r);return[e,l*100,a*100]};M.hsv.rgb=function(t){let e=t[0]/60,r=t[1]/100,n=t[2]/100,i=Math.floor(e)%6,s=e-Math.floor(e),a=255*n*(1-r),l=255*n*(1-r*s),c=255*n*(1-r*(1-s));switch(n*=255,i){case 0:return[n,c,a];case 1:return[l,n,a];case 2:return[a,n,c];case 3:return[a,l,n];case 4:return[c,a,n];case 5:return[n,a,l]}};M.hsv.hsl=function(t){let e=t[0],r=t[1]/100,n=t[2]/100,i=Math.max(n,.01),s,a;a=(2-r)*n;let l=(2-r)*i;return s=r*i,s/=l<=1?l:2-l,s=s||0,a/=2,[e,s*100,a*100]};M.hwb.rgb=function(t){let e=t[0]/360,r=t[1]/100,n=t[2]/100,i=r+n,s;i>1&&(r/=i,n/=i);let a=Math.floor(6*e),l=1-n;s=6*e-a,(a&1)!==0&&(s=1-s);let c=r+s*(l-r),u,h,f;switch(a){default:case 6:case 0:u=l,h=c,f=r;break;case 1:u=c,h=l,f=r;break;case 2:u=r,h=l,f=c;break;case 3:u=r,h=c,f=l;break;case 4:u=c,h=r,f=l;break;case 5:u=l,h=r,f=c;break}return[u*255,h*255,f*255]};M.cmyk.rgb=function(t){let e=t[0]/100,r=t[1]/100,n=t[2]/100,i=t[3]/100,s=1-Math.min(1,e*(1-i)+i),a=1-Math.min(1,r*(1-i)+i),l=1-Math.min(1,n*(1-i)+i);return[s*255,a*255,l*255]};M.xyz.rgb=function(t){let e=t[0]/100,r=t[1]/100,n=t[2]/100,i,s,a;return i=e*3.2406+r*-1.5372+n*-.4986,s=e*-.9689+r*1.8758+n*.0415,a=e*.0557+r*-.204+n*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,i=Math.min(Math.max(0,i),1),s=Math.min(Math.max(0,s),1),a=Math.min(Math.max(0,a),1),[i*255,s*255,a*255]};M.xyz.lab=function(t){let e=t[0],r=t[1],n=t[2];e/=95.047,r/=100,n/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let i=116*r-16,s=500*(e-r),a=200*(r-n);return[i,s,a]};M.lab.xyz=function(t){let e=t[0],r=t[1],n=t[2],i,s,a;s=(e+16)/116,i=r/500+s,a=s-n/200;let l=s**3,c=i**3,u=a**3;return s=l>.008856?l:(s-16/116)/7.787,i=c>.008856?c:(i-16/116)/7.787,a=u>.008856?u:(a-16/116)/7.787,i*=95.047,s*=100,a*=108.883,[i,s,a]};M.lab.lch=function(t){let e=t[0],r=t[1],n=t[2],i;i=Math.atan2(n,r)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(r*r+n*n);return[e,a,i]};M.lch.lab=function(t){let e=t[0],r=t[1],i=t[2]/360*2*Math.PI,s=r*Math.cos(i),a=r*Math.sin(i);return[e,s,a]};M.rgb.ansi16=function(t,e=null){let[r,n,i]=t,s=e===null?M.rgb.hsv(t)[2]:e;if(s=Math.round(s/50),s===0)return 30;let a=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(r/255));return s===2&&(a+=60),a};M.hsv.ansi16=function(t){return M.rgb.ansi16(M.hsv.rgb(t),t[2])};M.rgb.ansi256=function(t){let e=t[0],r=t[1],n=t[2];return e===r&&r===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)};M.ansi16.rgb=function(t){let e=t%10;if(e===0||e===7)return t>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let r=(~~(t>50)+1)*.5,n=(e&1)*r*255,i=(e>>1&1)*r*255,s=(e>>2&1)*r*255;return[n,i,s]};M.ansi256.rgb=function(t){if(t>=232){let s=(t-232)*10+8;return[s,s,s]}t-=16;let e,r=Math.floor(t/36)/5*255,n=Math.floor((e=t%36)/6)/5*255,i=e%6/5*255;return[r,n,i]};M.rgb.hex=function(t){let r=(((Math.round(t[0])&255)<<16)+((Math.round(t[1])&255)<<8)+(Math.round(t[2])&255)).toString(16).toUpperCase();return"000000".substring(r.length)+r};M.hex.rgb=function(t){let e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let r=e[0];e[0].length===3&&(r=r.split("").map(l=>l+l).join(""));let n=parseInt(r,16),i=n>>16&255,s=n>>8&255,a=n&255;return[i,s,a]};M.rgb.hcg=function(t){let e=t[0]/255,r=t[1]/255,n=t[2]/255,i=Math.max(Math.max(e,r),n),s=Math.min(Math.min(e,r),n),a=i-s,l,c;return a<1?l=s/(1-a):l=0,a<=0?c=0:i===e?c=(r-n)/a%6:i===r?c=2+(n-e)/a:c=4+(e-r)/a,c/=6,c%=1,[c*360,a*100,l*100]};M.hsl.hcg=function(t){let e=t[1]/100,r=t[2]/100,n=r<.5?2*e*r:2*e*(1-r),i=0;return n<1&&(i=(r-.5*n)/(1-n)),[t[0],n*100,i*100]};M.hsv.hcg=function(t){let e=t[1]/100,r=t[2]/100,n=e*r,i=0;return n<1&&(i=(r-n)/(1-n)),[t[0],n*100,i*100]};M.hcg.rgb=function(t){let e=t[0]/360,r=t[1]/100,n=t[2]/100;if(r===0)return[n*255,n*255,n*255];let i=[0,0,0],s=e%1*6,a=s%1,l=1-a,c=0;switch(Math.floor(s)){case 0:i[0]=1,i[1]=a,i[2]=0;break;case 1:i[0]=l,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=a;break;case 3:i[0]=0,i[1]=l,i[2]=1;break;case 4:i[0]=a,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=l}return c=(1-r)*n,[(r*i[0]+c)*255,(r*i[1]+c)*255,(r*i[2]+c)*255]};M.hcg.hsv=function(t){let e=t[1]/100,r=t[2]/100,n=e+r*(1-e),i=0;return n>0&&(i=e/n),[t[0],i*100,n*100]};M.hcg.hsl=function(t){let e=t[1]/100,n=t[2]/100*(1-e)+.5*e,i=0;return n>0&&n<.5?i=e/(2*n):n>=.5&&n<1&&(i=e/(2*(1-n))),[t[0],i*100,n*100]};M.hcg.hwb=function(t){let e=t[1]/100,r=t[2]/100,n=e+r*(1-e);return[t[0],(n-e)*100,(1-n)*100]};M.hwb.hcg=function(t){let e=t[1]/100,n=1-t[2]/100,i=n-e,s=0;return i<1&&(s=(n-i)/(1-i)),[t[0],i*100,s*100]};M.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};M.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};M.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};M.gray.hsl=function(t){return[0,0,t[0]]};M.gray.hsv=M.gray.hsl;M.gray.hwb=function(t){return[0,100,t[0]]};M.gray.cmyk=function(t){return[0,0,0,t[0]]};M.gray.lab=function(t){return[t[0],0,0]};M.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,n=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(n.length)+n};M.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}});var yu=$((ox,gu)=>{var $i=Ao();function P0(){let t={},e=Object.keys($i);for(let r=e.length,n=0;n<r;n++)t[e[n]]={distance:-1,parent:null};return t}function T0(t){let e=P0(),r=[t];for(e[t].distance=0;r.length;){let n=r.pop(),i=Object.keys($i[n]);for(let s=i.length,a=0;a<s;a++){let l=i[a],c=e[l];c.distance===-1&&(c.distance=e[n].distance+1,c.parent=n,r.unshift(l))}}return e}function A0(t,e){return function(r){return e(t(r))}}function O0(t,e){let r=[e[t].parent,t],n=$i[e[t].parent][t],i=e[t].parent;for(;e[i].parent;)r.unshift(e[i].parent),n=A0($i[e[i].parent][i],n),i=e[i].parent;return n.conversion=r,n}gu.exports=function(t){let e=T0(t),r={},n=Object.keys(e);for(let i=n.length,s=0;s<i;s++){let a=n[s];e[a].parent!==null&&(r[a]=O0(a,e))}return r}});var vu=$((ax,bu)=>{var Oo=Ao(),I0=yu(),Yr={},R0=Object.keys(Oo);function M0(t){let e=function(...r){let n=r[0];return n==null?n:(n.length>1&&(r=n),t(r))};return"conversion"in t&&(e.conversion=t.conversion),e}function j0(t){let e=function(...r){let n=r[0];if(n==null)return n;n.length>1&&(r=n);let i=t(r);if(typeof i=="object")for(let s=i.length,a=0;a<s;a++)i[a]=Math.round(i[a]);return i};return"conversion"in t&&(e.conversion=t.conversion),e}R0.forEach(t=>{Yr[t]={},Object.defineProperty(Yr[t],"channels",{value:Oo[t].channels}),Object.defineProperty(Yr[t],"labels",{value:Oo[t].labels});let e=I0(t);Object.keys(e).forEach(n=>{let i=e[n];Yr[t][n]=j0(i),Yr[t][n].raw=M0(i)})});bu.exports=Yr});var _u=$((lx,Eu)=>{"use strict";var Du=(t,e)=>(...r)=>`\x1B[${t(...r)+e}m`,wu=(t,e)=>(...r)=>{let n=t(...r);return`\x1B[${38+e};5;${n}m`},Su=(t,e)=>(...r)=>{let n=t(...r);return`\x1B[${38+e};2;${n[0]};${n[1]};${n[2]}m`},Ui=t=>t,Cu=(t,e,r)=>[t,e,r],Jr=(t,e,r)=>{Object.defineProperty(t,e,{get:()=>{let n=r();return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})},Io,Qr=(t,e,r,n)=>{Io===void 0&&(Io=vu());let i=n?10:0,s={};for(let[a,l]of Object.entries(Io)){let c=a==="ansi16"?"ansi":a;a===e?s[c]=t(r,i):typeof l=="object"&&(s[c]=t(l[e],i))}return s};function B0(){let t=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[r,n]of Object.entries(e)){for(let[i,s]of Object.entries(n))e[i]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[i]=e[i],t.set(s[0],s[1]);Object.defineProperty(e,r,{value:n,enumerable:!1})}return Object.defineProperty(e,"codes",{value:t,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",Jr(e.color,"ansi",()=>Qr(Du,"ansi16",Ui,!1)),Jr(e.color,"ansi256",()=>Qr(wu,"ansi256",Ui,!1)),Jr(e.color,"ansi16m",()=>Qr(Su,"rgb",Cu,!1)),Jr(e.bgColor,"ansi",()=>Qr(Du,"ansi16",Ui,!0)),Jr(e.bgColor,"ansi256",()=>Qr(wu,"ansi256",Ui,!0)),Jr(e.bgColor,"ansi16m",()=>Qr(Su,"rgb",Cu,!0)),e}Object.defineProperty(Eu,"exports",{enumerable:!0,get:B0})});var ku=$((cx,xu)=>{"use strict";xu.exports=(t,e=process.argv)=>{let r=t.startsWith("-")?"":t.length===1?"-":"--",n=e.indexOf(r+t),i=e.indexOf("--");return n!==-1&&(i===-1||n<i)}});var Tu=$((ux,Pu)=>{"use strict";var L0=require("os"),Fu=require("tty"),$e=ku(),{env:ue}=process,jt;$e("no-color")||$e("no-colors")||$e("color=false")||$e("color=never")?jt=0:($e("color")||$e("colors")||$e("color=true")||$e("color=always"))&&(jt=1);"FORCE_COLOR"in ue&&(ue.FORCE_COLOR==="true"?jt=1:ue.FORCE_COLOR==="false"?jt=0:jt=ue.FORCE_COLOR.length===0?1:Math.min(parseInt(ue.FORCE_COLOR,10),3));function Ro(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Mo(t,e){if(jt===0)return 0;if($e("color=16m")||$e("color=full")||$e("color=truecolor"))return 3;if($e("color=256"))return 2;if(t&&!e&&jt===void 0)return 0;let r=jt||0;if(ue.TERM==="dumb")return r;if(process.platform==="win32"){let n=L0.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in ue)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in ue)||ue.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in ue)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ue.TEAMCITY_VERSION)?1:0;if(ue.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ue){let n=parseInt((ue.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ue.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ue.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ue.TERM)||"COLORTERM"in ue?1:r}function N0(t){let e=Mo(t,t&&t.isTTY);return Ro(e)}Pu.exports={supportsColor:N0,stdout:Ro(Mo(!0,Fu.isatty(1))),stderr:Ro(Mo(!0,Fu.isatty(2)))}});var Ou=$((dx,Au)=>{"use strict";var $0=(t,e,r)=>{let n=t.indexOf(e);if(n===-1)return t;let i=e.length,s=0,a="";do a+=t.substr(s,n-s)+e+r,s=n+i,n=t.indexOf(e,s);while(n!==-1);return a+=t.substr(s),a},U0=(t,e,r,n)=>{let i=0,s="";do{let a=t[n-1]==="\r";s+=t.substr(i,(a?n-1:n)-i)+e+(a?`\r
4
4
  `:`
5
5
  `)+r,i=n+1,n=t.indexOf(`
6
- `,i)}while(n!==-1);return s+=t.substr(i),s};Tu.exports={stringReplaceAll:N0,stringEncaseCRLFWithFirstIndex:$0}});var ju=$((dx,Mu)=>{"use strict";var U0=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,Ou=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,q0=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,z0=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,V0=new Map([["n",`
7
- `],["r","\r"],["t"," "],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e","\x1B"],["a","\x07"]]);function Ru(t){let e=t[0]==="u",r=t[1]==="{";return e&&!r&&t.length===5||t[0]==="x"&&t.length===3?String.fromCharCode(parseInt(t.slice(1),16)):e&&r?String.fromCodePoint(parseInt(t.slice(2,-1),16)):V0.get(t)||t}function W0(t,e){let r=[],n=e.trim().split(/\s*,\s*/g),i;for(let s of n){let a=Number(s);if(!Number.isNaN(a))r.push(a);else if(i=s.match(q0))r.push(i[2].replace(z0,(l,c,u)=>c?Ru(c):u));else throw new Error(`Invalid Chalk template style argument: ${s} (in style '${t}')`)}return r}function G0(t){Ou.lastIndex=0;let e=[],r;for(;(r=Ou.exec(t))!==null;){let n=r[1];if(r[2]){let i=W0(n,r[2]);e.push([n].concat(i))}else e.push([n])}return e}function Iu(t,e){let r={};for(let i of e)for(let s of i.styles)r[s[0]]=i.inverse?null:s.slice(1);let n=t;for(let[i,s]of Object.entries(r))if(Array.isArray(s)){if(!(i in n))throw new Error(`Unknown Chalk style: ${i}`);n=s.length>0?n[i](...s):n[i]}return n}Mu.exports=(t,e)=>{let r=[],n=[],i=[];if(e.replace(U0,(s,a,l,c,u,h)=>{if(a)i.push(Ru(a));else if(c){let f=i.join("");i=[],n.push(r.length===0?f:Iu(t,r)(f)),r.push({inverse:l,styles:G0(c)})}else if(u){if(r.length===0)throw new Error("Found extraneous } in Chalk template literal");n.push(Iu(t,r)(i.join(""))),i=[],r.pop()}else i.push(h)}),n.push(i.join("")),r.length>0){let s=`Chalk template literal is missing ${r.length} closing bracket${r.length===1?"":"s"} (\`}\`)`;throw new Error(s)}return n.join("")}});var zu=$((fx,qu)=>{"use strict";var Mn=Eu(),{stdout:jo,stderr:Bo}=Pu(),{stringReplaceAll:Z0,stringEncaseCRLFWithFirstIndex:K0}=Au(),{isArray:qi}=Array,Lu=["ansi","ansi","ansi256","ansi16m"],Xr=Object.create(null),H0=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=jo?jo.level:0;t.level=e.level===void 0?r:e.level},Lo=class{constructor(e){return Nu(e)}},Nu=t=>{let e={};return H0(e,t),e.template=(...r)=>Uu(e.template,...r),Object.setPrototypeOf(e,zi.prototype),Object.setPrototypeOf(e.template,e),e.template.constructor=()=>{throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},e.template.Instance=Lo,e.template};function zi(t){return Nu(t)}for(let[t,e]of Object.entries(Mn))Xr[t]={get(){let r=Vi(this,No(e.open,e.close,this._styler),this._isEmpty);return Object.defineProperty(this,t,{value:r}),r}};Xr.visible={get(){let t=Vi(this,this._styler,!0);return Object.defineProperty(this,"visible",{value:t}),t}};var $u=["rgb","hex","keyword","hsl","hsv","hwb","ansi","ansi256"];for(let t of $u)Xr[t]={get(){let{level:e}=this;return function(...r){let n=No(Mn.color[Lu[e]][t](...r),Mn.color.close,this._styler);return Vi(this,n,this._isEmpty)}}};for(let t of $u){let e="bg"+t[0].toUpperCase()+t.slice(1);Xr[e]={get(){let{level:r}=this;return function(...n){let i=No(Mn.bgColor[Lu[r]][t](...n),Mn.bgColor.close,this._styler);return Vi(this,i,this._isEmpty)}}}}var Y0=Object.defineProperties(()=>{},{...Xr,level:{enumerable:!0,get(){return this._generator.level},set(t){this._generator.level=t}}}),No=(t,e,r)=>{let n,i;return r===void 0?(n=t,i=e):(n=r.openAll+t,i=e+r.closeAll),{open:t,close:e,openAll:n,closeAll:i,parent:r}},Vi=(t,e,r)=>{let n=(...i)=>qi(i[0])&&qi(i[0].raw)?Bu(n,Uu(n,...i)):Bu(n,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(n,Y0),n._generator=t,n._styler=e,n._isEmpty=r,n},Bu=(t,e)=>{if(t.level<=0||!e)return t._isEmpty?"":e;let r=t._styler;if(r===void 0)return e;let{openAll:n,closeAll:i}=r;if(e.indexOf("\x1B")!==-1)for(;r!==void 0;)e=Z0(e,r.close,r.open),r=r.parent;let s=e.indexOf(`
8
- `);return s!==-1&&(e=K0(e,i,n,s)),n+e+i},Mo,Uu=(t,...e)=>{let[r]=e;if(!qi(r)||!qi(r.raw))return e.join(" ");let n=e.slice(1),i=[r.raw[0]];for(let s=1;s<r.length;s++)i.push(String(n[s-1]).replace(/[{}\\]/g,"\\$&"),String(r.raw[s]));return Mo===void 0&&(Mo=ju()),Mo(t,i.join(""))};Object.defineProperties(zi.prototype,Xr);var Wi=zi();Wi.supportsColor=jo;Wi.stderr=zi({level:Bo?Bo.level:0});Wi.stderr.supportsColor=Bo;qu.exports=Wi});var Vu=$($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.generateRandomBase64=Q0;var J0=require("crypto");function Q0(t=18){return(0,J0.randomBytes)(t).toString("base64")}});var Wu=$(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.readFileAsBase64=eb;var X0=require("fs/promises");async function eb(t){return{success:!0,base64:await(0,X0.readFile)(t,"base64")}}});var Yu=$(jn=>{"use strict";var Vo=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jn,"__esModule",{value:!0});jn.terminalSize=nb;var tb=require("child_process"),Gi=Vo(require("fs")),en=Vo(require("process")),rb=Vo(require("tty")),Zu=80,Ku=24,zo=(t,e,{shell:r,env:n}={})=>(0,tb.execFileSync)(t,e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:500,shell:r,env:n}).trim(),Zi=(t,e)=>({columns:Number.parseInt(t,10),rows:Number.parseInt(e,10)}),Hu=(t,e)=>{let{columns:r,rows:n}=Zi(t,e);if(!(Number.isNaN(r)||Number.isNaN(n))&&!(r===Zu&&n===Ku))return{columns:r,rows:n}};function nb(){let{env:t,stdout:e,stderr:r}=en.default;if(e?.columns&&e?.rows)return Zi(e.columns,e.rows);if(r?.columns&&r?.rows)return Zi(r.columns,r.rows);if(t.COLUMNS&&t.LINES)return Zi(t.COLUMNS,t.LINES);let n={columns:Zu,rows:Ku};return en.default.platform==="win32"?qo()??n:en.default.platform==="darwin"?Gu()??qo()??n:Gu()??qo()??ib()??n}var Gu=()=>{try{let t=en.default.platform==="darwin"?Gi.default.constants.O_EVTONLY|Gi.default.constants.O_NONBLOCK:Gi.default.constants.O_NONBLOCK,{columns:e,rows:r}=rb.default.WriteStream(Gi.default.openSync("/dev/tty",t));return{columns:e,rows:r}}catch{}},qo=()=>{try{let t=zo("tput",["cols"],{env:{TERM:"dumb",...en.default.env}}),e=zo("tput",["lines"],{env:{TERM:"dumb",...en.default.env}});if(t&&e)return Hu(t,e)}catch{}},ib=()=>{try{let t=zo("resize",["-u"]).match(/\d+/g);if(t.length===2)return Hu(t[0],t[1])}catch{}}});var pt=$((gx,Xu)=>{"use strict";var Ju=["nodebuffer","arraybuffer","fragments"],Qu=typeof Blob<"u";Qu&&Ju.push("blob");Xu.exports={BINARY_TYPES:Ju,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Qu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Bn=$((yx,Ki)=>{"use strict";var{EMPTY_BUFFER:sb}=pt(),Wo=Buffer[Symbol.species];function ob(t,e){if(t.length===0)return sb;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let i=0;i<t.length;i++){let s=t[i];r.set(s,n),n+=s.length}return n<e?new Wo(r.buffer,r.byteOffset,n):r}function ed(t,e,r,n,i){for(let s=0;s<i;s++)r[n+s]=t[s]^e[s&3]}function td(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function ab(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Go(t){if(Go.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Wo(t):ArrayBuffer.isView(t)?e=new Wo(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Go.readOnly=!1),e}Ki.exports={concat:ob,mask:ed,toArrayBuffer:ab,toBuffer:Go,unmask:td};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Ki.exports.mask=function(e,r,n,i,s){s<48?ed(e,r,n,i,s):t.mask(e,r,n,i,s)},Ki.exports.unmask=function(e,r){e.length<32?td(e,r):t.unmask(e,r)}}catch{}});var id=$((bx,nd)=>{"use strict";var rd=Symbol("kDone"),Zo=Symbol("kRun"),Ko=class{constructor(e){this[rd]=()=>{this.pending--,this[Zo]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Zo]()}[Zo](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[rd])}}};nd.exports=Ko});var Nn=$((vx,ld)=>{"use strict";var Ln=require("zlib"),sd=Bn(),lb=id(),{kStatusCode:od}=pt(),cb=Buffer[Symbol.species],ub=Buffer.from([0,0,255,255]),Yi=Symbol("permessage-deflate"),mt=Symbol("total-length"),tn=Symbol("callback"),Bt=Symbol("buffers"),rn=Symbol("error"),Hi,Ho=class{constructor(e,r,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!Hi){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Hi=new lb(i)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[tn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let i=r[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=i})}),e}decompress(e,r,n){Hi.add(i=>{this._decompress(e,r,(s,a)=>{i(),n(s,a)})})}compress(e,r,n){Hi.add(i=>{this._compress(e,r,(s,a)=>{i(),n(s,a)})})}_decompress(e,r,n){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,a=typeof this.params[s]!="number"?Ln.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Ln.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Yi]=this,this._inflate[mt]=0,this._inflate[Bt]=[],this._inflate.on("error",fb),this._inflate.on("data",ad)}this._inflate[tn]=n,this._inflate.write(e),r&&this._inflate.write(ub),this._inflate.flush(()=>{let s=this._inflate[rn];if(s){this._inflate.close(),this._inflate=null,n(s);return}let a=sd.concat(this._inflate[Bt],this._inflate[mt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[mt]=0,this._inflate[Bt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,r,n){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,a=typeof this.params[s]!="number"?Ln.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Ln.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[mt]=0,this._deflate[Bt]=[],this._deflate.on("data",db)}this._deflate[tn]=n,this._deflate.write(e),this._deflate.flush(Ln.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=sd.concat(this._deflate[Bt],this._deflate[mt]);r&&(s=new cb(s.buffer,s.byteOffset,s.length-4)),this._deflate[tn]=null,this._deflate[mt]=0,this._deflate[Bt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};ld.exports=Ho;function db(t){this[Bt].push(t),this[mt]+=t.length}function ad(t){if(this[mt]+=t.length,this[Yi]._maxPayload<1||this[mt]<=this[Yi]._maxPayload){this[Bt].push(t);return}this[rn]=new RangeError("Max payload size exceeded"),this[rn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rn][od]=1009,this.removeListener("data",ad),this.reset()}function fb(t){if(this[Yi]._inflate=null,this[rn]){this[tn](this[rn]);return}t[od]=1007,this[tn](t)}});var nn=$((Dx,Ji)=>{"use strict";var{isUtf8:cd}=require("buffer"),{hasBlob:hb}=pt(),pb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function mb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Yo(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function gb(t){return hb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ji.exports={isBlob:gb,isValidStatusCode:mb,isValidUTF8:Yo,tokenChars:pb};if(cd)Ji.exports.isValidUTF8=function(t){return t.length<24?Yo(t):cd(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Ji.exports.isValidUTF8=function(e){return e.length<32?Yo(e):t(e)}}catch{}});var ta=$((wx,gd)=>{"use strict";var{Writable:yb}=require("stream"),ud=Nn(),{BINARY_TYPES:bb,EMPTY_BUFFER:dd,kStatusCode:vb,kWebSocket:Db}=pt(),{concat:Jo,toArrayBuffer:wb,unmask:Sb}=Bn(),{isValidStatusCode:Cb,isValidUTF8:fd}=nn(),Qi=Buffer[Symbol.species],$e=0,hd=1,pd=2,md=3,Qo=4,Xo=5,Xi=6,ea=class extends yb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||bb[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Db]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=$e}_write(e,r,n){if(this._opcode===8&&this._state==$e)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Qi(n.buffer,n.byteOffset+e,n.length-e),new Qi(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=r.length-e;e>=n.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new Qi(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case $e:this.getInfo(e);break;case hd:this.getPayloadLength16(e);break;case pd:this.getPayloadLength64(e);break;case md:this.getMask();break;case Qo:this.getData(e);break;case Xo:case Xi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(r[0]&64)===64;if(n&&!this._extensions[ud.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=hd:this._payloadLength===127?this._state=pd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=md:this._state=Qo}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Qo}getData(e){let r=dd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Sb(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Xo,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[ud.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return r(i);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(a);return}this._fragments.push(s)}this.dataMessage(r),this._state===$e&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=$e;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Jo(n,r):this._binaryType==="arraybuffer"?i=wb(Jo(n,r)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=$e):(this._state=Xi,setImmediate(()=>{this.emit("message",i,!0),this._state=$e,this.startLoop(e)}))}else{let i=Jo(n,r);if(!this._skipUTF8Validation&&!fd(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Xo||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=$e):(this._state=Xi,setImmediate(()=>{this.emit("message",i,!1),this._state=$e,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,dd),this.end();else{let n=e.readUInt16BE(0);if(!Cb(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let i=new Qi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!fd(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=$e;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=$e):(this._state=Xi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=$e,this.startLoop(r)}))}createError(e,r,n,i,s){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(a,this.createError),a.code=s,a[vb]=i,a}};gd.exports=ea});var ia=$((Cx,vd)=>{"use strict";var{Duplex:Sx}=require("stream"),{randomFillSync:Eb}=require("crypto"),yd=Nn(),{EMPTY_BUFFER:_b,kWebSocket:xb,NOOP:kb}=pt(),{isBlob:sn,isValidStatusCode:Fb}=nn(),{mask:bd,toBuffer:mr}=Bn(),Ue=Symbol("kByteLength"),Pb=Buffer.alloc(4),es=8*1024,gr,on=es,ze=0,Tb=1,Ab=2,ra=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ze,this.onerror=kb,this[xb]=void 0}static frame(e,r){let n,i=!1,s=2,a=!1;r.mask&&(n=r.maskBuffer||Pb,r.generateMask?r.generateMask(n):(on===es&&(gr===void 0&&(gr=Buffer.alloc(es)),Eb(gr,0,es),on=0),n[0]=gr[on++],n[1]=gr[on++],n[2]=gr[on++],n[3]=gr[on++]),a=(n[0]|n[1]|n[2]|n[3])===0,s=6);let l;typeof e=="string"?(!r.mask||a)&&r[Ue]!==void 0?l=r[Ue]:(e=Buffer.from(e),l=e.length):(l=e.length,i=r.mask&&r.readOnly&&!a);let c=l;l>=65536?(s+=8,c=127):l>125&&(s+=2,c=126);let u=Buffer.allocUnsafe(i?l+s:s);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(l,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(l,4,6)),r.mask?(u[1]|=128,u[s-4]=n[0],u[s-3]=n[1],u[s-2]=n[2],u[s-1]=n[3],a?[u,e]:i?(bd(e,n,u,s,l),[u]):(bd(e,n,e,0,l),[u,e])):[u,e]}close(e,r,n,i){let s;if(e===void 0)s=_b;else{if(typeof e!="number"||!Fb(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let l=Buffer.byteLength(r);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+l),s.writeUInt16BE(e,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let a={[Ue]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ze?this.enqueue([this.dispatch,s,!1,a,i]):this.sendFrame(t.frame(s,a),i)}ping(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):sn(e)?(i=e.size,s=!1):(e=mr(e),i=e.length,s=mr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Ue]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};sn(e)?this._state!==ze?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==ze?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(t.frame(e,a),n)}pong(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):sn(e)?(i=e.size,s=!1):(e=mr(e),i=e.length,s=mr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Ue]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};sn(e)?this._state!==ze?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==ze?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(t.frame(e,a),n)}send(e,r,n){let i=this._extensions[yd.extensionName],s=r.binary?2:1,a=r.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):sn(e)?(l=e.size,c=!1):(e=mr(e),l=e.length,c=mr.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=l>=i._threshold),this._compress=a):(a=!1,s=0),r.fin&&(this._firstFragment=!0);let u={[Ue]:l,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:a};sn(e)?this._state!==ze?this.enqueue([this.getBlobData,e,this._compress,u,n]):this.getBlobData(e,this._compress,u,n):this._state!==ze?this.enqueue([this.dispatch,e,this._compress,u,n]):this.dispatch(e,this._compress,u,n)}getBlobData(e,r,n,i){this._bufferedBytes+=n[Ue],this._state=Ab,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(na,this,l,i);return}this._bufferedBytes-=n[Ue];let a=mr(s);r?this.dispatch(a,r,n,i):(this._state=ze,this.sendFrame(t.frame(a,n),i),this.dequeue())}).catch(s=>{process.nextTick(Ob,this,s,i)})}dispatch(e,r,n,i){if(!r){this.sendFrame(t.frame(e,n),i);return}let s=this._extensions[yd.extensionName];this._bufferedBytes+=n[Ue],this._state=Tb,s.compress(e,n.fin,(a,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");na(this,c,i);return}this._bufferedBytes-=n[Ue],this._state=ze,n.readOnly=!1,this.sendFrame(t.frame(l,n),i),this.dequeue()})}dequeue(){for(;this._state===ze&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ue],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ue],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};vd.exports=ra;function na(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let i=t._queue[n],s=i[i.length-1];typeof s=="function"&&s(e)}}function Ob(t,e,r){na(t,e,r),t.onerror(e)}});var Fd=$((Ex,kd)=>{"use strict";var{kForOnEventAttribute:$n,kListener:sa}=pt(),Dd=Symbol("kCode"),wd=Symbol("kData"),Sd=Symbol("kError"),Cd=Symbol("kMessage"),Ed=Symbol("kReason"),an=Symbol("kTarget"),_d=Symbol("kType"),xd=Symbol("kWasClean"),gt=class{constructor(e){this[an]=null,this[_d]=e}get target(){return this[an]}get type(){return this[_d]}};Object.defineProperty(gt.prototype,"target",{enumerable:!0});Object.defineProperty(gt.prototype,"type",{enumerable:!0});var yr=class extends gt{constructor(e,r={}){super(e),this[Dd]=r.code===void 0?0:r.code,this[Ed]=r.reason===void 0?"":r.reason,this[xd]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Dd]}get reason(){return this[Ed]}get wasClean(){return this[xd]}};Object.defineProperty(yr.prototype,"code",{enumerable:!0});Object.defineProperty(yr.prototype,"reason",{enumerable:!0});Object.defineProperty(yr.prototype,"wasClean",{enumerable:!0});var ln=class extends gt{constructor(e,r={}){super(e),this[Sd]=r.error===void 0?null:r.error,this[Cd]=r.message===void 0?"":r.message}get error(){return this[Sd]}get message(){return this[Cd]}};Object.defineProperty(ln.prototype,"error",{enumerable:!0});Object.defineProperty(ln.prototype,"message",{enumerable:!0});var Un=class extends gt{constructor(e,r={}){super(e),this[wd]=r.data===void 0?null:r.data}get data(){return this[wd]}};Object.defineProperty(Un.prototype,"data",{enumerable:!0});var Ib={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[$n]&&i[sa]===e&&!i[$n])return;let n;if(t==="message")n=function(s,a){let l=new Un("message",{data:a?s:s.toString()});l[an]=this,ts(e,this,l)};else if(t==="close")n=function(s,a){let l=new yr("close",{code:s,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[an]=this,ts(e,this,l)};else if(t==="error")n=function(s){let a=new ln("error",{error:s,message:s.message});a[an]=this,ts(e,this,a)};else if(t==="open")n=function(){let s=new gt("open");s[an]=this,ts(e,this,s)};else return;n[$n]=!!r[$n],n[sa]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[sa]===e&&!r[$n]){this.removeListener(t,r);break}}};kd.exports={CloseEvent:yr,ErrorEvent:ln,Event:gt,EventTarget:Ib,MessageEvent:Un};function ts(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var oa=$((_x,Pd)=>{"use strict";var{tokenChars:qn}=nn();function Je(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Rb(t){let e=Object.create(null),r=Object.create(null),n=!1,i=!1,s=!1,a,l,c=-1,u=-1,h=-1,f=0;for(;f<t.length;f++)if(u=t.charCodeAt(f),a===void 0)if(h===-1&&qn[u]===1)c===-1&&(c=f);else if(f!==0&&(u===32||u===9))h===-1&&c!==-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f);let p=t.slice(c,h);u===44?(Je(e,p,r),r=Object.create(null)):a=p,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(h===-1&&qn[u]===1)c===-1&&(c=f);else if(u===32||u===9)h===-1&&c!==-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f),Je(r,t.slice(c,h),!0),u===44&&(Je(e,a,r),r=Object.create(null),a=void 0),c=h=-1}else if(u===61&&c!==-1&&h===-1)l=t.slice(c,f),c=h=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(i){if(qn[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:n||(n=!0),i=!1}else if(s)if(qn[u]===1)c===-1&&(c=f);else if(u===34&&c!==-1)s=!1,h=f;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&t.charCodeAt(f-1)===61)s=!0;else if(h===-1&&qn[u]===1)c===-1&&(c=f);else if(c!==-1&&(u===32||u===9))h===-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f);let p=t.slice(c,h);n&&(p=p.replace(/\\/g,""),n=!1),Je(r,l,p),u===44&&(Je(e,a,r),r=Object.create(null),a=void 0),l=void 0,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||s||u===32||u===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=f);let d=t.slice(c,h);return a===void 0?Je(e,d,r):(l===void 0?Je(r,d,!0):n?Je(r,l,d.replace(/\\/g,"")):Je(r,l,d),Je(e,a,r)),e}function Mb(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(i=>{let s=n[i];return Array.isArray(s)||(s=[s]),s.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Pd.exports={format:Mb,parse:Rb}});var ss=$((Fx,Ud)=>{"use strict";var jb=require("events"),Bb=require("https"),Lb=require("http"),Od=require("net"),Nb=require("tls"),{randomBytes:$b,createHash:Ub}=require("crypto"),{Duplex:xx,Readable:kx}=require("stream"),{URL:aa}=require("url"),Lt=Nn(),qb=ta(),zb=ia(),{isBlob:Vb}=nn(),{BINARY_TYPES:Td,CLOSE_TIMEOUT:Wb,EMPTY_BUFFER:rs,GUID:Gb,kForOnEventAttribute:la,kListener:Zb,kStatusCode:Kb,kWebSocket:de,NOOP:Id}=pt(),{EventTarget:{addEventListener:Hb,removeEventListener:Yb}}=Fd(),{format:Jb,parse:Qb}=oa(),{toBuffer:Xb}=Bn(),Rd=Symbol("kAborted"),ca=[8,13],yt=["CONNECTING","OPEN","CLOSING","CLOSED"],ev=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ne=class t extends jb{constructor(e,r,n){super(),this._binaryType=Td[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=rs,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),Md(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Td.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let i=new qb({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new zb(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[de]=this,s[de]=this,e[de]=this,i.on("conclude",nv),i.on("drain",iv),i.on("error",sv),i.on("message",ov),i.on("ping",av),i.on("pong",lv),s.onerror=cv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Ld),e.on("data",is),e.on("end",Nd),e.on("error",$d),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Lt.extensionName]&&this._extensions[Lt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Ae(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Bd(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ua(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||rs,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ua(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||rs,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){ua(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Lt.extensionName]||(i.compress=!1),this._sender.send(e||rs,i,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Ae(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ne,"CONNECTING",{enumerable:!0,value:yt.indexOf("CONNECTING")});Object.defineProperty(ne.prototype,"CONNECTING",{enumerable:!0,value:yt.indexOf("CONNECTING")});Object.defineProperty(ne,"OPEN",{enumerable:!0,value:yt.indexOf("OPEN")});Object.defineProperty(ne.prototype,"OPEN",{enumerable:!0,value:yt.indexOf("OPEN")});Object.defineProperty(ne,"CLOSING",{enumerable:!0,value:yt.indexOf("CLOSING")});Object.defineProperty(ne.prototype,"CLOSING",{enumerable:!0,value:yt.indexOf("CLOSING")});Object.defineProperty(ne,"CLOSED",{enumerable:!0,value:yt.indexOf("CLOSED")});Object.defineProperty(ne.prototype,"CLOSED",{enumerable:!0,value:yt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ne.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ne.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[la])return e[Zb];return null},set(e){for(let r of this.listeners(t))if(r[la]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[la]:!0})}})});ne.prototype.addEventListener=Hb;ne.prototype.removeEventListener=Yb;Ud.exports=ne;function Md(t,e,r,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Wb,protocolVersion:ca[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!ca.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${ca.join(", ")})`);let s;if(e instanceof aa)s=e;else try{s=new aa(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let a=s.protocol==="wss:",l=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!a&&!l?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let g=new SyntaxError(c);if(t._redirects===0)throw g;ns(t,g);return}let u=a?443:80,h=$b(16).toString("base64"),f=a?Bb.request:Lb.request,d=new Set,p;if(i.createConnection=i.createConnection||(a?rv:tv),i.defaultPort=i.defaultPort||u,i.port=s.port||u,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(p=new Lt(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Jb({[Lt.extensionName]:p.offer()})),r.length){for(let g of r){if(typeof g!="string"||!ev.test(g)||d.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(g)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),l){let g=i.path.split(":");i.socketPath=g[0],i.path=g[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=a,t._originalHostOrSocketPath=l?i.socketPath:s.host;let g=n&&n.headers;if(n={...n,headers:{}},g)for(let[y,b]of Object.entries(g))n.headers[y.toLowerCase()]=b}else if(t.listenerCount("redirect")===0){let g=l?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,g||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=f(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=f(i);i.timeout&&m.on("timeout",()=>{Ae(t,m,"Opening handshake has timed out")}),m.on("error",g=>{m===null||m[Rd]||(m=t._req=null,ns(t,g))}),m.on("response",g=>{let y=g.headers.location,b=g.statusCode;if(y&&i.followRedirects&&b>=300&&b<400){if(++t._redirects>i.maxRedirects){Ae(t,m,"Maximum redirects exceeded");return}m.abort();let D;try{D=new aa(y,e)}catch{let S=new SyntaxError(`Invalid URL: ${y}`);ns(t,S);return}Md(t,D,r,n)}else t.emit("unexpected-response",m,g)||Ae(t,m,`Unexpected server response: ${g.statusCode}`)}),m.on("upgrade",(g,y,b)=>{if(t.emit("upgrade",g),t.readyState!==ne.CONNECTING)return;m=t._req=null;let D=g.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){Ae(t,y,"Invalid Upgrade header");return}let v=Ub("sha1").update(h+Gb).digest("base64");if(g.headers["sec-websocket-accept"]!==v){Ae(t,y,"Invalid Sec-WebSocket-Accept header");return}let S=g.headers["sec-websocket-protocol"],C;if(S!==void 0?d.size?d.has(S)||(C="Server sent an invalid subprotocol"):C="Server sent a subprotocol but none was requested":d.size&&(C="Server sent no subprotocol"),C){Ae(t,y,C);return}S&&(t._protocol=S);let x=g.headers["sec-websocket-extensions"];if(x!==void 0){if(!p){Ae(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let _;try{_=Qb(x)}catch{Ae(t,y,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(_);if(B.length!==1||B[0]!==Lt.extensionName){Ae(t,y,"Server indicated an extension that was not requested");return}try{p.accept(_[Lt.extensionName])}catch{Ae(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Lt.extensionName]=p}t.setSocket(y,b,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function ns(t,e){t._readyState=ne.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function tv(t){return t.path=t.socketPath,Od.connect(t)}function rv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Od.isIP(t.host)?"":t.host),Nb.connect(t)}function Ae(t,e,r){t._readyState=ne.CLOSING;let n=new Error(r);Error.captureStackTrace(n,Ae),e.setHeader?(e[Rd]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ns,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function ua(t,e,r){if(e){let n=Vb(e)?e.size:Xb(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${yt[t.readyState]})`);process.nextTick(r,n)}}function nv(t,e){let r=this[de];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[de]!==void 0&&(r._socket.removeListener("data",is),process.nextTick(jd,r._socket),t===1005?r.close():r.close(t,e))}function iv(){let t=this[de];t.isPaused||t._socket.resume()}function sv(t){let e=this[de];e._socket[de]!==void 0&&(e._socket.removeListener("data",is),process.nextTick(jd,e._socket),e.close(t[Kb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Ad(){this[de].emitClose()}function ov(t,e){this[de].emit("message",t,e)}function av(t){let e=this[de];e._autoPong&&e.pong(t,!this._isServer,Id),e.emit("ping",t)}function lv(t){this[de].emit("pong",t)}function jd(t){t.resume()}function cv(t){let e=this[de];e.readyState!==ne.CLOSED&&(e.readyState===ne.OPEN&&(e._readyState=ne.CLOSING,Bd(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Bd(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ld(){let t=this[de];if(this.removeListener("close",Ld),this.removeListener("data",is),this.removeListener("end",Nd),t._readyState=ne.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[de]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Ad),t._receiver.on("finish",Ad))}function is(t){this[de]._receiver.write(t)||this.pause()}function Nd(){let t=this[de];t._readyState=ne.CLOSING,t._receiver.end(),this.end()}function $d(){let t=this[de];this.removeListener("error",$d),this.on("error",Id),t&&(t._readyState=ne.CLOSING,this.destroy())}});var Wd=$((Tx,Vd)=>{"use strict";var Px=ss(),{Duplex:uv}=require("stream");function qd(t){t.emit("close")}function dv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function zd(t){this.removeListener("error",zd),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function fv(t,e){let r=!0,n=new uv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,a){let l=!a&&n._readableState.objectMode?s.toString():s;n.push(l)||t.pause()}),t.once("error",function(s){n.destroyed||(r=!1,n.destroy(s))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(qd,n);return}let a=!1;t.once("error",function(c){a=!0,s(c)}),t.once("close",function(){a||s(i),process.nextTick(qd,n)}),r&&t.terminate()},n._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(i,s,a){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(i,s,a)});return}t.send(i,a)},n.on("end",dv),n.on("error",zd),n}Vd.exports=fv});var Zd=$((Ax,Gd)=>{"use strict";var{tokenChars:hv}=nn();function pv(t){let e=new Set,r=-1,n=-1,i=0;for(i;i<t.length;i++){let a=t.charCodeAt(i);if(n===-1&&hv[a]===1)r===-1&&(r=i);else if(i!==0&&(a===32||a===9))n===-1&&r!==-1&&(n=i);else if(a===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let l=t.slice(r,n);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(r,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Gd.exports={parse:pv}});var ef=$((Ix,Xd)=>{"use strict";var mv=require("events"),os=require("http"),{Duplex:Ox}=require("stream"),{createHash:gv}=require("crypto"),Kd=oa(),br=Nn(),yv=Zd(),bv=ss(),{CLOSE_TIMEOUT:vv,GUID:Dv,kWebSocket:wv}=pt(),Sv=/^[+/0-9A-Za-z]{22}==$/,Hd=0,Yd=1,Qd=2,da=class extends mv{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:vv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:bv,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=os.createServer((n,i)=>{let s=os.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Cv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,a)=>{this.handleUpgrade(i,s,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Hd}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Qd){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(zn,this);return}if(e&&this.once("close",e),this._state!==Yd)if(this._state=Yd,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(zn,this):process.nextTick(zn,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{zn(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,i){r.on("error",Jd);let s=e.headers["sec-websocket-key"],a=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){vr(this,e,r,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){vr(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!Sv.test(s)){vr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){vr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Vn(r,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=yv.parse(c)}catch{vr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&h!==void 0){let d=new br(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=Kd.parse(h);p[br.extensionName]&&(d.accept(p[br.extensionName]),f[br.extensionName]=d)}catch{vr(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let d={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(d,(p,m,g,y)=>{if(!p)return Vn(r,m||401,g,y);this.completeUpgrade(f,s,u,e,r,n,i)});return}if(!this.options.verifyClient(d))return Vn(r,401)}this.completeUpgrade(f,s,u,e,r,n,i)}completeUpgrade(e,r,n,i,s,a,l){if(!s.readable||!s.writable)return s.destroy();if(s[wv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Hd)return Vn(s,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${gv("sha1").update(r+Dv).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(n.size){let f=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),h._protocol=f)}if(e[br.extensionName]){let f=e[br.extensionName].params,d=Kd.format({[br.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${d}`),h._extensions=e}this.emit("headers",u,i),s.write(u.concat(`\r
6
+ `,i)}while(n!==-1);return s+=t.substr(i),s};Au.exports={stringReplaceAll:$0,stringEncaseCRLFWithFirstIndex:U0}});var Bu=$((fx,ju)=>{"use strict";var q0=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,Iu=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,z0=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,V0=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,W0=new Map([["n",`
7
+ `],["r","\r"],["t"," "],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e","\x1B"],["a","\x07"]]);function Mu(t){let e=t[0]==="u",r=t[1]==="{";return e&&!r&&t.length===5||t[0]==="x"&&t.length===3?String.fromCharCode(parseInt(t.slice(1),16)):e&&r?String.fromCodePoint(parseInt(t.slice(2,-1),16)):W0.get(t)||t}function G0(t,e){let r=[],n=e.trim().split(/\s*,\s*/g),i;for(let s of n){let a=Number(s);if(!Number.isNaN(a))r.push(a);else if(i=s.match(z0))r.push(i[2].replace(V0,(l,c,u)=>c?Mu(c):u));else throw new Error(`Invalid Chalk template style argument: ${s} (in style '${t}')`)}return r}function Z0(t){Iu.lastIndex=0;let e=[],r;for(;(r=Iu.exec(t))!==null;){let n=r[1];if(r[2]){let i=G0(n,r[2]);e.push([n].concat(i))}else e.push([n])}return e}function Ru(t,e){let r={};for(let i of e)for(let s of i.styles)r[s[0]]=i.inverse?null:s.slice(1);let n=t;for(let[i,s]of Object.entries(r))if(Array.isArray(s)){if(!(i in n))throw new Error(`Unknown Chalk style: ${i}`);n=s.length>0?n[i](...s):n[i]}return n}ju.exports=(t,e)=>{let r=[],n=[],i=[];if(e.replace(q0,(s,a,l,c,u,h)=>{if(a)i.push(Mu(a));else if(c){let f=i.join("");i=[],n.push(r.length===0?f:Ru(t,r)(f)),r.push({inverse:l,styles:Z0(c)})}else if(u){if(r.length===0)throw new Error("Found extraneous } in Chalk template literal");n.push(Ru(t,r)(i.join(""))),i=[],r.pop()}else i.push(h)}),n.push(i.join("")),r.length>0){let s=`Chalk template literal is missing ${r.length} closing bracket${r.length===1?"":"s"} (\`}\`)`;throw new Error(s)}return n.join("")}});var Vu=$((hx,zu)=>{"use strict";var Mn=_u(),{stdout:Bo,stderr:Lo}=Tu(),{stringReplaceAll:K0,stringEncaseCRLFWithFirstIndex:H0}=Ou(),{isArray:qi}=Array,Nu=["ansi","ansi","ansi256","ansi16m"],Xr=Object.create(null),Y0=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let r=Bo?Bo.level:0;t.level=e.level===void 0?r:e.level},No=class{constructor(e){return $u(e)}},$u=t=>{let e={};return Y0(e,t),e.template=(...r)=>qu(e.template,...r),Object.setPrototypeOf(e,zi.prototype),Object.setPrototypeOf(e.template,e),e.template.constructor=()=>{throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},e.template.Instance=No,e.template};function zi(t){return $u(t)}for(let[t,e]of Object.entries(Mn))Xr[t]={get(){let r=Vi(this,$o(e.open,e.close,this._styler),this._isEmpty);return Object.defineProperty(this,t,{value:r}),r}};Xr.visible={get(){let t=Vi(this,this._styler,!0);return Object.defineProperty(this,"visible",{value:t}),t}};var Uu=["rgb","hex","keyword","hsl","hsv","hwb","ansi","ansi256"];for(let t of Uu)Xr[t]={get(){let{level:e}=this;return function(...r){let n=$o(Mn.color[Nu[e]][t](...r),Mn.color.close,this._styler);return Vi(this,n,this._isEmpty)}}};for(let t of Uu){let e="bg"+t[0].toUpperCase()+t.slice(1);Xr[e]={get(){let{level:r}=this;return function(...n){let i=$o(Mn.bgColor[Nu[r]][t](...n),Mn.bgColor.close,this._styler);return Vi(this,i,this._isEmpty)}}}}var J0=Object.defineProperties(()=>{},{...Xr,level:{enumerable:!0,get(){return this._generator.level},set(t){this._generator.level=t}}}),$o=(t,e,r)=>{let n,i;return r===void 0?(n=t,i=e):(n=r.openAll+t,i=e+r.closeAll),{open:t,close:e,openAll:n,closeAll:i,parent:r}},Vi=(t,e,r)=>{let n=(...i)=>qi(i[0])&&qi(i[0].raw)?Lu(n,qu(n,...i)):Lu(n,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(n,J0),n._generator=t,n._styler=e,n._isEmpty=r,n},Lu=(t,e)=>{if(t.level<=0||!e)return t._isEmpty?"":e;let r=t._styler;if(r===void 0)return e;let{openAll:n,closeAll:i}=r;if(e.indexOf("\x1B")!==-1)for(;r!==void 0;)e=K0(e,r.close,r.open),r=r.parent;let s=e.indexOf(`
8
+ `);return s!==-1&&(e=H0(e,i,n,s)),n+e+i},jo,qu=(t,...e)=>{let[r]=e;if(!qi(r)||!qi(r.raw))return e.join(" ");let n=e.slice(1),i=[r.raw[0]];for(let s=1;s<r.length;s++)i.push(String(n[s-1]).replace(/[{}\\]/g,"\\$&"),String(r.raw[s]));return jo===void 0&&(jo=Bu()),jo(t,i.join(""))};Object.defineProperties(zi.prototype,Xr);var Wi=zi();Wi.supportsColor=Bo;Wi.stderr=zi({level:Lo?Lo.level:0});Wi.stderr.supportsColor=Lo;zu.exports=Wi});var Wu=$(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.generateRandomBase64=X0;var Q0=require("crypto");function X0(t=18){return(0,Q0.randomBytes)(t).toString("base64")}});var Gu=$(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.readFileAsBase64=tb;var eb=require("fs/promises");async function tb(t){return{success:!0,base64:await(0,eb.readFile)(t,"base64")}}});var Ju=$(jn=>{"use strict";var Wo=jn&&jn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(jn,"__esModule",{value:!0});jn.terminalSize=ib;var rb=require("child_process"),Gi=Wo(require("fs")),en=Wo(require("process")),nb=Wo(require("tty")),Ku=80,Hu=24,Vo=(t,e,{shell:r,env:n}={})=>(0,rb.execFileSync)(t,e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:500,shell:r,env:n}).trim(),Zi=(t,e)=>({columns:Number.parseInt(t,10),rows:Number.parseInt(e,10)}),Yu=(t,e)=>{let{columns:r,rows:n}=Zi(t,e);if(!(Number.isNaN(r)||Number.isNaN(n))&&!(r===Ku&&n===Hu))return{columns:r,rows:n}};function ib(){let{env:t,stdout:e,stderr:r}=en.default;if(e?.columns&&e?.rows)return Zi(e.columns,e.rows);if(r?.columns&&r?.rows)return Zi(r.columns,r.rows);if(t.COLUMNS&&t.LINES)return Zi(t.COLUMNS,t.LINES);let n={columns:Ku,rows:Hu};return en.default.platform==="win32"?zo()??n:en.default.platform==="darwin"?Zu()??zo()??n:Zu()??zo()??sb()??n}var Zu=()=>{try{let t=en.default.platform==="darwin"?Gi.default.constants.O_EVTONLY|Gi.default.constants.O_NONBLOCK:Gi.default.constants.O_NONBLOCK,{columns:e,rows:r}=nb.default.WriteStream(Gi.default.openSync("/dev/tty",t));return{columns:e,rows:r}}catch{}},zo=()=>{try{let t=Vo("tput",["cols"],{env:{TERM:"dumb",...en.default.env}}),e=Vo("tput",["lines"],{env:{TERM:"dumb",...en.default.env}});if(t&&e)return Yu(t,e)}catch{}},sb=()=>{try{let t=Vo("resize",["-u"]).match(/\d+/g);if(t.length===2)return Yu(t[0],t[1])}catch{}}});var mt=$((yx,ed)=>{"use strict";var Qu=["nodebuffer","arraybuffer","fragments"],Xu=typeof Blob<"u";Xu&&Qu.push("blob");ed.exports={BINARY_TYPES:Qu,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Xu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Bn=$((bx,Ki)=>{"use strict";var{EMPTY_BUFFER:ob}=mt(),Go=Buffer[Symbol.species];function ab(t,e){if(t.length===0)return ob;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let i=0;i<t.length;i++){let s=t[i];r.set(s,n),n+=s.length}return n<e?new Go(r.buffer,r.byteOffset,n):r}function td(t,e,r,n,i){for(let s=0;s<i;s++)r[n+s]=t[s]^e[s&3]}function rd(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function lb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Zo(t){if(Zo.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Go(t):ArrayBuffer.isView(t)?e=new Go(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Zo.readOnly=!1),e}Ki.exports={concat:ab,mask:td,toArrayBuffer:lb,toBuffer:Zo,unmask:rd};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=require("bufferutil");Ki.exports.mask=function(e,r,n,i,s){s<48?td(e,r,n,i,s):t.mask(e,r,n,i,s)},Ki.exports.unmask=function(e,r){e.length<32?rd(e,r):t.unmask(e,r)}}catch{}});var sd=$((vx,id)=>{"use strict";var nd=Symbol("kDone"),Ko=Symbol("kRun"),Ho=class{constructor(e){this[nd]=()=>{this.pending--,this[Ko]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ko]()}[Ko](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[nd])}}};id.exports=Ho});var Nn=$((Dx,cd)=>{"use strict";var Ln=require("zlib"),od=Bn(),cb=sd(),{kStatusCode:ad}=mt(),ub=Buffer[Symbol.species],db=Buffer.from([0,0,255,255]),Yi=Symbol("permessage-deflate"),gt=Symbol("total-length"),tn=Symbol("callback"),Bt=Symbol("buffers"),rn=Symbol("error"),Hi,Yo=class{constructor(e,r,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!Hi){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Hi=new cb(i)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[tn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let i=r[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=i})}),e}decompress(e,r,n){Hi.add(i=>{this._decompress(e,r,(s,a)=>{i(),n(s,a)})})}compress(e,r,n){Hi.add(i=>{this._compress(e,r,(s,a)=>{i(),n(s,a)})})}_decompress(e,r,n){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,a=typeof this.params[s]!="number"?Ln.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Ln.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[Yi]=this,this._inflate[gt]=0,this._inflate[Bt]=[],this._inflate.on("error",hb),this._inflate.on("data",ld)}this._inflate[tn]=n,this._inflate.write(e),r&&this._inflate.write(db),this._inflate.flush(()=>{let s=this._inflate[rn];if(s){this._inflate.close(),this._inflate=null,n(s);return}let a=od.concat(this._inflate[Bt],this._inflate[gt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[gt]=0,this._inflate[Bt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,r,n){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,a=typeof this.params[s]!="number"?Ln.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Ln.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[gt]=0,this._deflate[Bt]=[],this._deflate.on("data",fb)}this._deflate[tn]=n,this._deflate.write(e),this._deflate.flush(Ln.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=od.concat(this._deflate[Bt],this._deflate[gt]);r&&(s=new ub(s.buffer,s.byteOffset,s.length-4)),this._deflate[tn]=null,this._deflate[gt]=0,this._deflate[Bt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};cd.exports=Yo;function fb(t){this[Bt].push(t),this[gt]+=t.length}function ld(t){if(this[gt]+=t.length,this[Yi]._maxPayload<1||this[gt]<=this[Yi]._maxPayload){this[Bt].push(t);return}this[rn]=new RangeError("Max payload size exceeded"),this[rn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rn][ad]=1009,this.removeListener("data",ld),this.reset()}function hb(t){if(this[Yi]._inflate=null,this[rn]){this[tn](this[rn]);return}t[ad]=1007,this[tn](t)}});var nn=$((wx,Ji)=>{"use strict";var{isUtf8:ud}=require("buffer"),{hasBlob:pb}=mt(),mb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function gb(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Jo(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function yb(t){return pb&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ji.exports={isBlob:yb,isValidStatusCode:gb,isValidUTF8:Jo,tokenChars:mb};if(ud)Ji.exports.isValidUTF8=function(t){return t.length<24?Jo(t):ud(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=require("utf-8-validate");Ji.exports.isValidUTF8=function(e){return e.length<32?Jo(e):t(e)}}catch{}});var ra=$((Sx,yd)=>{"use strict";var{Writable:bb}=require("stream"),dd=Nn(),{BINARY_TYPES:vb,EMPTY_BUFFER:fd,kStatusCode:Db,kWebSocket:wb}=mt(),{concat:Qo,toArrayBuffer:Sb,unmask:Cb}=Bn(),{isValidStatusCode:Eb,isValidUTF8:hd}=nn(),Qi=Buffer[Symbol.species],Ue=0,pd=1,md=2,gd=3,Xo=4,ea=5,Xi=6,ta=class extends bb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||vb[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[wb]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ue}_write(e,r,n){if(this._opcode===8&&this._state==Ue)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Qi(n.buffer,n.byteOffset+e,n.length-e),new Qi(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=r.length-e;e>=n.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new Qi(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case Ue:this.getInfo(e);break;case pd:this.getPayloadLength16(e);break;case md:this.getPayloadLength64(e);break;case gd:this.getMask();break;case Xo:this.getData(e);break;case ea:case Xi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(r[0]&64)===64;if(n&&!this._extensions[dd.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=pd:this._payloadLength===127?this._state=md:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=gd:this._state=Xo}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Xo}getData(e){let r=fd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Cb(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=ea,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[dd.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return r(i);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(a);return}this._fragments.push(s)}this.dataMessage(r),this._state===Ue&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=Ue;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Qo(n,r):this._binaryType==="arraybuffer"?i=Sb(Qo(n,r)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Ue):(this._state=Xi,setImmediate(()=>{this.emit("message",i,!0),this._state=Ue,this.startLoop(e)}))}else{let i=Qo(n,r);if(!this._skipUTF8Validation&&!hd(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===ea||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Ue):(this._state=Xi,setImmediate(()=>{this.emit("message",i,!1),this._state=Ue,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fd),this.end();else{let n=e.readUInt16BE(0);if(!Eb(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let i=new Qi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!hd(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=Ue;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ue):(this._state=Xi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ue,this.startLoop(r)}))}createError(e,r,n,i,s){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(a,this.createError),a.code=s,a[Db]=i,a}};yd.exports=ta});var sa=$((Ex,Dd)=>{"use strict";var{Duplex:Cx}=require("stream"),{randomFillSync:_b}=require("crypto"),bd=Nn(),{EMPTY_BUFFER:xb,kWebSocket:kb,NOOP:Fb}=mt(),{isBlob:sn,isValidStatusCode:Pb}=nn(),{mask:vd,toBuffer:mr}=Bn(),qe=Symbol("kByteLength"),Tb=Buffer.alloc(4),es=8*1024,gr,on=es,Ve=0,Ab=1,Ob=2,na=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Ve,this.onerror=Fb,this[kb]=void 0}static frame(e,r){let n,i=!1,s=2,a=!1;r.mask&&(n=r.maskBuffer||Tb,r.generateMask?r.generateMask(n):(on===es&&(gr===void 0&&(gr=Buffer.alloc(es)),_b(gr,0,es),on=0),n[0]=gr[on++],n[1]=gr[on++],n[2]=gr[on++],n[3]=gr[on++]),a=(n[0]|n[1]|n[2]|n[3])===0,s=6);let l;typeof e=="string"?(!r.mask||a)&&r[qe]!==void 0?l=r[qe]:(e=Buffer.from(e),l=e.length):(l=e.length,i=r.mask&&r.readOnly&&!a);let c=l;l>=65536?(s+=8,c=127):l>125&&(s+=2,c=126);let u=Buffer.allocUnsafe(i?l+s:s);return u[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(l,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(l,4,6)),r.mask?(u[1]|=128,u[s-4]=n[0],u[s-3]=n[1],u[s-2]=n[2],u[s-1]=n[3],a?[u,e]:i?(vd(e,n,u,s,l),[u]):(vd(e,n,e,0,l),[u,e])):[u,e]}close(e,r,n,i){let s;if(e===void 0)s=xb;else{if(typeof e!="number"||!Pb(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let l=Buffer.byteLength(r);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+l),s.writeUInt16BE(e,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let a={[qe]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ve?this.enqueue([this.dispatch,s,!1,a,i]):this.sendFrame(t.frame(s,a),i)}ping(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):sn(e)?(i=e.size,s=!1):(e=mr(e),i=e.length,s=mr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[qe]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};sn(e)?this._state!==Ve?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Ve?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(t.frame(e,a),n)}pong(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):sn(e)?(i=e.size,s=!1):(e=mr(e),i=e.length,s=mr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[qe]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};sn(e)?this._state!==Ve?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Ve?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(t.frame(e,a),n)}send(e,r,n){let i=this._extensions[bd.extensionName],s=r.binary?2:1,a=r.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):sn(e)?(l=e.size,c=!1):(e=mr(e),l=e.length,c=mr.readOnly),this._firstFragment?(this._firstFragment=!1,a&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=l>=i._threshold),this._compress=a):(a=!1,s=0),r.fin&&(this._firstFragment=!0);let u={[qe]:l,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:a};sn(e)?this._state!==Ve?this.enqueue([this.getBlobData,e,this._compress,u,n]):this.getBlobData(e,this._compress,u,n):this._state!==Ve?this.enqueue([this.dispatch,e,this._compress,u,n]):this.dispatch(e,this._compress,u,n)}getBlobData(e,r,n,i){this._bufferedBytes+=n[qe],this._state=Ob,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(ia,this,l,i);return}this._bufferedBytes-=n[qe];let a=mr(s);r?this.dispatch(a,r,n,i):(this._state=Ve,this.sendFrame(t.frame(a,n),i),this.dequeue())}).catch(s=>{process.nextTick(Ib,this,s,i)})}dispatch(e,r,n,i){if(!r){this.sendFrame(t.frame(e,n),i);return}let s=this._extensions[bd.extensionName];this._bufferedBytes+=n[qe],this._state=Ab,s.compress(e,n.fin,(a,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ia(this,c,i);return}this._bufferedBytes-=n[qe],this._state=Ve,n.readOnly=!1,this.sendFrame(t.frame(l,n),i),this.dequeue()})}dequeue(){for(;this._state===Ve&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][qe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][qe],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Dd.exports=na;function ia(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let i=t._queue[n],s=i[i.length-1];typeof s=="function"&&s(e)}}function Ib(t,e,r){ia(t,e,r),t.onerror(e)}});var Pd=$((_x,Fd)=>{"use strict";var{kForOnEventAttribute:$n,kListener:oa}=mt(),wd=Symbol("kCode"),Sd=Symbol("kData"),Cd=Symbol("kError"),Ed=Symbol("kMessage"),_d=Symbol("kReason"),an=Symbol("kTarget"),xd=Symbol("kType"),kd=Symbol("kWasClean"),yt=class{constructor(e){this[an]=null,this[xd]=e}get target(){return this[an]}get type(){return this[xd]}};Object.defineProperty(yt.prototype,"target",{enumerable:!0});Object.defineProperty(yt.prototype,"type",{enumerable:!0});var yr=class extends yt{constructor(e,r={}){super(e),this[wd]=r.code===void 0?0:r.code,this[_d]=r.reason===void 0?"":r.reason,this[kd]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[wd]}get reason(){return this[_d]}get wasClean(){return this[kd]}};Object.defineProperty(yr.prototype,"code",{enumerable:!0});Object.defineProperty(yr.prototype,"reason",{enumerable:!0});Object.defineProperty(yr.prototype,"wasClean",{enumerable:!0});var ln=class extends yt{constructor(e,r={}){super(e),this[Cd]=r.error===void 0?null:r.error,this[Ed]=r.message===void 0?"":r.message}get error(){return this[Cd]}get message(){return this[Ed]}};Object.defineProperty(ln.prototype,"error",{enumerable:!0});Object.defineProperty(ln.prototype,"message",{enumerable:!0});var Un=class extends yt{constructor(e,r={}){super(e),this[Sd]=r.data===void 0?null:r.data}get data(){return this[Sd]}};Object.defineProperty(Un.prototype,"data",{enumerable:!0});var Rb={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[$n]&&i[oa]===e&&!i[$n])return;let n;if(t==="message")n=function(s,a){let l=new Un("message",{data:a?s:s.toString()});l[an]=this,ts(e,this,l)};else if(t==="close")n=function(s,a){let l=new yr("close",{code:s,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[an]=this,ts(e,this,l)};else if(t==="error")n=function(s){let a=new ln("error",{error:s,message:s.message});a[an]=this,ts(e,this,a)};else if(t==="open")n=function(){let s=new yt("open");s[an]=this,ts(e,this,s)};else return;n[$n]=!!r[$n],n[oa]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[oa]===e&&!r[$n]){this.removeListener(t,r);break}}};Fd.exports={CloseEvent:yr,ErrorEvent:ln,Event:yt,EventTarget:Rb,MessageEvent:Un};function ts(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var aa=$((xx,Td)=>{"use strict";var{tokenChars:qn}=nn();function Xe(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Mb(t){let e=Object.create(null),r=Object.create(null),n=!1,i=!1,s=!1,a,l,c=-1,u=-1,h=-1,f=0;for(;f<t.length;f++)if(u=t.charCodeAt(f),a===void 0)if(h===-1&&qn[u]===1)c===-1&&(c=f);else if(f!==0&&(u===32||u===9))h===-1&&c!==-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f);let p=t.slice(c,h);u===44?(Xe(e,p,r),r=Object.create(null)):a=p,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===void 0)if(h===-1&&qn[u]===1)c===-1&&(c=f);else if(u===32||u===9)h===-1&&c!==-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f),Xe(r,t.slice(c,h),!0),u===44&&(Xe(e,a,r),r=Object.create(null),a=void 0),c=h=-1}else if(u===61&&c!==-1&&h===-1)l=t.slice(c,f),c=h=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(i){if(qn[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:n||(n=!0),i=!1}else if(s)if(qn[u]===1)c===-1&&(c=f);else if(u===34&&c!==-1)s=!1,h=f;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&t.charCodeAt(f-1)===61)s=!0;else if(h===-1&&qn[u]===1)c===-1&&(c=f);else if(c!==-1&&(u===32||u===9))h===-1&&(h=f);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);h===-1&&(h=f);let p=t.slice(c,h);n&&(p=p.replace(/\\/g,""),n=!1),Xe(r,l,p),u===44&&(Xe(e,a,r),r=Object.create(null),a=void 0),l=void 0,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||s||u===32||u===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=f);let d=t.slice(c,h);return a===void 0?Xe(e,d,r):(l===void 0?Xe(r,d,!0):n?Xe(r,l,d.replace(/\\/g,"")):Xe(r,l,d),Xe(e,a,r)),e}function jb(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(i=>{let s=n[i];return Array.isArray(s)||(s=[s]),s.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Td.exports={format:jb,parse:Mb}});var ss=$((Px,qd)=>{"use strict";var Bb=require("events"),Lb=require("https"),Nb=require("http"),Id=require("net"),$b=require("tls"),{randomBytes:Ub,createHash:qb}=require("crypto"),{Duplex:kx,Readable:Fx}=require("stream"),{URL:la}=require("url"),Lt=Nn(),zb=ra(),Vb=sa(),{isBlob:Wb}=nn(),{BINARY_TYPES:Ad,CLOSE_TIMEOUT:Gb,EMPTY_BUFFER:rs,GUID:Zb,kForOnEventAttribute:ca,kListener:Kb,kStatusCode:Hb,kWebSocket:de,NOOP:Rd}=mt(),{EventTarget:{addEventListener:Yb,removeEventListener:Jb}}=Pd(),{format:Qb,parse:Xb}=aa(),{toBuffer:ev}=Bn(),Md=Symbol("kAborted"),ua=[8,13],bt=["CONNECTING","OPEN","CLOSING","CLOSED"],tv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ne=class t extends Bb{constructor(e,r,n){super(),this._binaryType=Ad[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=rs,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),jd(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ad.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let i=new zb({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new Vb(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[de]=this,s[de]=this,e[de]=this,i.on("conclude",iv),i.on("drain",sv),i.on("error",ov),i.on("message",av),i.on("ping",lv),i.on("pong",cv),s.onerror=uv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Nd),e.on("data",is),e.on("end",$d),e.on("error",Ud),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Lt.extensionName]&&this._extensions[Lt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Oe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ld(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){da(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||rs,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){da(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||rs,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){da(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Lt.extensionName]||(i.compress=!1),this._sender.send(e||rs,i,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Oe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ne,"CONNECTING",{enumerable:!0,value:bt.indexOf("CONNECTING")});Object.defineProperty(ne.prototype,"CONNECTING",{enumerable:!0,value:bt.indexOf("CONNECTING")});Object.defineProperty(ne,"OPEN",{enumerable:!0,value:bt.indexOf("OPEN")});Object.defineProperty(ne.prototype,"OPEN",{enumerable:!0,value:bt.indexOf("OPEN")});Object.defineProperty(ne,"CLOSING",{enumerable:!0,value:bt.indexOf("CLOSING")});Object.defineProperty(ne.prototype,"CLOSING",{enumerable:!0,value:bt.indexOf("CLOSING")});Object.defineProperty(ne,"CLOSED",{enumerable:!0,value:bt.indexOf("CLOSED")});Object.defineProperty(ne.prototype,"CLOSED",{enumerable:!0,value:bt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ne.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ne.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[ca])return e[Kb];return null},set(e){for(let r of this.listeners(t))if(r[ca]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[ca]:!0})}})});ne.prototype.addEventListener=Yb;ne.prototype.removeEventListener=Jb;qd.exports=ne;function jd(t,e,r,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Gb,protocolVersion:ua[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!ua.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${ua.join(", ")})`);let s;if(e instanceof la)s=e;else try{s=new la(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let a=s.protocol==="wss:",l=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!a&&!l?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let g=new SyntaxError(c);if(t._redirects===0)throw g;ns(t,g);return}let u=a?443:80,h=Ub(16).toString("base64"),f=a?Lb.request:Nb.request,d=new Set,p;if(i.createConnection=i.createConnection||(a?nv:rv),i.defaultPort=i.defaultPort||u,i.port=s.port||u,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(p=new Lt(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Qb({[Lt.extensionName]:p.offer()})),r.length){for(let g of r){if(typeof g!="string"||!tv.test(g)||d.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(g)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),l){let g=i.path.split(":");i.socketPath=g[0],i.path=g[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=a,t._originalHostOrSocketPath=l?i.socketPath:s.host;let g=n&&n.headers;if(n={...n,headers:{}},g)for(let[y,b]of Object.entries(g))n.headers[y.toLowerCase()]=b}else if(t.listenerCount("redirect")===0){let g=l?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!a)&&(delete i.headers.authorization,delete i.headers.cookie,g||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=f(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=f(i);i.timeout&&m.on("timeout",()=>{Oe(t,m,"Opening handshake has timed out")}),m.on("error",g=>{m===null||m[Md]||(m=t._req=null,ns(t,g))}),m.on("response",g=>{let y=g.headers.location,b=g.statusCode;if(y&&i.followRedirects&&b>=300&&b<400){if(++t._redirects>i.maxRedirects){Oe(t,m,"Maximum redirects exceeded");return}m.abort();let D;try{D=new la(y,e)}catch{let S=new SyntaxError(`Invalid URL: ${y}`);ns(t,S);return}jd(t,D,r,n)}else t.emit("unexpected-response",m,g)||Oe(t,m,`Unexpected server response: ${g.statusCode}`)}),m.on("upgrade",(g,y,b)=>{if(t.emit("upgrade",g),t.readyState!==ne.CONNECTING)return;m=t._req=null;let D=g.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){Oe(t,y,"Invalid Upgrade header");return}let v=qb("sha1").update(h+Zb).digest("base64");if(g.headers["sec-websocket-accept"]!==v){Oe(t,y,"Invalid Sec-WebSocket-Accept header");return}let S=g.headers["sec-websocket-protocol"],C;if(S!==void 0?d.size?d.has(S)||(C="Server sent an invalid subprotocol"):C="Server sent a subprotocol but none was requested":d.size&&(C="Server sent no subprotocol"),C){Oe(t,y,C);return}S&&(t._protocol=S);let x=g.headers["sec-websocket-extensions"];if(x!==void 0){if(!p){Oe(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let _;try{_=Xb(x)}catch{Oe(t,y,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(_);if(B.length!==1||B[0]!==Lt.extensionName){Oe(t,y,"Server indicated an extension that was not requested");return}try{p.accept(_[Lt.extensionName])}catch{Oe(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Lt.extensionName]=p}t.setSocket(y,b,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function ns(t,e){t._readyState=ne.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function rv(t){return t.path=t.socketPath,Id.connect(t)}function nv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Id.isIP(t.host)?"":t.host),$b.connect(t)}function Oe(t,e,r){t._readyState=ne.CLOSING;let n=new Error(r);Error.captureStackTrace(n,Oe),e.setHeader?(e[Md]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ns,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function da(t,e,r){if(e){let n=Wb(e)?e.size:ev(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${bt[t.readyState]})`);process.nextTick(r,n)}}function iv(t,e){let r=this[de];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[de]!==void 0&&(r._socket.removeListener("data",is),process.nextTick(Bd,r._socket),t===1005?r.close():r.close(t,e))}function sv(){let t=this[de];t.isPaused||t._socket.resume()}function ov(t){let e=this[de];e._socket[de]!==void 0&&(e._socket.removeListener("data",is),process.nextTick(Bd,e._socket),e.close(t[Hb])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Od(){this[de].emitClose()}function av(t,e){this[de].emit("message",t,e)}function lv(t){let e=this[de];e._autoPong&&e.pong(t,!this._isServer,Rd),e.emit("ping",t)}function cv(t){this[de].emit("pong",t)}function Bd(t){t.resume()}function uv(t){let e=this[de];e.readyState!==ne.CLOSED&&(e.readyState===ne.OPEN&&(e._readyState=ne.CLOSING,Ld(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ld(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Nd(){let t=this[de];if(this.removeListener("close",Nd),this.removeListener("data",is),this.removeListener("end",$d),t._readyState=ne.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[de]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Od),t._receiver.on("finish",Od))}function is(t){this[de]._receiver.write(t)||this.pause()}function $d(){let t=this[de];t._readyState=ne.CLOSING,t._receiver.end(),this.end()}function Ud(){let t=this[de];this.removeListener("error",Ud),this.on("error",Rd),t&&(t._readyState=ne.CLOSING,this.destroy())}});var Gd=$((Ax,Wd)=>{"use strict";var Tx=ss(),{Duplex:dv}=require("stream");function zd(t){t.emit("close")}function fv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Vd(t){this.removeListener("error",Vd),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function hv(t,e){let r=!0,n=new dv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,a){let l=!a&&n._readableState.objectMode?s.toString():s;n.push(l)||t.pause()}),t.once("error",function(s){n.destroyed||(r=!1,n.destroy(s))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(zd,n);return}let a=!1;t.once("error",function(c){a=!0,s(c)}),t.once("close",function(){a||s(i),process.nextTick(zd,n)}),r&&t.terminate()},n._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(i,s,a){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(i,s,a)});return}t.send(i,a)},n.on("end",fv),n.on("error",Vd),n}Wd.exports=hv});var Kd=$((Ox,Zd)=>{"use strict";var{tokenChars:pv}=nn();function mv(t){let e=new Set,r=-1,n=-1,i=0;for(i;i<t.length;i++){let a=t.charCodeAt(i);if(n===-1&&pv[a]===1)r===-1&&(r=i);else if(i!==0&&(a===32||a===9))n===-1&&r!==-1&&(n=i);else if(a===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let l=t.slice(r,n);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(r,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Zd.exports={parse:mv}});var tf=$((Rx,ef)=>{"use strict";var gv=require("events"),os=require("http"),{Duplex:Ix}=require("stream"),{createHash:yv}=require("crypto"),Hd=aa(),br=Nn(),bv=Kd(),vv=ss(),{CLOSE_TIMEOUT:Dv,GUID:wv,kWebSocket:Sv}=mt(),Cv=/^[+/0-9A-Za-z]{22}==$/,Yd=0,Jd=1,Xd=2,fa=class extends gv{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Dv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:vv,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=os.createServer((n,i)=>{let s=os.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Ev(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,a)=>{this.handleUpgrade(i,s,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Yd}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Xd){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(zn,this);return}if(e&&this.once("close",e),this._state!==Jd)if(this._state=Jd,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(zn,this):process.nextTick(zn,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{zn(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,i){r.on("error",Qd);let s=e.headers["sec-websocket-key"],a=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){vr(this,e,r,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){vr(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!Cv.test(s)){vr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){vr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Vn(r,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=bv.parse(c)}catch{vr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&h!==void 0){let d=new br(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=Hd.parse(h);p[br.extensionName]&&(d.accept(p[br.extensionName]),f[br.extensionName]=d)}catch{vr(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let d={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(d,(p,m,g,y)=>{if(!p)return Vn(r,m||401,g,y);this.completeUpgrade(f,s,u,e,r,n,i)});return}if(!this.options.verifyClient(d))return Vn(r,401)}this.completeUpgrade(f,s,u,e,r,n,i)}completeUpgrade(e,r,n,i,s,a,l){if(!s.readable||!s.writable)return s.destroy();if(s[Sv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Yd)return Vn(s,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${yv("sha1").update(r+wv).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(n.size){let f=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;f&&(u.push(`Sec-WebSocket-Protocol: ${f}`),h._protocol=f)}if(e[br.extensionName]){let f=e[br.extensionName].params,d=Hd.format({[br.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${d}`),h._extensions=e}this.emit("headers",u,i),s.write(u.concat(`\r
9
9
  `).join(`\r
10
- `)),s.removeListener("error",Jd),h.setSocket(s,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(zn,this)})),l(h,i)}};Xd.exports=da;function Cv(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function zn(t){t._state=Qd,t.emit("close")}function Jd(){this.destroy()}function Vn(t,e,r,n){r=r||os.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${os.STATUS_CODES[e]}\r
10
+ `)),s.removeListener("error",Qd),h.setSocket(s,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(zn,this)})),l(h,i)}};ef.exports=fa;function Ev(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function zn(t){t._state=Xd,t.emit("close")}function Qd(){this.destroy()}function Vn(t,e,r,n){r=r||os.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${os.STATUS_CODES[e]}\r
11
11
  `+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
12
12
  `)+`\r
13
13
  \r
14
- `+r)}function vr(t,e,r,n,i,s){if(t.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,vr),t.emit("wsClientError",a,r,e)}else Vn(r,n,i,s)}});var rf=$((Rx,tf)=>{"use strict";var bt=ss();bt.createWebSocketStream=Wd();bt.Server=ef();bt.Receiver=ta();bt.Sender=ia();bt.WebSocket=bt;bt.WebSocketServer=bt.Server;tf.exports=bt});var nf=$(cn=>{"use strict";var Ev=cn&&cn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cn,"__esModule",{value:!0});cn.WebSocket=void 0;var _v=Ev(rf());cn.WebSocket=_v.default});var sf=$(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.WebSocket=Qe.terminalSize=Qe.readFileAsBase64=Qe.generateRandomBase64=void 0;var xv=Vu();Object.defineProperty(Qe,"generateRandomBase64",{enumerable:!0,get:function(){return xv.generateRandomBase64}});var kv=Wu();Object.defineProperty(Qe,"readFileAsBase64",{enumerable:!0,get:function(){return kv.readFileAsBase64}});var Fv=Yu();Object.defineProperty(Qe,"terminalSize",{enumerable:!0,get:function(){return Fv.terminalSize}});var Pv=nf();Object.defineProperty(Qe,"WebSocket",{enumerable:!0,get:function(){return Pv.WebSocket}})});var eo=$((MF,cm)=>{var om=require("fs");function am(t){return new Promise((e,r)=>{om.unlink(t,function(n){return n?r(n):e()})})}function lm(t){return new Promise((e,r)=>{om.readFile(t,function(n,i){if(n)return r(n);e(i)})})}function AC(t){return new Promise((e,r)=>{lm(t).then(n=>{am(t).then(()=>{e(n)}).catch(i=>{r(i)})}).catch(n=>{r(n)})})}function OC(t){return new Promise((e,r)=>{t.listDisplays().then(n=>{let i=n.map(({id:s})=>t({screen:s}));Promise.all(i).then(e).catch(r)}).catch(r)})}cm.exports={unlinkP:am,readFileP:lm,readAndUnlinkP:AC,defaultAll:OC}});var pm=$((jF,hm)=>{var IC=require("child_process").exec,um=require("path"),RC=eo().defaultAll,MC=`Screen 0: minimum 320 x 200, current 5760 x 1080, maximum 8192 x 8192
14
+ `+r)}function vr(t,e,r,n,i,s){if(t.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,vr),t.emit("wsClientError",a,r,e)}else Vn(r,n,i,s)}});var nf=$((Mx,rf)=>{"use strict";var vt=ss();vt.createWebSocketStream=Gd();vt.Server=tf();vt.Receiver=ra();vt.Sender=sa();vt.WebSocket=vt;vt.WebSocketServer=vt.Server;rf.exports=vt});var sf=$(cn=>{"use strict";var _v=cn&&cn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cn,"__esModule",{value:!0});cn.WebSocket=void 0;var xv=_v(nf());cn.WebSocket=xv.default});var of=$(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.WebSocket=et.terminalSize=et.readFileAsBase64=et.generateRandomBase64=void 0;var kv=Wu();Object.defineProperty(et,"generateRandomBase64",{enumerable:!0,get:function(){return kv.generateRandomBase64}});var Fv=Gu();Object.defineProperty(et,"readFileAsBase64",{enumerable:!0,get:function(){return Fv.readFileAsBase64}});var Pv=Ju();Object.defineProperty(et,"terminalSize",{enumerable:!0,get:function(){return Pv.terminalSize}});var Tv=sf();Object.defineProperty(et,"WebSocket",{enumerable:!0,get:function(){return Tv.WebSocket}})});var eo=$((jF,um)=>{var am=require("fs");function lm(t){return new Promise((e,r)=>{am.unlink(t,function(n){return n?r(n):e()})})}function cm(t){return new Promise((e,r)=>{am.readFile(t,function(n,i){if(n)return r(n);e(i)})})}function OC(t){return new Promise((e,r)=>{cm(t).then(n=>{lm(t).then(()=>{e(n)}).catch(i=>{r(i)})}).catch(n=>{r(n)})})}function IC(t){return new Promise((e,r)=>{t.listDisplays().then(n=>{let i=n.map(({id:s})=>t({screen:s}));Promise.all(i).then(e).catch(r)}).catch(r)})}um.exports={unlinkP:lm,readFileP:cm,readAndUnlinkP:OC,defaultAll:IC}});var mm=$((BF,pm)=>{var RC=require("child_process").exec,dm=require("path"),MC=eo().defaultAll,jC=`Screen 0: minimum 320 x 200, current 5760 x 1080, maximum 8192 x 8192
15
15
  eDP-1 connected (normal left inverted right x axis y axis)
16
16
  2560x1440 60.00 +
17
17
  1920x1440 60.00
@@ -91,11 +91,11 @@ DP-2-2 connected 1920x1080+1920+0 (normal left inverted right x axis y axis) 476
91
91
  720x480 60.00 59.94
92
92
  640x480 60.00 59.94
93
93
  720x400 70.08
94
- DP-2-3 disconnected (normal left inverted right x axis y axis)`;function dm(t){return t.split(`
95
- `).filter(e=>e.indexOf(" connected ")>0).filter(e=>e.search(/\dx\d/)>0).map((e,r)=>{let n=e.split(" "),i=n[0],s=n[2]==="primary",a=s?n[3]:n[2],l=a.split(/[x+]/),c=+l[0],u=+l[1],h=+l[2],f=+l[3];return{width:c,height:u,name:i,id:i,offsetX:h,offsetY:f,primary:s,crop:a}})}function fm(){return new Promise((t,e)=>{IC("xrandr --current",(r,n)=>r?e(r):t(dm(n)))})}function jC(t){let e=0;return t.forEach(r=>{e+=r.height*r.width}),e}function BC(t){switch(um.extname(t)){case".jpg":case".jpeg":return"jpeg";case".png":return"png"}return"jpeg"}function Sn(t={}){return new Promise((e,r)=>{fm().then(n=>{let i=n.find(t.screen?f=>f.id===t.screen:f=>f.primary||f.id==="default")||n[0],s=["jpg","jpeg","png","tiff","bmp","gif"],a=(t.format||BC(t.filename||"")).toLowerCase();if(!s.includes(a))return r(new Error("Invalid format"));let l=t.filename?t.filename.replace(/[^a-zA-Z0-9._\-/]/g,""):"-",c=t.filename?{}:{encoding:"buffer",maxBuffer:jC(n)},u,h;t.linuxLibrary==="scrot"?(u="scrot",h=[l,"-e","-z",'echo "'+l+'"']):(u="import",h=["-silent","-window","root","-crop",i.crop,"-screen",a+":"+l]),require("child_process").execFile(u,h,c,(f,d)=>f?r(f):e(t.filename?um.resolve(l):d))})})}Sn.listDisplays=fm;Sn.parseDisplaysOutput=dm;Sn.EXAMPLE_DISPLAYS_OUTPUT=MC;Sn.all=()=>RC(Sn);hm.exports=Sn});var mm=$(lc=>{var Mr=require("path"),Gt=process.platform==="win32",Wt=require("fs"),LC=process.env.NODE_DEBUG&&/fs/.test(process.env.NODE_DEBUG);function NC(){var t;if(LC){var e=new Error;t=r}else t=n;return t;function r(i){i&&(e.message=i.message,i=e,n(i))}function n(i){if(i){if(process.throwDeprecation)throw i;if(!process.noDeprecation){var s="fs: missing callback "+(i.stack||i.message);process.traceDeprecation?console.trace(s):console.error(s)}}}}function $C(t){return typeof t=="function"?t:NC()}var BF=Mr.normalize;Gt?_t=/(.*?)(?:[\/\\]+|$)/g:_t=/(.*?)(?:[\/]+|$)/g;var _t;Gt?bi=/^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/:bi=/^[\/]*/;var bi;lc.realpathSync=function(e,r){if(e=Mr.resolve(e),r&&Object.prototype.hasOwnProperty.call(r,e))return r[e];var n=e,i={},s={},a,l,c,u;h();function h(){var y=bi.exec(e);a=y[0].length,l=y[0],c=y[0],u="",Gt&&!s[c]&&(Wt.lstatSync(c),s[c]=!0)}for(;a<e.length;){_t.lastIndex=a;var f=_t.exec(e);if(u=l,l+=f[0],c=u+f[1],a=_t.lastIndex,!(s[c]||r&&r[c]===c)){var d;if(r&&Object.prototype.hasOwnProperty.call(r,c))d=r[c];else{var p=Wt.lstatSync(c);if(!p.isSymbolicLink()){s[c]=!0,r&&(r[c]=c);continue}var m=null;if(!Gt){var g=p.dev.toString(32)+":"+p.ino.toString(32);i.hasOwnProperty(g)&&(m=i[g])}m===null&&(Wt.statSync(c),m=Wt.readlinkSync(c)),d=Mr.resolve(u,m),r&&(r[c]=d),Gt||(i[g]=m)}e=Mr.resolve(d,e.slice(a)),h()}}return r&&(r[n]=e),e};lc.realpath=function(e,r,n){if(typeof n!="function"&&(n=$C(r),r=null),e=Mr.resolve(e),r&&Object.prototype.hasOwnProperty.call(r,e))return process.nextTick(n.bind(null,null,r[e]));var i=e,s={},a={},l,c,u,h;f();function f(){var y=bi.exec(e);l=y[0].length,c=y[0],u=y[0],h="",Gt&&!a[u]?Wt.lstat(u,function(b){if(b)return n(b);a[u]=!0,d()}):process.nextTick(d)}function d(){if(l>=e.length)return r&&(r[i]=e),n(null,e);_t.lastIndex=l;var y=_t.exec(e);return h=c,c+=y[0],u=h+y[1],l=_t.lastIndex,a[u]||r&&r[u]===u?process.nextTick(d):r&&Object.prototype.hasOwnProperty.call(r,u)?g(r[u]):Wt.lstat(u,p)}function p(y,b){if(y)return n(y);if(!b.isSymbolicLink())return a[u]=!0,r&&(r[u]=u),process.nextTick(d);if(!Gt){var D=b.dev.toString(32)+":"+b.ino.toString(32);if(s.hasOwnProperty(D))return m(null,s[D],u)}Wt.stat(u,function(v){if(v)return n(v);Wt.readlink(u,function(S,C){Gt||(s[D]=C),m(S,C)})})}function m(y,b,D){if(y)return n(y);var v=Mr.resolve(h,b);r&&(r[D]=v),g(v)}function g(y){e=Mr.resolve(y,e.slice(l)),f()}}});var fc=$((NF,vm)=>{vm.exports=Zt;Zt.realpath=Zt;Zt.sync=dc;Zt.realpathSync=dc;Zt.monkeypatch=qC;Zt.unmonkeypatch=zC;var Cn=require("fs"),cc=Cn.realpath,uc=Cn.realpathSync,UC=process.version,gm=/^v[0-5]\./.test(UC),ym=mm();function bm(t){return t&&t.syscall==="realpath"&&(t.code==="ELOOP"||t.code==="ENOMEM"||t.code==="ENAMETOOLONG")}function Zt(t,e,r){if(gm)return cc(t,e,r);typeof e=="function"&&(r=e,e=null),cc(t,e,function(n,i){bm(n)?ym.realpath(t,e,r):r(n,i)})}function dc(t,e){if(gm)return uc(t,e);try{return uc(t,e)}catch(r){if(bm(r))return ym.realpathSync(t,e);throw r}}function qC(){Cn.realpath=Zt,Cn.realpathSync=dc}function zC(){Cn.realpath=cc,Cn.realpathSync=uc}});var wm=$(($F,Dm)=>{Dm.exports=function(t,e){for(var r=[],n=0;n<t.length;n++){var i=e(t[n],n);VC(i)?r.push.apply(r,i):r.push(i)}return r};var VC=Array.isArray||function(t){return Object.prototype.toString.call(t)==="[object Array]"}});var xm=$((UF,_m)=>{"use strict";_m.exports=Cm;function Cm(t,e,r){t instanceof RegExp&&(t=Sm(t,r)),e instanceof RegExp&&(e=Sm(e,r));var n=Em(t,e,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+t.length,n[1]),post:r.slice(n[1]+e.length)}}function Sm(t,e){var r=e.match(t);return r?r[0]:null}Cm.range=Em;function Em(t,e,r){var n,i,s,a,l,c=r.indexOf(t),u=r.indexOf(e,c+1),h=c;if(c>=0&&u>0){if(t===e)return[c,u];for(n=[],s=r.length;h>=0&&!l;)h==c?(n.push(h),c=r.indexOf(t,h+1)):n.length==1?l=[n.pop(),u]:(i=n.pop(),i<s&&(s=i,a=u),u=r.indexOf(e,h+1)),h=c<u&&c>=0?c:u;n.length&&(l=[s,a])}return l}});var Rm=$((qF,Im)=>{var WC=wm(),km=xm();Im.exports=KC;var Fm="\0SLASH"+Math.random()+"\0",Pm="\0OPEN"+Math.random()+"\0",pc="\0CLOSE"+Math.random()+"\0",Tm="\0COMMA"+Math.random()+"\0",Am="\0PERIOD"+Math.random()+"\0";function hc(t){return parseInt(t,10)==t?parseInt(t,10):t.charCodeAt(0)}function GC(t){return t.split("\\\\").join(Fm).split("\\{").join(Pm).split("\\}").join(pc).split("\\,").join(Tm).split("\\.").join(Am)}function ZC(t){return t.split(Fm).join("\\").split(Pm).join("{").split(pc).join("}").split(Tm).join(",").split(Am).join(".")}function Om(t){if(!t)return[""];var e=[],r=km("{","}",t);if(!r)return t.split(",");var n=r.pre,i=r.body,s=r.post,a=n.split(",");a[a.length-1]+="{"+i+"}";var l=Om(s);return s.length&&(a[a.length-1]+=l.shift(),a.push.apply(a,l)),e.push.apply(e,a),e}function KC(t){return t?(t.substr(0,2)==="{}"&&(t="\\{\\}"+t.substr(2)),En(GC(t),!0).map(ZC)):[]}function HC(t){return"{"+t+"}"}function YC(t){return/^-?0\d/.test(t)}function JC(t,e){return t<=e}function QC(t,e){return t>=e}function En(t,e){var r=[],n=km("{","}",t);if(!n||/\$$/.test(n.pre))return[t];var i=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(n.body),s=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(n.body),a=i||s,l=n.body.indexOf(",")>=0;if(!a&&!l)return n.post.match(/,(?!,).*\}/)?(t=n.pre+"{"+n.body+pc+n.post,En(t)):[t];var c;if(a)c=n.body.split(/\.\./);else if(c=Om(n.body),c.length===1&&(c=En(c[0],!1).map(HC),c.length===1)){var h=n.post.length?En(n.post,!1):[""];return h.map(function(P){return n.pre+c[0]+P})}var u=n.pre,h=n.post.length?En(n.post,!1):[""],f;if(a){var d=hc(c[0]),p=hc(c[1]),m=Math.max(c[0].length,c[1].length),g=c.length==3?Math.abs(hc(c[2])):1,y=JC,b=p<d;b&&(g*=-1,y=QC);var D=c.some(YC);f=[];for(var v=d;y(v,p);v+=g){var S;if(s)S=String.fromCharCode(v),S==="\\"&&(S="");else if(S=String(v),D){var C=m-S.length;if(C>0){var x=new Array(C+1).join("0");v<0?S="-"+x+S.slice(1):S=x+S}}f.push(S)}}else f=WC(c,function(E){return En(E,!1)});for(var _=0;_<f.length;_++)for(var B=0;B<h.length;B++){var w=u+f[_]+h[B];(!e||a||w)&&r.push(w)}return r}});var no=$((zF,Nm)=>{Nm.exports=Re;Re.Minimatch=ae;var vi=(function(){try{return require("path")}catch{}})()||{sep:"/"};Re.sep=vi.sep;var jr=Re.GLOBSTAR=ae.GLOBSTAR={},XC=Rm(),Mm={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},mc="[^/]",gc=mc+"*?",eE="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",tE="(?:(?!(?:\\/|^)\\.).)*?",jm=rE("().*{}+?[]^$\\!");function rE(t){return t.split("").reduce(function(e,r){return e[r]=!0,e},{})}var Bm=/\/+/;Re.filter=nE;function nE(t,e){return e=e||{},function(r,n,i){return Re(r,t,e)}}function Kt(t,e){e=e||{};var r={};return Object.keys(t).forEach(function(n){r[n]=t[n]}),Object.keys(e).forEach(function(n){r[n]=e[n]}),r}Re.defaults=function(t){if(!t||typeof t!="object"||!Object.keys(t).length)return Re;var e=Re,r=function(i,s,a){return e(i,s,Kt(t,a))};return r.Minimatch=function(i,s){return new e.Minimatch(i,Kt(t,s))},r.Minimatch.defaults=function(i){return e.defaults(Kt(t,i)).Minimatch},r.filter=function(i,s){return e.filter(i,Kt(t,s))},r.defaults=function(i){return e.defaults(Kt(t,i))},r.makeRe=function(i,s){return e.makeRe(i,Kt(t,s))},r.braceExpand=function(i,s){return e.braceExpand(i,Kt(t,s))},r.match=function(n,i,s){return e.match(n,i,Kt(t,s))},r};ae.defaults=function(t){return Re.defaults(t).Minimatch};function Re(t,e,r){return ro(e),r||(r={}),!r.nocomment&&e.charAt(0)==="#"?!1:new ae(e,r).match(t)}function ae(t,e){if(!(this instanceof ae))return new ae(t,e);ro(t),e||(e={}),t=t.trim(),!e.allowWindowsEscape&&vi.sep!=="/"&&(t=t.split(vi.sep).join("/")),this.options=e,this.maxGlobstarRecursion=e.maxGlobstarRecursion!==void 0?e.maxGlobstarRecursion:200,this.set=[],this.pattern=t,this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.make()}ae.prototype.debug=function(){};ae.prototype.make=iE;function iE(){var t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate();var r=this.globSet=this.braceExpand();e.debug&&(this.debug=function(){console.error.apply(console,arguments)}),this.debug(this.pattern,r),r=this.globParts=r.map(function(n){return n.split(Bm)}),this.debug(this.pattern,r),r=r.map(function(n,i,s){return n.map(this.parse,this)},this),this.debug(this.pattern,r),r=r.filter(function(n){return n.indexOf(!1)===-1}),this.debug(this.pattern,r),this.set=r}ae.prototype.parseNegate=sE;function sE(){var t=this.pattern,e=!1,r=this.options,n=0;if(!r.nonegate){for(var i=0,s=t.length;i<s&&t.charAt(i)==="!";i++)e=!e,n++;n&&(this.pattern=t.substr(n)),this.negate=e}}Re.braceExpand=function(t,e){return Lm(t,e)};ae.prototype.braceExpand=Lm;function Lm(t,e){return e||(this instanceof ae?e=this.options:e={}),t=typeof t>"u"?this.pattern:t,ro(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:XC(t)}var oE=1024*64,ro=function(t){if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>oE)throw new TypeError("pattern is too long")};ae.prototype.parse=aE;var to={};function aE(t,e){ro(t);var r=this.options;if(t==="**")if(r.noglobstar)t="*";else return jr;if(t==="")return"";var n="",i=!!r.nocase,s=!1,a=[],l=[],c,u=!1,h=-1,f=-1,d=t.charAt(0)==="."?"":r.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",p=this;function m(){if(c){switch(c){case"*":n+=gc,i=!0;break;case"?":n+=mc,i=!0;break;default:n+="\\"+c;break}p.debug("clearStateChar %j %j",c,n),c=!1}}for(var g=0,y=t.length,b;g<y&&(b=t.charAt(g));g++){if(this.debug("%s %s %s %j",t,g,n,b),s&&jm[b]){n+="\\"+b,s=!1;continue}switch(b){case"/":return!1;case"\\":m(),s=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s %s %s %j <-- stateChar",t,g,n,b),u){this.debug(" in class"),b==="!"&&g===f+1&&(b="^"),n+=b;continue}if(b==="*"&&c==="*")continue;p.debug("call clearStateChar %j",c),m(),c=b,r.noext&&m();continue;case"(":if(u){n+="(";continue}if(!c){n+="\\(";continue}a.push({type:c,start:g-1,reStart:n.length,open:Mm[c].open,close:Mm[c].close}),n+=c==="!"?"(?:(?!(?:":"(?:",this.debug("plType %j %j",c,n),c=!1;continue;case")":if(u||!a.length){n+="\\)";continue}m(),i=!0;var D=a.pop();n+=D.close,D.type==="!"&&l.push(D),D.reEnd=n.length;continue;case"|":if(u||!a.length||s){n+="\\|",s=!1;continue}m(),n+="|";continue;case"[":if(m(),u){n+="\\"+b;continue}u=!0,f=g,h=n.length,n+=b;continue;case"]":if(g===f+1||!u){n+="\\"+b,s=!1;continue}var v=t.substring(f+1,g);try{RegExp("["+v+"]")}catch{var S=this.parse(v,to);n=n.substr(0,h)+"\\["+S[0]+"\\]",i=i||S[1],u=!1;continue}i=!0,u=!1,n+=b;continue;default:m(),s?s=!1:jm[b]&&!(b==="^"&&u)&&(n+="\\"),n+=b}}for(u&&(v=t.substr(f+1),S=this.parse(v,to),n=n.substr(0,h)+"\\["+S[0],i=i||S[1]),D=a.pop();D;D=a.pop()){var C=n.slice(D.reStart+D.open.length);this.debug("setting tail",n,D),C=C.replace(/((?:\\{2}){0,64})(\\?)\|/g,function(kt,ge,N){return N||(N="\\"),ge+ge+N+"|"}),this.debug(`tail=%j
96
- %s`,C,C,D,n);var x=D.type==="*"?gc:D.type==="?"?mc:"\\"+D.type;i=!0,n=n.slice(0,D.reStart)+x+"\\("+C}m(),s&&(n+="\\\\");var _=!1;switch(n.charAt(0)){case"[":case".":case"(":_=!0}for(var B=l.length-1;B>-1;B--){var w=l[B],E=n.slice(0,w.reStart),P=n.slice(w.reStart,w.reEnd-8),q=n.slice(w.reEnd-8,w.reEnd),W=n.slice(w.reEnd);q+=W;var V=E.split("(").length-1,pe=W;for(g=0;g<V;g++)pe=pe.replace(/\)[+*?]?/,"");W=pe;var me="";W===""&&e!==to&&(me="$");var ve=E+P+W+me+q;n=ve}if(n!==""&&i&&(n="(?=.)"+n),_&&(n=d+n),e===to)return[n,i];if(!i)return cE(t);var J=r.nocase?"i":"";try{var De=new RegExp("^"+n+"$",J)}catch{return new RegExp("$.")}return De._glob=t,De._src=n,De}Re.makeRe=function(t,e){return new ae(t,e||{}).makeRe()};ae.prototype.makeRe=lE;function lE(){if(this.regexp||this.regexp===!1)return this.regexp;var t=this.set;if(!t.length)return this.regexp=!1,this.regexp;var e=this.options,r=e.noglobstar?gc:e.dot?eE:tE,n=e.nocase?"i":"",i=t.map(function(s){return s.map(function(a){return a===jr?r:typeof a=="string"?uE(a):a._src}).join("\\/")}).join("|");i="^(?:"+i+")$",this.negate&&(i="^(?!"+i+").*$");try{this.regexp=new RegExp(i,n)}catch{this.regexp=!1}return this.regexp}Re.match=function(t,e,r){r=r||{};var n=new ae(e,r);return t=t.filter(function(i){return n.match(i)}),n.options.nonull&&!t.length&&t.push(e),t};ae.prototype.match=function(e,r){if(typeof r>"u"&&(r=this.partial),this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&r)return!0;var n=this.options;vi.sep!=="/"&&(e=e.split(vi.sep).join("/")),e=e.split(Bm),this.debug(this.pattern,"split",e);var i=this.set;this.debug(this.pattern,"set",i);var s,a;for(a=e.length-1;a>=0&&(s=e[a],!s);a--);for(a=0;a<i.length;a++){var l=i[a],c=e;n.matchBase&&l.length===1&&(c=[s]);var u=this.matchOne(c,l,r);if(u)return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate};ae.prototype.matchOne=function(t,e,r){return e.indexOf(jr)!==-1?this._matchGlobstar(t,e,r,0,0):this._matchOne(t,e,r,0,0)};ae.prototype._matchGlobstar=function(t,e,r,n,i){var s,a=-1;for(s=i;s<e.length;s++)if(e[s]===jr){a=s;break}var l=-1;for(s=e.length-1;s>=0;s--)if(e[s]===jr){l=s;break}var c=e.slice(i,a),u=r?e.slice(a+1):e.slice(a+1,l),h=r?[]:e.slice(l+1);if(c.length){var f=t.slice(n,n+c.length);if(!this._matchOne(f,c,r,0,0))return!1;n+=c.length}var d=0;if(h.length){if(h.length+n>t.length)return!1;var p=t.length-h.length;if(this._matchOne(t,h,r,p,0))d=h.length;else{if(t[t.length-1]!==""||n+h.length===t.length||(p--,!this._matchOne(t,h,r,p,0)))return!1;d=h.length+1}}if(!u.length){var m=!!d;for(s=n;s<t.length-d;s++){var g=String(t[s]);if(m=!0,g==="."||g===".."||!this.options.dot&&g.charAt(0)===".")return!1}return r||m}for(var y=[[[],0]],b=y[0],D=0,v=[0],S=0;S<u.length;S++){var C=u[S];C===jr?(v.push(D),b=[[],0],y.push(b)):(b[0].push(C),D++)}for(var x=y.length-1,_=t.length-d,B=0;B<y.length;B++)y[B][1]=_-(v[x--]+y[B][0].length);return!!this._matchGlobStarBodySections(t,y,n,0,r,0,!!d)};ae.prototype._matchGlobStarBodySections=function(t,e,r,n,i,s,a){var l=e[n];if(!l){for(var c=r;c<t.length;c++){a=!0;var u=t[c];if(u==="."||u===".."||!this.options.dot&&u.charAt(0)===".")return!1}return a}for(var h=l[0],f=l[1];r<=f;){var d=this._matchOne(t.slice(0,r+h.length),h,i,r,0);if(d&&s<this.maxGlobstarRecursion){var p=this._matchGlobStarBodySections(t,e,r+h.length,n+1,i,s+1,a);if(p!==!1)return p}var u=t[r];if(u==="."||u===".."||!this.options.dot&&u.charAt(0)===".")return!1;r++}return i||null};ae.prototype._matchOne=function(t,e,r,n,i){var s,a,l,c;for(s=n,a=i,l=t.length,c=e.length;s<l&&a<c;s++,a++){this.debug("matchOne loop");var u=e[a],h=t[s];if(this.debug(e,u,h),u===!1||u===jr)return!1;var f;if(typeof u=="string"?(f=h===u,this.debug("string match",u,h,f)):(f=h.match(u),this.debug("pattern match",u,h,f)),!f)return!1}if(s===l&&a===c)return!0;if(s===l)return r;if(a===c)return s===l-1&&t[s]==="";throw new Error("wtf?")};function cE(t){return t.replace(/\\(.)/g,"$1")}function uE(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var $m=$((VF,yc)=>{typeof Object.create=="function"?yc.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:yc.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var Um=$((WF,vc)=>{try{if(bc=require("util"),typeof bc.inherits!="function")throw"";vc.exports=bc.inherits}catch{vc.exports=$m()}var bc});var so=$((GF,io)=>{"use strict";function qm(t){return t.charAt(0)==="/"}function zm(t){var e=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,r=e.exec(t),n=r[1]||"",i=!!(n&&n.charAt(1)!==":");return!!(r[2]||i)}io.exports=process.platform==="win32"?zm:qm;io.exports.posix=qm;io.exports.win32=zm});var wc=$(Ht=>{Ht.setopts=gE;Ht.ownProp=Vm;Ht.makeAbs=Di;Ht.finish=yE;Ht.mark=bE;Ht.isIgnored=Gm;Ht.childrenIgnored=vE;function Vm(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var dE=require("fs"),_n=require("path"),fE=no(),Wm=so(),Dc=fE.Minimatch;function hE(t,e){return t.localeCompare(e,"en")}function pE(t,e){t.ignore=e.ignore||[],Array.isArray(t.ignore)||(t.ignore=[t.ignore]),t.ignore.length&&(t.ignore=t.ignore.map(mE))}function mE(t){var e=null;if(t.slice(-3)==="/**"){var r=t.replace(/(\/\*\*)+$/,"");e=new Dc(r,{dot:!0})}return{matcher:new Dc(t,{dot:!0}),gmatcher:e}}function gE(t,e,r){if(r||(r={}),r.matchBase&&e.indexOf("/")===-1){if(r.noglobstar)throw new Error("base matching requires globstar");e="**/"+e}t.silent=!!r.silent,t.pattern=e,t.strict=r.strict!==!1,t.realpath=!!r.realpath,t.realpathCache=r.realpathCache||Object.create(null),t.follow=!!r.follow,t.dot=!!r.dot,t.mark=!!r.mark,t.nodir=!!r.nodir,t.nodir&&(t.mark=!0),t.sync=!!r.sync,t.nounique=!!r.nounique,t.nonull=!!r.nonull,t.nosort=!!r.nosort,t.nocase=!!r.nocase,t.stat=!!r.stat,t.noprocess=!!r.noprocess,t.absolute=!!r.absolute,t.fs=r.fs||dE,t.maxLength=r.maxLength||1/0,t.cache=r.cache||Object.create(null),t.statCache=r.statCache||Object.create(null),t.symlinks=r.symlinks||Object.create(null),pE(t,r),t.changedCwd=!1;var n=process.cwd();Vm(r,"cwd")?(t.cwd=_n.resolve(r.cwd),t.changedCwd=t.cwd!==n):t.cwd=n,t.root=r.root||_n.resolve(t.cwd,"/"),t.root=_n.resolve(t.root),process.platform==="win32"&&(t.root=t.root.replace(/\\/g,"/")),t.cwdAbs=Wm(t.cwd)?t.cwd:Di(t,t.cwd),process.platform==="win32"&&(t.cwdAbs=t.cwdAbs.replace(/\\/g,"/")),t.nomount=!!r.nomount,r.nonegate=!0,r.nocomment=!0,r.allowWindowsEscape=!1,t.minimatch=new Dc(e,r),t.options=t.minimatch.options}function yE(t){for(var e=t.nounique,r=e?[]:Object.create(null),n=0,i=t.matches.length;n<i;n++){var s=t.matches[n];if(!s||Object.keys(s).length===0){if(t.nonull){var a=t.minimatch.globSet[n];e?r.push(a):r[a]=!0}}else{var l=Object.keys(s);e?r.push.apply(r,l):l.forEach(function(c){r[c]=!0})}}if(e||(r=Object.keys(r)),t.nosort||(r=r.sort(hE)),t.mark){for(var n=0;n<r.length;n++)r[n]=t._mark(r[n]);t.nodir&&(r=r.filter(function(c){var u=!/\/$/.test(c),h=t.cache[c]||t.cache[Di(t,c)];return u&&h&&(u=h!=="DIR"&&!Array.isArray(h)),u}))}t.ignore.length&&(r=r.filter(function(c){return!Gm(t,c)})),t.found=r}function bE(t,e){var r=Di(t,e),n=t.cache[r],i=e;if(n){var s=n==="DIR"||Array.isArray(n),a=e.slice(-1)==="/";if(s&&!a?i+="/":!s&&a&&(i=i.slice(0,-1)),i!==e){var l=Di(t,i);t.statCache[l]=t.statCache[r],t.cache[l]=t.cache[r]}}return i}function Di(t,e){var r=e;return e.charAt(0)==="/"?r=_n.join(t.root,e):Wm(e)||e===""?r=e:t.changedCwd?r=_n.resolve(t.cwd,e):r=_n.resolve(e),process.platform==="win32"&&(r=r.replace(/\\/g,"/")),r}function Gm(t,e){return t.ignore.length?t.ignore.some(function(r){return r.matcher.match(e)||!!(r.gmatcher&&r.gmatcher.match(e))}):!1}function vE(t,e){return t.ignore.length?t.ignore.some(function(r){return!!(r.gmatcher&&r.gmatcher.match(e))}):!1}});var Jm=$((JF,Ym)=>{Ym.exports=Hm;Hm.GlobSync=ce;var DE=fc(),Zm=no(),KF=Zm.Minimatch,HF=Ec().Glob,YF=require("util"),Sc=require("path"),Km=require("assert"),oo=so(),Br=wc(),wE=Br.setopts,Cc=Br.ownProp,SE=Br.childrenIgnored,CE=Br.isIgnored;function Hm(t,e){if(typeof e=="function"||arguments.length===3)throw new TypeError(`callback provided to sync glob
94
+ DP-2-3 disconnected (normal left inverted right x axis y axis)`;function fm(t){return t.split(`
95
+ `).filter(e=>e.indexOf(" connected ")>0).filter(e=>e.search(/\dx\d/)>0).map((e,r)=>{let n=e.split(" "),i=n[0],s=n[2]==="primary",a=s?n[3]:n[2],l=a.split(/[x+]/),c=+l[0],u=+l[1],h=+l[2],f=+l[3];return{width:c,height:u,name:i,id:i,offsetX:h,offsetY:f,primary:s,crop:a}})}function hm(){return new Promise((t,e)=>{RC("xrandr --current",(r,n)=>r?e(r):t(fm(n)))})}function BC(t){let e=0;return t.forEach(r=>{e+=r.height*r.width}),e}function LC(t){switch(dm.extname(t)){case".jpg":case".jpeg":return"jpeg";case".png":return"png"}return"jpeg"}function Sn(t={}){return new Promise((e,r)=>{hm().then(n=>{let i=n.find(t.screen?f=>f.id===t.screen:f=>f.primary||f.id==="default")||n[0],s=["jpg","jpeg","png","tiff","bmp","gif"],a=(t.format||LC(t.filename||"")).toLowerCase();if(!s.includes(a))return r(new Error("Invalid format"));let l=t.filename?t.filename.replace(/[^a-zA-Z0-9._\-/]/g,""):"-",c=t.filename?{}:{encoding:"buffer",maxBuffer:BC(n)},u,h;t.linuxLibrary==="scrot"?(u="scrot",h=[l,"-e","-z",'echo "'+l+'"']):(u="import",h=["-silent","-window","root","-crop",i.crop,"-screen",a+":"+l]),require("child_process").execFile(u,h,c,(f,d)=>f?r(f):e(t.filename?dm.resolve(l):d))})})}Sn.listDisplays=hm;Sn.parseDisplaysOutput=fm;Sn.EXAMPLE_DISPLAYS_OUTPUT=jC;Sn.all=()=>MC(Sn);pm.exports=Sn});var gm=$(cc=>{var Mr=require("path"),Gt=process.platform==="win32",Wt=require("fs"),NC=process.env.NODE_DEBUG&&/fs/.test(process.env.NODE_DEBUG);function $C(){var t;if(NC){var e=new Error;t=r}else t=n;return t;function r(i){i&&(e.message=i.message,i=e,n(i))}function n(i){if(i){if(process.throwDeprecation)throw i;if(!process.noDeprecation){var s="fs: missing callback "+(i.stack||i.message);process.traceDeprecation?console.trace(s):console.error(s)}}}}function UC(t){return typeof t=="function"?t:$C()}var LF=Mr.normalize;Gt?xt=/(.*?)(?:[\/\\]+|$)/g:xt=/(.*?)(?:[\/]+|$)/g;var xt;Gt?bi=/^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/:bi=/^[\/]*/;var bi;cc.realpathSync=function(e,r){if(e=Mr.resolve(e),r&&Object.prototype.hasOwnProperty.call(r,e))return r[e];var n=e,i={},s={},a,l,c,u;h();function h(){var y=bi.exec(e);a=y[0].length,l=y[0],c=y[0],u="",Gt&&!s[c]&&(Wt.lstatSync(c),s[c]=!0)}for(;a<e.length;){xt.lastIndex=a;var f=xt.exec(e);if(u=l,l+=f[0],c=u+f[1],a=xt.lastIndex,!(s[c]||r&&r[c]===c)){var d;if(r&&Object.prototype.hasOwnProperty.call(r,c))d=r[c];else{var p=Wt.lstatSync(c);if(!p.isSymbolicLink()){s[c]=!0,r&&(r[c]=c);continue}var m=null;if(!Gt){var g=p.dev.toString(32)+":"+p.ino.toString(32);i.hasOwnProperty(g)&&(m=i[g])}m===null&&(Wt.statSync(c),m=Wt.readlinkSync(c)),d=Mr.resolve(u,m),r&&(r[c]=d),Gt||(i[g]=m)}e=Mr.resolve(d,e.slice(a)),h()}}return r&&(r[n]=e),e};cc.realpath=function(e,r,n){if(typeof n!="function"&&(n=UC(r),r=null),e=Mr.resolve(e),r&&Object.prototype.hasOwnProperty.call(r,e))return process.nextTick(n.bind(null,null,r[e]));var i=e,s={},a={},l,c,u,h;f();function f(){var y=bi.exec(e);l=y[0].length,c=y[0],u=y[0],h="",Gt&&!a[u]?Wt.lstat(u,function(b){if(b)return n(b);a[u]=!0,d()}):process.nextTick(d)}function d(){if(l>=e.length)return r&&(r[i]=e),n(null,e);xt.lastIndex=l;var y=xt.exec(e);return h=c,c+=y[0],u=h+y[1],l=xt.lastIndex,a[u]||r&&r[u]===u?process.nextTick(d):r&&Object.prototype.hasOwnProperty.call(r,u)?g(r[u]):Wt.lstat(u,p)}function p(y,b){if(y)return n(y);if(!b.isSymbolicLink())return a[u]=!0,r&&(r[u]=u),process.nextTick(d);if(!Gt){var D=b.dev.toString(32)+":"+b.ino.toString(32);if(s.hasOwnProperty(D))return m(null,s[D],u)}Wt.stat(u,function(v){if(v)return n(v);Wt.readlink(u,function(S,C){Gt||(s[D]=C),m(S,C)})})}function m(y,b,D){if(y)return n(y);var v=Mr.resolve(h,b);r&&(r[D]=v),g(v)}function g(y){e=Mr.resolve(y,e.slice(l)),f()}}});var hc=$(($F,Dm)=>{Dm.exports=Zt;Zt.realpath=Zt;Zt.sync=fc;Zt.realpathSync=fc;Zt.monkeypatch=zC;Zt.unmonkeypatch=VC;var Cn=require("fs"),uc=Cn.realpath,dc=Cn.realpathSync,qC=process.version,ym=/^v[0-5]\./.test(qC),bm=gm();function vm(t){return t&&t.syscall==="realpath"&&(t.code==="ELOOP"||t.code==="ENOMEM"||t.code==="ENAMETOOLONG")}function Zt(t,e,r){if(ym)return uc(t,e,r);typeof e=="function"&&(r=e,e=null),uc(t,e,function(n,i){vm(n)?bm.realpath(t,e,r):r(n,i)})}function fc(t,e){if(ym)return dc(t,e);try{return dc(t,e)}catch(r){if(vm(r))return bm.realpathSync(t,e);throw r}}function zC(){Cn.realpath=Zt,Cn.realpathSync=fc}function VC(){Cn.realpath=uc,Cn.realpathSync=dc}});var Sm=$((UF,wm)=>{wm.exports=function(t,e){for(var r=[],n=0;n<t.length;n++){var i=e(t[n],n);WC(i)?r.push.apply(r,i):r.push(i)}return r};var WC=Array.isArray||function(t){return Object.prototype.toString.call(t)==="[object Array]"}});var km=$((qF,xm)=>{"use strict";xm.exports=Em;function Em(t,e,r){t instanceof RegExp&&(t=Cm(t,r)),e instanceof RegExp&&(e=Cm(e,r));var n=_m(t,e,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+t.length,n[1]),post:r.slice(n[1]+e.length)}}function Cm(t,e){var r=e.match(t);return r?r[0]:null}Em.range=_m;function _m(t,e,r){var n,i,s,a,l,c=r.indexOf(t),u=r.indexOf(e,c+1),h=c;if(c>=0&&u>0){if(t===e)return[c,u];for(n=[],s=r.length;h>=0&&!l;)h==c?(n.push(h),c=r.indexOf(t,h+1)):n.length==1?l=[n.pop(),u]:(i=n.pop(),i<s&&(s=i,a=u),u=r.indexOf(e,h+1)),h=c<u&&c>=0?c:u;n.length&&(l=[s,a])}return l}});var Mm=$((zF,Rm)=>{var GC=Sm(),Fm=km();Rm.exports=HC;var Pm="\0SLASH"+Math.random()+"\0",Tm="\0OPEN"+Math.random()+"\0",mc="\0CLOSE"+Math.random()+"\0",Am="\0COMMA"+Math.random()+"\0",Om="\0PERIOD"+Math.random()+"\0";function pc(t){return parseInt(t,10)==t?parseInt(t,10):t.charCodeAt(0)}function ZC(t){return t.split("\\\\").join(Pm).split("\\{").join(Tm).split("\\}").join(mc).split("\\,").join(Am).split("\\.").join(Om)}function KC(t){return t.split(Pm).join("\\").split(Tm).join("{").split(mc).join("}").split(Am).join(",").split(Om).join(".")}function Im(t){if(!t)return[""];var e=[],r=Fm("{","}",t);if(!r)return t.split(",");var n=r.pre,i=r.body,s=r.post,a=n.split(",");a[a.length-1]+="{"+i+"}";var l=Im(s);return s.length&&(a[a.length-1]+=l.shift(),a.push.apply(a,l)),e.push.apply(e,a),e}function HC(t){return t?(t.substr(0,2)==="{}"&&(t="\\{\\}"+t.substr(2)),En(ZC(t),!0).map(KC)):[]}function YC(t){return"{"+t+"}"}function JC(t){return/^-?0\d/.test(t)}function QC(t,e){return t<=e}function XC(t,e){return t>=e}function En(t,e){var r=[],n=Fm("{","}",t);if(!n||/\$$/.test(n.pre))return[t];var i=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(n.body),s=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(n.body),a=i||s,l=n.body.indexOf(",")>=0;if(!a&&!l)return n.post.match(/,(?!,).*\}/)?(t=n.pre+"{"+n.body+mc+n.post,En(t)):[t];var c;if(a)c=n.body.split(/\.\./);else if(c=Im(n.body),c.length===1&&(c=En(c[0],!1).map(YC),c.length===1)){var h=n.post.length?En(n.post,!1):[""];return h.map(function(P){return n.pre+c[0]+P})}var u=n.pre,h=n.post.length?En(n.post,!1):[""],f;if(a){var d=pc(c[0]),p=pc(c[1]),m=Math.max(c[0].length,c[1].length),g=c.length==3?Math.abs(pc(c[2])):1,y=QC,b=p<d;b&&(g*=-1,y=XC);var D=c.some(JC);f=[];for(var v=d;y(v,p);v+=g){var S;if(s)S=String.fromCharCode(v),S==="\\"&&(S="");else if(S=String(v),D){var C=m-S.length;if(C>0){var x=new Array(C+1).join("0");v<0?S="-"+x+S.slice(1):S=x+S}}f.push(S)}}else f=GC(c,function(E){return En(E,!1)});for(var _=0;_<f.length;_++)for(var B=0;B<h.length;B++){var w=u+f[_]+h[B];(!e||a||w)&&r.push(w)}return r}});var no=$((VF,$m)=>{$m.exports=Me;Me.Minimatch=ae;var vi=(function(){try{return require("path")}catch{}})()||{sep:"/"};Me.sep=vi.sep;var jr=Me.GLOBSTAR=ae.GLOBSTAR={},eE=Mm(),jm={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},gc="[^/]",yc=gc+"*?",tE="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",rE="(?:(?!(?:\\/|^)\\.).)*?",Bm=nE("().*{}+?[]^$\\!");function nE(t){return t.split("").reduce(function(e,r){return e[r]=!0,e},{})}var Lm=/\/+/;Me.filter=iE;function iE(t,e){return e=e||{},function(r,n,i){return Me(r,t,e)}}function Kt(t,e){e=e||{};var r={};return Object.keys(t).forEach(function(n){r[n]=t[n]}),Object.keys(e).forEach(function(n){r[n]=e[n]}),r}Me.defaults=function(t){if(!t||typeof t!="object"||!Object.keys(t).length)return Me;var e=Me,r=function(i,s,a){return e(i,s,Kt(t,a))};return r.Minimatch=function(i,s){return new e.Minimatch(i,Kt(t,s))},r.Minimatch.defaults=function(i){return e.defaults(Kt(t,i)).Minimatch},r.filter=function(i,s){return e.filter(i,Kt(t,s))},r.defaults=function(i){return e.defaults(Kt(t,i))},r.makeRe=function(i,s){return e.makeRe(i,Kt(t,s))},r.braceExpand=function(i,s){return e.braceExpand(i,Kt(t,s))},r.match=function(n,i,s){return e.match(n,i,Kt(t,s))},r};ae.defaults=function(t){return Me.defaults(t).Minimatch};function Me(t,e,r){return ro(e),r||(r={}),!r.nocomment&&e.charAt(0)==="#"?!1:new ae(e,r).match(t)}function ae(t,e){if(!(this instanceof ae))return new ae(t,e);ro(t),e||(e={}),t=t.trim(),!e.allowWindowsEscape&&vi.sep!=="/"&&(t=t.split(vi.sep).join("/")),this.options=e,this.maxGlobstarRecursion=e.maxGlobstarRecursion!==void 0?e.maxGlobstarRecursion:200,this.set=[],this.pattern=t,this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.make()}ae.prototype.debug=function(){};ae.prototype.make=sE;function sE(){var t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate();var r=this.globSet=this.braceExpand();e.debug&&(this.debug=function(){console.error.apply(console,arguments)}),this.debug(this.pattern,r),r=this.globParts=r.map(function(n){return n.split(Lm)}),this.debug(this.pattern,r),r=r.map(function(n,i,s){return n.map(this.parse,this)},this),this.debug(this.pattern,r),r=r.filter(function(n){return n.indexOf(!1)===-1}),this.debug(this.pattern,r),this.set=r}ae.prototype.parseNegate=oE;function oE(){var t=this.pattern,e=!1,r=this.options,n=0;if(!r.nonegate){for(var i=0,s=t.length;i<s&&t.charAt(i)==="!";i++)e=!e,n++;n&&(this.pattern=t.substr(n)),this.negate=e}}Me.braceExpand=function(t,e){return Nm(t,e)};ae.prototype.braceExpand=Nm;function Nm(t,e){return e||(this instanceof ae?e=this.options:e={}),t=typeof t>"u"?this.pattern:t,ro(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:eE(t)}var aE=1024*64,ro=function(t){if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>aE)throw new TypeError("pattern is too long")};ae.prototype.parse=lE;var to={};function lE(t,e){ro(t);var r=this.options;if(t==="**")if(r.noglobstar)t="*";else return jr;if(t==="")return"";var n="",i=!!r.nocase,s=!1,a=[],l=[],c,u=!1,h=-1,f=-1,d=t.charAt(0)==="."?"":r.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",p=this;function m(){if(c){switch(c){case"*":n+=yc,i=!0;break;case"?":n+=gc,i=!0;break;default:n+="\\"+c;break}p.debug("clearStateChar %j %j",c,n),c=!1}}for(var g=0,y=t.length,b;g<y&&(b=t.charAt(g));g++){if(this.debug("%s %s %s %j",t,g,n,b),s&&Bm[b]){n+="\\"+b,s=!1;continue}switch(b){case"/":return!1;case"\\":m(),s=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s %s %s %j <-- stateChar",t,g,n,b),u){this.debug(" in class"),b==="!"&&g===f+1&&(b="^"),n+=b;continue}if(b==="*"&&c==="*")continue;p.debug("call clearStateChar %j",c),m(),c=b,r.noext&&m();continue;case"(":if(u){n+="(";continue}if(!c){n+="\\(";continue}a.push({type:c,start:g-1,reStart:n.length,open:jm[c].open,close:jm[c].close}),n+=c==="!"?"(?:(?!(?:":"(?:",this.debug("plType %j %j",c,n),c=!1;continue;case")":if(u||!a.length){n+="\\)";continue}m(),i=!0;var D=a.pop();n+=D.close,D.type==="!"&&l.push(D),D.reEnd=n.length;continue;case"|":if(u||!a.length||s){n+="\\|",s=!1;continue}m(),n+="|";continue;case"[":if(m(),u){n+="\\"+b;continue}u=!0,f=g,h=n.length,n+=b;continue;case"]":if(g===f+1||!u){n+="\\"+b,s=!1;continue}var v=t.substring(f+1,g);try{RegExp("["+v+"]")}catch{var S=this.parse(v,to);n=n.substr(0,h)+"\\["+S[0]+"\\]",i=i||S[1],u=!1;continue}i=!0,u=!1,n+=b;continue;default:m(),s?s=!1:Bm[b]&&!(b==="^"&&u)&&(n+="\\"),n+=b}}for(u&&(v=t.substr(f+1),S=this.parse(v,to),n=n.substr(0,h)+"\\["+S[0],i=i||S[1]),D=a.pop();D;D=a.pop()){var C=n.slice(D.reStart+D.open.length);this.debug("setting tail",n,D),C=C.replace(/((?:\\{2}){0,64})(\\?)\|/g,function(kt,ge,N){return N||(N="\\"),ge+ge+N+"|"}),this.debug(`tail=%j
96
+ %s`,C,C,D,n);var x=D.type==="*"?yc:D.type==="?"?gc:"\\"+D.type;i=!0,n=n.slice(0,D.reStart)+x+"\\("+C}m(),s&&(n+="\\\\");var _=!1;switch(n.charAt(0)){case"[":case".":case"(":_=!0}for(var B=l.length-1;B>-1;B--){var w=l[B],E=n.slice(0,w.reStart),P=n.slice(w.reStart,w.reEnd-8),q=n.slice(w.reEnd-8,w.reEnd),W=n.slice(w.reEnd);q+=W;var V=E.split("(").length-1,pe=W;for(g=0;g<V;g++)pe=pe.replace(/\)[+*?]?/,"");W=pe;var me="";W===""&&e!==to&&(me="$");var ve=E+P+W+me+q;n=ve}if(n!==""&&i&&(n="(?=.)"+n),_&&(n=d+n),e===to)return[n,i];if(!i)return uE(t);var J=r.nocase?"i":"";try{var De=new RegExp("^"+n+"$",J)}catch{return new RegExp("$.")}return De._glob=t,De._src=n,De}Me.makeRe=function(t,e){return new ae(t,e||{}).makeRe()};ae.prototype.makeRe=cE;function cE(){if(this.regexp||this.regexp===!1)return this.regexp;var t=this.set;if(!t.length)return this.regexp=!1,this.regexp;var e=this.options,r=e.noglobstar?yc:e.dot?tE:rE,n=e.nocase?"i":"",i=t.map(function(s){return s.map(function(a){return a===jr?r:typeof a=="string"?dE(a):a._src}).join("\\/")}).join("|");i="^(?:"+i+")$",this.negate&&(i="^(?!"+i+").*$");try{this.regexp=new RegExp(i,n)}catch{this.regexp=!1}return this.regexp}Me.match=function(t,e,r){r=r||{};var n=new ae(e,r);return t=t.filter(function(i){return n.match(i)}),n.options.nonull&&!t.length&&t.push(e),t};ae.prototype.match=function(e,r){if(typeof r>"u"&&(r=this.partial),this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&r)return!0;var n=this.options;vi.sep!=="/"&&(e=e.split(vi.sep).join("/")),e=e.split(Lm),this.debug(this.pattern,"split",e);var i=this.set;this.debug(this.pattern,"set",i);var s,a;for(a=e.length-1;a>=0&&(s=e[a],!s);a--);for(a=0;a<i.length;a++){var l=i[a],c=e;n.matchBase&&l.length===1&&(c=[s]);var u=this.matchOne(c,l,r);if(u)return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate};ae.prototype.matchOne=function(t,e,r){return e.indexOf(jr)!==-1?this._matchGlobstar(t,e,r,0,0):this._matchOne(t,e,r,0,0)};ae.prototype._matchGlobstar=function(t,e,r,n,i){var s,a=-1;for(s=i;s<e.length;s++)if(e[s]===jr){a=s;break}var l=-1;for(s=e.length-1;s>=0;s--)if(e[s]===jr){l=s;break}var c=e.slice(i,a),u=r?e.slice(a+1):e.slice(a+1,l),h=r?[]:e.slice(l+1);if(c.length){var f=t.slice(n,n+c.length);if(!this._matchOne(f,c,r,0,0))return!1;n+=c.length}var d=0;if(h.length){if(h.length+n>t.length)return!1;var p=t.length-h.length;if(this._matchOne(t,h,r,p,0))d=h.length;else{if(t[t.length-1]!==""||n+h.length===t.length||(p--,!this._matchOne(t,h,r,p,0)))return!1;d=h.length+1}}if(!u.length){var m=!!d;for(s=n;s<t.length-d;s++){var g=String(t[s]);if(m=!0,g==="."||g===".."||!this.options.dot&&g.charAt(0)===".")return!1}return r||m}for(var y=[[[],0]],b=y[0],D=0,v=[0],S=0;S<u.length;S++){var C=u[S];C===jr?(v.push(D),b=[[],0],y.push(b)):(b[0].push(C),D++)}for(var x=y.length-1,_=t.length-d,B=0;B<y.length;B++)y[B][1]=_-(v[x--]+y[B][0].length);return!!this._matchGlobStarBodySections(t,y,n,0,r,0,!!d)};ae.prototype._matchGlobStarBodySections=function(t,e,r,n,i,s,a){var l=e[n];if(!l){for(var c=r;c<t.length;c++){a=!0;var u=t[c];if(u==="."||u===".."||!this.options.dot&&u.charAt(0)===".")return!1}return a}for(var h=l[0],f=l[1];r<=f;){var d=this._matchOne(t.slice(0,r+h.length),h,i,r,0);if(d&&s<this.maxGlobstarRecursion){var p=this._matchGlobStarBodySections(t,e,r+h.length,n+1,i,s+1,a);if(p!==!1)return p}var u=t[r];if(u==="."||u===".."||!this.options.dot&&u.charAt(0)===".")return!1;r++}return i||null};ae.prototype._matchOne=function(t,e,r,n,i){var s,a,l,c;for(s=n,a=i,l=t.length,c=e.length;s<l&&a<c;s++,a++){this.debug("matchOne loop");var u=e[a],h=t[s];if(this.debug(e,u,h),u===!1||u===jr)return!1;var f;if(typeof u=="string"?(f=h===u,this.debug("string match",u,h,f)):(f=h.match(u),this.debug("pattern match",u,h,f)),!f)return!1}if(s===l&&a===c)return!0;if(s===l)return r;if(a===c)return s===l-1&&t[s]==="";throw new Error("wtf?")};function uE(t){return t.replace(/\\(.)/g,"$1")}function dE(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var Um=$((WF,bc)=>{typeof Object.create=="function"?bc.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:bc.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var qm=$((GF,Dc)=>{try{if(vc=require("util"),typeof vc.inherits!="function")throw"";Dc.exports=vc.inherits}catch{Dc.exports=Um()}var vc});var so=$((ZF,io)=>{"use strict";function zm(t){return t.charAt(0)==="/"}function Vm(t){var e=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,r=e.exec(t),n=r[1]||"",i=!!(n&&n.charAt(1)!==":");return!!(r[2]||i)}io.exports=process.platform==="win32"?Vm:zm;io.exports.posix=zm;io.exports.win32=Vm});var Sc=$(Ht=>{Ht.setopts=yE;Ht.ownProp=Wm;Ht.makeAbs=Di;Ht.finish=bE;Ht.mark=vE;Ht.isIgnored=Zm;Ht.childrenIgnored=DE;function Wm(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var fE=require("fs"),_n=require("path"),hE=no(),Gm=so(),wc=hE.Minimatch;function pE(t,e){return t.localeCompare(e,"en")}function mE(t,e){t.ignore=e.ignore||[],Array.isArray(t.ignore)||(t.ignore=[t.ignore]),t.ignore.length&&(t.ignore=t.ignore.map(gE))}function gE(t){var e=null;if(t.slice(-3)==="/**"){var r=t.replace(/(\/\*\*)+$/,"");e=new wc(r,{dot:!0})}return{matcher:new wc(t,{dot:!0}),gmatcher:e}}function yE(t,e,r){if(r||(r={}),r.matchBase&&e.indexOf("/")===-1){if(r.noglobstar)throw new Error("base matching requires globstar");e="**/"+e}t.silent=!!r.silent,t.pattern=e,t.strict=r.strict!==!1,t.realpath=!!r.realpath,t.realpathCache=r.realpathCache||Object.create(null),t.follow=!!r.follow,t.dot=!!r.dot,t.mark=!!r.mark,t.nodir=!!r.nodir,t.nodir&&(t.mark=!0),t.sync=!!r.sync,t.nounique=!!r.nounique,t.nonull=!!r.nonull,t.nosort=!!r.nosort,t.nocase=!!r.nocase,t.stat=!!r.stat,t.noprocess=!!r.noprocess,t.absolute=!!r.absolute,t.fs=r.fs||fE,t.maxLength=r.maxLength||1/0,t.cache=r.cache||Object.create(null),t.statCache=r.statCache||Object.create(null),t.symlinks=r.symlinks||Object.create(null),mE(t,r),t.changedCwd=!1;var n=process.cwd();Wm(r,"cwd")?(t.cwd=_n.resolve(r.cwd),t.changedCwd=t.cwd!==n):t.cwd=n,t.root=r.root||_n.resolve(t.cwd,"/"),t.root=_n.resolve(t.root),process.platform==="win32"&&(t.root=t.root.replace(/\\/g,"/")),t.cwdAbs=Gm(t.cwd)?t.cwd:Di(t,t.cwd),process.platform==="win32"&&(t.cwdAbs=t.cwdAbs.replace(/\\/g,"/")),t.nomount=!!r.nomount,r.nonegate=!0,r.nocomment=!0,r.allowWindowsEscape=!1,t.minimatch=new wc(e,r),t.options=t.minimatch.options}function bE(t){for(var e=t.nounique,r=e?[]:Object.create(null),n=0,i=t.matches.length;n<i;n++){var s=t.matches[n];if(!s||Object.keys(s).length===0){if(t.nonull){var a=t.minimatch.globSet[n];e?r.push(a):r[a]=!0}}else{var l=Object.keys(s);e?r.push.apply(r,l):l.forEach(function(c){r[c]=!0})}}if(e||(r=Object.keys(r)),t.nosort||(r=r.sort(pE)),t.mark){for(var n=0;n<r.length;n++)r[n]=t._mark(r[n]);t.nodir&&(r=r.filter(function(c){var u=!/\/$/.test(c),h=t.cache[c]||t.cache[Di(t,c)];return u&&h&&(u=h!=="DIR"&&!Array.isArray(h)),u}))}t.ignore.length&&(r=r.filter(function(c){return!Zm(t,c)})),t.found=r}function vE(t,e){var r=Di(t,e),n=t.cache[r],i=e;if(n){var s=n==="DIR"||Array.isArray(n),a=e.slice(-1)==="/";if(s&&!a?i+="/":!s&&a&&(i=i.slice(0,-1)),i!==e){var l=Di(t,i);t.statCache[l]=t.statCache[r],t.cache[l]=t.cache[r]}}return i}function Di(t,e){var r=e;return e.charAt(0)==="/"?r=_n.join(t.root,e):Gm(e)||e===""?r=e:t.changedCwd?r=_n.resolve(t.cwd,e):r=_n.resolve(e),process.platform==="win32"&&(r=r.replace(/\\/g,"/")),r}function Zm(t,e){return t.ignore.length?t.ignore.some(function(r){return r.matcher.match(e)||!!(r.gmatcher&&r.gmatcher.match(e))}):!1}function DE(t,e){return t.ignore.length?t.ignore.some(function(r){return!!(r.gmatcher&&r.gmatcher.match(e))}):!1}});var Qm=$((QF,Jm)=>{Jm.exports=Ym;Ym.GlobSync=ce;var wE=hc(),Km=no(),HF=Km.Minimatch,YF=_c().Glob,JF=require("util"),Cc=require("path"),Hm=require("assert"),oo=so(),Br=Sc(),SE=Br.setopts,Ec=Br.ownProp,CE=Br.childrenIgnored,EE=Br.isIgnored;function Ym(t,e){if(typeof e=="function"||arguments.length===3)throw new TypeError(`callback provided to sync glob
97
97
  See: https://github.com/isaacs/node-glob/issues/167`);return new ce(t,e).found}function ce(t,e){if(!t)throw new Error("must provide pattern");if(typeof e=="function"||arguments.length===3)throw new TypeError(`callback provided to sync glob
98
- See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof ce))return new ce(t,e);if(wE(this,t,e),this.noprocess)return this;var r=this.minimatch.set.length;this.matches=new Array(r);for(var n=0;n<r;n++)this._process(this.minimatch.set[n],n,!1);this._finish()}ce.prototype._finish=function(){if(Km.ok(this instanceof ce),this.realpath){var t=this;this.matches.forEach(function(e,r){var n=t.matches[r]=Object.create(null);for(var i in e)try{i=t._makeAbs(i);var s=DE.realpathSync(i,t.realpathCache);n[s]=!0}catch(a){if(a.syscall==="stat")n[t._makeAbs(i)]=!0;else throw a}})}Br.finish(this)};ce.prototype._process=function(t,e,r){Km.ok(this instanceof ce);for(var n=0;typeof t[n]=="string";)n++;var i;switch(n){case t.length:this._processSimple(t.join("/"),e);return;case 0:i=null;break;default:i=t.slice(0,n).join("/");break}var s=t.slice(n),a;i===null?a=".":((oo(i)||oo(t.map(function(u){return typeof u=="string"?u:"[*]"}).join("/")))&&(!i||!oo(i))&&(i="/"+i),a=i);var l=this._makeAbs(a);if(!SE(this,a)){var c=s[0]===Zm.GLOBSTAR;c?this._processGlobStar(i,a,l,s,e,r):this._processReaddir(i,a,l,s,e,r)}};ce.prototype._processReaddir=function(t,e,r,n,i,s){var a=this._readdir(r,s);if(a){for(var l=n[0],c=!!this.minimatch.negate,u=l._glob,h=this.dot||u.charAt(0)===".",f=[],d=0;d<a.length;d++){var p=a[d];if(p.charAt(0)!=="."||h){var m;c&&!t?m=!p.match(l):m=p.match(l),m&&f.push(p)}}var g=f.length;if(g!==0){if(n.length===1&&!this.mark&&!this.stat){this.matches[i]||(this.matches[i]=Object.create(null));for(var d=0;d<g;d++){var p=f[d];t&&(t.slice(-1)!=="/"?p=t+"/"+p:p=t+p),p.charAt(0)==="/"&&!this.nomount&&(p=Sc.join(this.root,p)),this._emitMatch(i,p)}return}n.shift();for(var d=0;d<g;d++){var p=f[d],y;t?y=[t,p]:y=[p],this._process(y.concat(n),i,s)}}}};ce.prototype._emitMatch=function(t,e){if(!CE(this,e)){var r=this._makeAbs(e);if(this.mark&&(e=this._mark(e)),this.absolute&&(e=r),!this.matches[t][e]){if(this.nodir){var n=this.cache[r];if(n==="DIR"||Array.isArray(n))return}this.matches[t][e]=!0,this.stat&&this._stat(e)}}};ce.prototype._readdirInGlobStar=function(t){if(this.follow)return this._readdir(t,!1);var e,r,n;try{r=this.fs.lstatSync(t)}catch(s){if(s.code==="ENOENT")return null}var i=r&&r.isSymbolicLink();return this.symlinks[t]=i,!i&&r&&!r.isDirectory()?this.cache[t]="FILE":e=this._readdir(t,!1),e};ce.prototype._readdir=function(t,e){var r;if(e&&!Cc(this.symlinks,t))return this._readdirInGlobStar(t);if(Cc(this.cache,t)){var n=this.cache[t];if(!n||n==="FILE")return null;if(Array.isArray(n))return n}try{return this._readdirEntries(t,this.fs.readdirSync(t))}catch(i){return this._readdirError(t,i),null}};ce.prototype._readdirEntries=function(t,e){if(!this.mark&&!this.stat)for(var r=0;r<e.length;r++){var n=e[r];t==="/"?n=t+n:n=t+"/"+n,this.cache[n]=!0}return this.cache[t]=e,e};ce.prototype._readdirError=function(t,e){switch(e.code){case"ENOTSUP":case"ENOTDIR":var r=this._makeAbs(t);if(this.cache[r]="FILE",r===this.cwdAbs){var n=new Error(e.code+" invalid cwd "+this.cwd);throw n.path=this.cwd,n.code=e.code,n}break;case"ENOENT":case"ELOOP":case"ENAMETOOLONG":case"UNKNOWN":this.cache[this._makeAbs(t)]=!1;break;default:if(this.cache[this._makeAbs(t)]=!1,this.strict)throw e;this.silent||console.error("glob error",e);break}};ce.prototype._processGlobStar=function(t,e,r,n,i,s){var a=this._readdir(r,s);if(a){var l=n.slice(1),c=t?[t]:[],u=c.concat(l);this._process(u,i,!1);var h=a.length,f=this.symlinks[r];if(!(f&&s))for(var d=0;d<h;d++){var p=a[d];if(!(p.charAt(0)==="."&&!this.dot)){var m=c.concat(a[d],l);this._process(m,i,!0);var g=c.concat(a[d],n);this._process(g,i,!0)}}}};ce.prototype._processSimple=function(t,e){var r=this._stat(t);if(this.matches[e]||(this.matches[e]=Object.create(null)),!!r){if(t&&oo(t)&&!this.nomount){var n=/[\/\\]$/.test(t);t.charAt(0)==="/"?t=Sc.join(this.root,t):(t=Sc.resolve(this.root,t),n&&(t+="/"))}process.platform==="win32"&&(t=t.replace(/\\/g,"/")),this._emitMatch(e,t)}};ce.prototype._stat=function(t){var e=this._makeAbs(t),r=t.slice(-1)==="/";if(t.length>this.maxLength)return!1;if(!this.stat&&Cc(this.cache,e)){var a=this.cache[e];if(Array.isArray(a)&&(a="DIR"),!r||a==="DIR")return a;if(r&&a==="FILE")return!1}var n,i=this.statCache[e];if(!i){var s;try{s=this.fs.lstatSync(e)}catch(l){if(l&&(l.code==="ENOENT"||l.code==="ENOTDIR"))return this.statCache[e]=!1,!1}if(s&&s.isSymbolicLink())try{i=this.fs.statSync(e)}catch{i=s}else i=s}this.statCache[e]=i;var a=!0;return i&&(a=i.isDirectory()?"DIR":"FILE"),this.cache[e]=this.cache[e]||a,r&&a==="FILE"?!1:a};ce.prototype._mark=function(t){return Br.mark(this,t)};ce.prototype._makeAbs=function(t){return Br.makeAbs(this,t)}});var _c=$((QF,Xm)=>{Xm.exports=Qm;function Qm(t,e){if(t&&e)return Qm(t)(e);if(typeof t!="function")throw new TypeError("need wrapper function");return Object.keys(t).forEach(function(n){r[n]=t[n]}),r;function r(){for(var n=new Array(arguments.length),i=0;i<n.length;i++)n[i]=arguments[i];var s=t.apply(this,n),a=n[n.length-1];return typeof s=="function"&&s!==a&&Object.keys(a).forEach(function(l){s[l]=a[l]}),s}}});var kc=$((XF,xc)=>{var eg=_c();xc.exports=eg(ao);xc.exports.strict=eg(tg);ao.proto=ao(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return ao(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return tg(this)},configurable:!0})});function ao(t){var e=function(){return e.called?e.value:(e.called=!0,e.value=t.apply(this,arguments))};return e.called=!1,e}function tg(t){var e=function(){if(e.called)throw new Error(e.onceError);return e.called=!0,e.value=t.apply(this,arguments)},r=t.name||"Function wrapped with `once`";return e.onceError=r+" shouldn't be called more than once",e.called=!1,e}});var ng=$((eP,rg)=>{var EE=_c(),wi=Object.create(null),_E=kc();rg.exports=EE(xE);function xE(t,e){return wi[t]?(wi[t].push(e),null):(wi[t]=[e],kE(t))}function kE(t){return _E(function e(){var r=wi[t],n=r.length,i=FE(arguments);try{for(var s=0;s<n;s++)r[s].apply(null,i)}finally{r.length>n?(r.splice(0,n),process.nextTick(function(){e.apply(null,i)})):delete wi[t]}})}function FE(t){for(var e=t.length,r=[],n=0;n<e;n++)r[n]=t[n];return r}});var Ec=$((nP,sg)=>{sg.exports=Lr;var PE=fc(),ig=no(),tP=ig.Minimatch,TE=Um(),AE=require("events").EventEmitter,Fc=require("path"),Pc=require("assert"),Si=so(),Ac=Jm(),Nr=wc(),OE=Nr.setopts,Tc=Nr.ownProp,Oc=ng(),rP=require("util"),IE=Nr.childrenIgnored,RE=Nr.isIgnored,ME=kc();function Lr(t,e,r){if(typeof e=="function"&&(r=e,e={}),e||(e={}),e.sync){if(r)throw new TypeError("callback provided to sync glob");return Ac(t,e)}return new ee(t,e,r)}Lr.sync=Ac;var jE=Lr.GlobSync=Ac.GlobSync;Lr.glob=Lr;function BE(t,e){if(e===null||typeof e!="object")return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}Lr.hasMagic=function(t,e){var r=BE({},e);r.noprocess=!0;var n=new ee(t,r),i=n.minimatch.set;if(!t)return!1;if(i.length>1)return!0;for(var s=0;s<i[0].length;s++)if(typeof i[0][s]!="string")return!0;return!1};Lr.Glob=ee;TE(ee,AE);function ee(t,e,r){if(typeof e=="function"&&(r=e,e=null),e&&e.sync){if(r)throw new TypeError("callback provided to sync glob");return new jE(t,e)}if(!(this instanceof ee))return new ee(t,e,r);OE(this,t,e),this._didRealPath=!1;var n=this.minimatch.set.length;this.matches=new Array(n),typeof r=="function"&&(r=ME(r),this.on("error",r),this.on("end",function(c){r(null,c)}));var i=this;if(this._processing=0,this._emitQueue=[],this._processQueue=[],this.paused=!1,this.noprocess)return this;if(n===0)return l();for(var s=!0,a=0;a<n;a++)this._process(this.minimatch.set[a],a,!1,l);s=!1;function l(){--i._processing,i._processing<=0&&(s?process.nextTick(function(){i._finish()}):i._finish())}}ee.prototype._finish=function(){if(Pc(this instanceof ee),!this.aborted){if(this.realpath&&!this._didRealpath)return this._realpath();Nr.finish(this),this.emit("end",this.found)}};ee.prototype._realpath=function(){if(this._didRealpath)return;this._didRealpath=!0;var t=this.matches.length;if(t===0)return this._finish();for(var e=this,r=0;r<this.matches.length;r++)this._realpathSet(r,n);function n(){--t===0&&e._finish()}};ee.prototype._realpathSet=function(t,e){var r=this.matches[t];if(!r)return e();var n=Object.keys(r),i=this,s=n.length;if(s===0)return e();var a=this.matches[t]=Object.create(null);n.forEach(function(l,c){l=i._makeAbs(l),PE.realpath(l,i.realpathCache,function(u,h){u?u.syscall==="stat"?a[l]=!0:i.emit("error",u):a[h]=!0,--s===0&&(i.matches[t]=a,e())})})};ee.prototype._mark=function(t){return Nr.mark(this,t)};ee.prototype._makeAbs=function(t){return Nr.makeAbs(this,t)};ee.prototype.abort=function(){this.aborted=!0,this.emit("abort")};ee.prototype.pause=function(){this.paused||(this.paused=!0,this.emit("pause"))};ee.prototype.resume=function(){if(this.paused){if(this.emit("resume"),this.paused=!1,this._emitQueue.length){var t=this._emitQueue.slice(0);this._emitQueue.length=0;for(var e=0;e<t.length;e++){var r=t[e];this._emitMatch(r[0],r[1])}}if(this._processQueue.length){var n=this._processQueue.slice(0);this._processQueue.length=0;for(var e=0;e<n.length;e++){var i=n[e];this._processing--,this._process(i[0],i[1],i[2],i[3])}}}};ee.prototype._process=function(t,e,r,n){if(Pc(this instanceof ee),Pc(typeof n=="function"),!this.aborted){if(this._processing++,this.paused){this._processQueue.push([t,e,r,n]);return}for(var i=0;typeof t[i]=="string";)i++;var s;switch(i){case t.length:this._processSimple(t.join("/"),e,n);return;case 0:s=null;break;default:s=t.slice(0,i).join("/");break}var a=t.slice(i),l;s===null?l=".":((Si(s)||Si(t.map(function(h){return typeof h=="string"?h:"[*]"}).join("/")))&&(!s||!Si(s))&&(s="/"+s),l=s);var c=this._makeAbs(l);if(IE(this,l))return n();var u=a[0]===ig.GLOBSTAR;u?this._processGlobStar(s,l,c,a,e,r,n):this._processReaddir(s,l,c,a,e,r,n)}};ee.prototype._processReaddir=function(t,e,r,n,i,s,a){var l=this;this._readdir(r,s,function(c,u){return l._processReaddir2(t,e,r,n,i,s,u,a)})};ee.prototype._processReaddir2=function(t,e,r,n,i,s,a,l){if(!a)return l();for(var c=n[0],u=!!this.minimatch.negate,h=c._glob,f=this.dot||h.charAt(0)===".",d=[],p=0;p<a.length;p++){var m=a[p];if(m.charAt(0)!=="."||f){var g;u&&!t?g=!m.match(c):g=m.match(c),g&&d.push(m)}}var y=d.length;if(y===0)return l();if(n.length===1&&!this.mark&&!this.stat){this.matches[i]||(this.matches[i]=Object.create(null));for(var p=0;p<y;p++){var m=d[p];t&&(t!=="/"?m=t+"/"+m:m=t+m),m.charAt(0)==="/"&&!this.nomount&&(m=Fc.join(this.root,m)),this._emitMatch(i,m)}return l()}n.shift();for(var p=0;p<y;p++){var m=d[p],b;t&&(t!=="/"?m=t+"/"+m:m=t+m),this._process([m].concat(n),i,s,l)}l()};ee.prototype._emitMatch=function(t,e){if(!this.aborted&&!RE(this,e)){if(this.paused){this._emitQueue.push([t,e]);return}var r=Si(e)?e:this._makeAbs(e);if(this.mark&&(e=this._mark(e)),this.absolute&&(e=r),!this.matches[t][e]){if(this.nodir){var n=this.cache[r];if(n==="DIR"||Array.isArray(n))return}this.matches[t][e]=!0;var i=this.statCache[r];i&&this.emit("stat",e,i),this.emit("match",e)}}};ee.prototype._readdirInGlobStar=function(t,e){if(this.aborted)return;if(this.follow)return this._readdir(t,!1,e);var r="lstat\0"+t,n=this,i=Oc(r,s);i&&n.fs.lstat(t,i);function s(a,l){if(a&&a.code==="ENOENT")return e();var c=l&&l.isSymbolicLink();n.symlinks[t]=c,!c&&l&&!l.isDirectory()?(n.cache[t]="FILE",e()):n._readdir(t,!1,e)}};ee.prototype._readdir=function(t,e,r){if(!this.aborted&&(r=Oc("readdir\0"+t+"\0"+e,r),!!r)){if(e&&!Tc(this.symlinks,t))return this._readdirInGlobStar(t,r);if(Tc(this.cache,t)){var n=this.cache[t];if(!n||n==="FILE")return r();if(Array.isArray(n))return r(null,n)}var i=this;i.fs.readdir(t,LE(this,t,r))}};function LE(t,e,r){return function(n,i){n?t._readdirError(e,n,r):t._readdirEntries(e,i,r)}}ee.prototype._readdirEntries=function(t,e,r){if(!this.aborted){if(!this.mark&&!this.stat)for(var n=0;n<e.length;n++){var i=e[n];t==="/"?i=t+i:i=t+"/"+i,this.cache[i]=!0}return this.cache[t]=e,r(null,e)}};ee.prototype._readdirError=function(t,e,r){if(!this.aborted){switch(e.code){case"ENOTSUP":case"ENOTDIR":var n=this._makeAbs(t);if(this.cache[n]="FILE",n===this.cwdAbs){var i=new Error(e.code+" invalid cwd "+this.cwd);i.path=this.cwd,i.code=e.code,this.emit("error",i),this.abort()}break;case"ENOENT":case"ELOOP":case"ENAMETOOLONG":case"UNKNOWN":this.cache[this._makeAbs(t)]=!1;break;default:this.cache[this._makeAbs(t)]=!1,this.strict&&(this.emit("error",e),this.abort()),this.silent||console.error("glob error",e);break}return r()}};ee.prototype._processGlobStar=function(t,e,r,n,i,s,a){var l=this;this._readdir(r,s,function(c,u){l._processGlobStar2(t,e,r,n,i,s,u,a)})};ee.prototype._processGlobStar2=function(t,e,r,n,i,s,a,l){if(!a)return l();var c=n.slice(1),u=t?[t]:[],h=u.concat(c);this._process(h,i,!1,l);var f=this.symlinks[r],d=a.length;if(f&&s)return l();for(var p=0;p<d;p++){var m=a[p];if(!(m.charAt(0)==="."&&!this.dot)){var g=u.concat(a[p],c);this._process(g,i,!0,l);var y=u.concat(a[p],n);this._process(y,i,!0,l)}}l()};ee.prototype._processSimple=function(t,e,r){var n=this;this._stat(t,function(i,s){n._processSimple2(t,e,i,s,r)})};ee.prototype._processSimple2=function(t,e,r,n,i){if(this.matches[e]||(this.matches[e]=Object.create(null)),!n)return i();if(t&&Si(t)&&!this.nomount){var s=/[\/\\]$/.test(t);t.charAt(0)==="/"?t=Fc.join(this.root,t):(t=Fc.resolve(this.root,t),s&&(t+="/"))}process.platform==="win32"&&(t=t.replace(/\\/g,"/")),this._emitMatch(e,t),i()};ee.prototype._stat=function(t,e){var r=this._makeAbs(t),n=t.slice(-1)==="/";if(t.length>this.maxLength)return e();if(!this.stat&&Tc(this.cache,r)){var i=this.cache[r];if(Array.isArray(i)&&(i="DIR"),!n||i==="DIR")return e(null,i);if(n&&i==="FILE")return e()}var s,a=this.statCache[r];if(a!==void 0){if(a===!1)return e(null,a);var l=a.isDirectory()?"DIR":"FILE";return n&&l==="FILE"?e():e(null,l,a)}var c=this,u=Oc("stat\0"+r,h);u&&c.fs.lstat(r,u);function h(f,d){if(d&&d.isSymbolicLink())return c.fs.stat(r,function(p,m){p?c._stat2(t,r,null,d,e):c._stat2(t,r,p,m,e)});c._stat2(t,r,f,d,e)}};ee.prototype._stat2=function(t,e,r,n,i){if(r&&(r.code==="ENOENT"||r.code==="ENOTDIR"))return this.statCache[e]=!1,i();var s=t.slice(-1)==="/";if(this.statCache[e]=n,e.slice(-1)==="/"&&n&&!n.isDirectory())return i(null,!1,n);var a=!0;return n&&(a=n.isDirectory()?"DIR":"FILE"),this.cache[e]=this.cache[e]||a,s&&a==="FILE"?i():i(null,a,n)}});var pg=$((iP,hg)=>{hg.exports=Mc;Mc.sync=fg;var Q=require("assert"),cg=require("path"),og=require("fs"),uo=Ec(),ug=parseInt("666",8),NE={nosort:!0,silent:!0},Ic=0,Ci=process.platform==="win32";function dg(t){var e=["unlink","chmod","stat","lstat","rmdir","readdir"];e.forEach(function(r){t[r]=t[r]||og[r],r=r+"Sync",t[r]=t[r]||og[r]}),t.maxBusyTries=t.maxBusyTries||3,t.emfileWait=t.emfileWait||1e3,t.glob===!1&&(t.disableGlob=!0),t.disableGlob=t.disableGlob||!1,t.glob=t.glob||NE}function Mc(t,e,r){typeof e=="function"&&(r=e,e={}),Q(t,"rimraf: missing path"),Q.equal(typeof t,"string","rimraf: path should be a string"),Q.equal(typeof r,"function","rimraf: callback function required"),Q(e,"rimraf: invalid options argument provided"),Q.equal(typeof e,"object","rimraf: options should be object"),dg(e);var n=0,i=null,s=0;if(e.disableGlob||!uo.hasMagic(t))return l(null,[t]);e.lstat(t,function(c,u){if(!c)return l(null,[t]);uo(t,e.glob,l)});function a(c){i=i||c,--s===0&&r(i)}function l(c,u){if(c)return r(c);if(s=u.length,s===0)return r();u.forEach(function(h){Rc(h,e,function f(d){if(d){if((d.code==="EBUSY"||d.code==="ENOTEMPTY"||d.code==="EPERM")&&n<e.maxBusyTries){n++;var p=n*100;return setTimeout(function(){Rc(h,e,f)},p)}if(d.code==="EMFILE"&&Ic<e.emfileWait)return setTimeout(function(){Rc(h,e,f)},Ic++);d.code==="ENOENT"&&(d=null)}Ic=0,a(d)})})}}function Rc(t,e,r){Q(t),Q(e),Q(typeof r=="function"),e.lstat(t,function(n,i){if(n&&n.code==="ENOENT")return r(null);if(n&&n.code==="EPERM"&&Ci&&ag(t,e,n,r),i&&i.isDirectory())return lo(t,e,n,r);e.unlink(t,function(s){if(s){if(s.code==="ENOENT")return r(null);if(s.code==="EPERM")return Ci?ag(t,e,s,r):lo(t,e,s,r);if(s.code==="EISDIR")return lo(t,e,s,r)}return r(s)})})}function ag(t,e,r,n){Q(t),Q(e),Q(typeof n=="function"),r&&Q(r instanceof Error),e.chmod(t,ug,function(i){i?n(i.code==="ENOENT"?null:r):e.stat(t,function(s,a){s?n(s.code==="ENOENT"?null:r):a.isDirectory()?lo(t,e,r,n):e.unlink(t,n)})})}function lg(t,e,r){Q(t),Q(e),r&&Q(r instanceof Error);try{e.chmodSync(t,ug)}catch(i){if(i.code==="ENOENT")return;throw r}try{var n=e.statSync(t)}catch(i){if(i.code==="ENOENT")return;throw r}n.isDirectory()?co(t,e,r):e.unlinkSync(t)}function lo(t,e,r,n){Q(t),Q(e),r&&Q(r instanceof Error),Q(typeof n=="function"),e.rmdir(t,function(i){i&&(i.code==="ENOTEMPTY"||i.code==="EEXIST"||i.code==="EPERM")?$E(t,e,n):i&&i.code==="ENOTDIR"?n(r):n(i)})}function $E(t,e,r){Q(t),Q(e),Q(typeof r=="function"),e.readdir(t,function(n,i){if(n)return r(n);var s=i.length;if(s===0)return e.rmdir(t,r);var a;i.forEach(function(l){Mc(cg.join(t,l),e,function(c){if(!a){if(c)return r(a=c);--s===0&&e.rmdir(t,r)}})})})}function fg(t,e){e=e||{},dg(e),Q(t,"rimraf: missing path"),Q.equal(typeof t,"string","rimraf: path should be a string"),Q(e,"rimraf: missing options"),Q.equal(typeof e,"object","rimraf: options should be object");var r;if(e.disableGlob||!uo.hasMagic(t))r=[t];else try{e.lstatSync(t),r=[t]}catch{r=uo.sync(t,e.glob)}if(r.length)for(var n=0;n<r.length;n++){var t=r[n];try{var i=e.lstatSync(t)}catch(a){if(a.code==="ENOENT")return;a.code==="EPERM"&&Ci&&lg(t,e,a)}try{i&&i.isDirectory()?co(t,e,null):e.unlinkSync(t)}catch(a){if(a.code==="ENOENT")return;if(a.code==="EPERM")return Ci?lg(t,e,a):co(t,e,a);if(a.code!=="EISDIR")throw a;co(t,e,a)}}}function co(t,e,r){Q(t),Q(e),r&&Q(r instanceof Error);try{e.rmdirSync(t)}catch(n){if(n.code==="ENOENT")return;if(n.code==="ENOTDIR")throw r;(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM")&&UE(t,e)}}function UE(t,e){Q(t),Q(e),e.readdirSync(t).forEach(function(a){fg(cg.join(t,a),e)});var r=Ci?100:1,n=0;do{var i=!0;try{var s=e.rmdirSync(t,e);return i=!1,s}finally{if(++n<r&&i)continue}}while(!0)}});var bg=$((sP,yg)=>{var Ei=require("path"),mg=require("fs"),gg=parseInt("0777",8);yg.exports=xn.mkdirp=xn.mkdirP=xn;function xn(t,e,r,n){typeof e=="function"?(r=e,e={}):(!e||typeof e!="object")&&(e={mode:e});var i=e.mode,s=e.fs||mg;i===void 0&&(i=gg),n||(n=null);var a=r||function(){};t=Ei.resolve(t),s.mkdir(t,i,function(l){if(!l)return n=n||t,a(null,n);switch(l.code){case"ENOENT":if(Ei.dirname(t)===t)return a(l);xn(Ei.dirname(t),e,function(c,u){c?a(c,u):xn(t,e,a,u)});break;default:s.stat(t,function(c,u){c||!u.isDirectory()?a(l,n):a(null,n)});break}})}xn.sync=function t(e,r,n){(!r||typeof r!="object")&&(r={mode:r});var i=r.mode,s=r.fs||mg;i===void 0&&(i=gg),n||(n=null),e=Ei.resolve(e);try{s.mkdirSync(e,i),n=n||e}catch(l){switch(l.code){case"ENOENT":n=t(Ei.dirname(e),r,n),t(e,r,n);break;default:var a;try{a=s.statSync(e)}catch{throw l}if(!a.isDirectory())throw l;break}}return n}});var $c=$((Ze,kg)=>{var jc=require("fs"),Dg=require("path"),fo=require("constants"),qE=require("os"),Bc=pg(),wg=bg(),oP=require("os").tmpdir(),Sg=Bc.sync,Cg=Dg.resolve(qE.tmpdir()),Lc=fo.O_CREAT|fo.O_TRUNC|fo.O_RDWR|fo.O_EXCL,_i=function(t){if(typeof t=="function")return[void 0,t];var e,r=new Promise(function(n,i){e=function(){var s=Array.from(arguments),a=s.shift();process.nextTick(function(){a?i(a):s.length===1?n(s[0]):n(s)})}});return[r,e]},kn=function(t,e){var r=zE(t,e),n=new Date,i=[r.prefix,n.getFullYear(),n.getMonth(),n.getDate(),"-",process.pid,"-",(Math.random()*4294967296+1).toString(36),r.suffix].join("");return Dg.join(r.dir||Cg,i)},zE=function(t,e){var r={prefix:null,suffix:null};if(t)switch(typeof t){case"string":r.prefix=t;break;case"object":r=t;break;default:throw new Error("Unknown affix declaration: "+r)}else r.prefix=e;return r},at=!1,VE=function(t){return at=t!==!1,kg.exports},vg=!1,ho=[],po=[];function Nc(t){if(!at)return!1;_g(),ho.push(t)}function Eg(t){if(!at)return!1;_g(),po.push(t)}function _g(){if(!at)return!1;vg||(process.addListener("exit",function(){try{xg()}catch(t){throw console.warn("Fail to clean temporary files on exit : ",t),t}}),vg=!0)}function WE(){if(!at)return!1;for(var t=0,e;(e=ho.shift())!==void 0;)Sg(e,{maxBusyTries:6}),t++;return t}function GE(t){var e=_i(t),r=e[0];if(t=e[1],!at)return t(new Error("not tracking")),r;var n=0,i=ho.length;if(!i)return t(null,n),r;for(var s,a=function(l){if(i){if(l){t(l),i=0;return}else n++;i--,i||t(null,n)}};(s=ho.shift())!==void 0;)Bc(s,{maxBusyTries:6},a);return r}function ZE(){if(!at)return!1;for(var t=0,e;(e=po.shift())!==void 0;)Sg(e,{maxBusyTries:6}),t++;return t}function KE(t){var e=_i(t),r=e[0];if(t=e[1],!at)return t(new Error("not tracking")),r;var n=0,i=po.length;if(!i)return t(null,n),r;for(var s,a=function(l){if(i){if(l){t(l,n),i=0;return}else n++;i--,i||t(null,n)}};(s=po.shift())!==void 0;)Bc(s,{maxBusyTries:6},a);return r}function xg(){if(!at)return!1;var t=WE(),e=ZE();return{files:t,dirs:e}}function HE(t){var e=_i(t),r=e[0];return t=e[1],at?(GE(function(n,i){n?t(n,{files:i}):KE(function(s,a){t(s,{files:i,dirs:a})})}),r):(t(new Error("not tracking")),r)}var YE=(t,e)=>{let r=_i(e),n=r[0];e=r[1];let i=kn(t,"d-");return wg(i,448,s=>{s||Eg(i),e(s,i)}),n},JE=t=>{let e=kn(t,"d-");return wg.sync(e,448),Eg(e),e},QE=(t,e)=>{let r=_i(e),n=r[0];e=r[1];let i=kn(t,"f-");return jc.open(i,Lc,384,(s,a)=>{s||Nc(i),e(s,{path:i,fd:a})}),n},XE=t=>{let e=kn(t,"f-"),r=jc.openSync(e,Lc,384);return Nc(e),{path:e,fd:r}},e_=t=>{let e=kn(t,"s-"),r=jc.createWriteStream(e,{flags:Lc,mode:384});return Nc(e),r};Ze.dir=Cg;Ze.track=VE;Ze.mkdir=YE;Ze.mkdirSync=JE;Ze.open=QE;Ze.openSync=XE;Ze.path=kn;Ze.cleanup=HE;Ze.cleanupSync=xg;Ze.createWriteStream=e_});var Ig=$((aP,Og)=>{var Fg=require("child_process").exec,Pg=$c(),t_=require("fs"),r_=eo(),n_=require("path"),{unlinkP:i_,readAndUnlinkP:s_}=r_;function xi(t={}){let e=r=>new Promise((n,i)=>{let s=r.length;if(s===0)return i(new Error("No displays detected try dropping screen option"));let a=s-1,l=t.screen||0;if(!Number.isInteger(l)||l<0||l>a){let g=a===0?"(valid choice is 0 or drop screen option altogether)":`(valid choice is an integer between 0 and ${a})`;return i(new Error(`Invalid choice of displayId: ${l} ${g}`))}let c=["jpg","jpeg","png","tiff","bmp","gif","pdf"],u=(t.format||"jpg").toLowerCase();if(!c.includes(u))return i(new Error("Invalid format"));let h,f;if(t.filename){let g=t.filename.replace(/[^a-zA-Z0-9._\-/]/g,""),y=g.lastIndexOf(".");f=y>=0?g.slice(y):`.${u}`,h=g}else f=`.${u}`;let d=Array(l+1).fill(null).map(()=>Pg.path({suffix:f})),p=[];t.filename&&(d[l]=h),p=d.slice(0,l+1);let m=["-x","-t",u,...p];require("child_process").execFile("screencapture",m,function(g,y){if(g)return i(g);t.filename?n(n_.resolve(h)):t_.readFile(d[l],function(b,D){if(b)return i(b);Promise.all(p.map(i_)).then(()=>n(D)).catch(v=>i(v))})})});return Uc().then(r=>e(r))}var o_=`
98
+ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof ce))return new ce(t,e);if(SE(this,t,e),this.noprocess)return this;var r=this.minimatch.set.length;this.matches=new Array(r);for(var n=0;n<r;n++)this._process(this.minimatch.set[n],n,!1);this._finish()}ce.prototype._finish=function(){if(Hm.ok(this instanceof ce),this.realpath){var t=this;this.matches.forEach(function(e,r){var n=t.matches[r]=Object.create(null);for(var i in e)try{i=t._makeAbs(i);var s=wE.realpathSync(i,t.realpathCache);n[s]=!0}catch(a){if(a.syscall==="stat")n[t._makeAbs(i)]=!0;else throw a}})}Br.finish(this)};ce.prototype._process=function(t,e,r){Hm.ok(this instanceof ce);for(var n=0;typeof t[n]=="string";)n++;var i;switch(n){case t.length:this._processSimple(t.join("/"),e);return;case 0:i=null;break;default:i=t.slice(0,n).join("/");break}var s=t.slice(n),a;i===null?a=".":((oo(i)||oo(t.map(function(u){return typeof u=="string"?u:"[*]"}).join("/")))&&(!i||!oo(i))&&(i="/"+i),a=i);var l=this._makeAbs(a);if(!CE(this,a)){var c=s[0]===Km.GLOBSTAR;c?this._processGlobStar(i,a,l,s,e,r):this._processReaddir(i,a,l,s,e,r)}};ce.prototype._processReaddir=function(t,e,r,n,i,s){var a=this._readdir(r,s);if(a){for(var l=n[0],c=!!this.minimatch.negate,u=l._glob,h=this.dot||u.charAt(0)===".",f=[],d=0;d<a.length;d++){var p=a[d];if(p.charAt(0)!=="."||h){var m;c&&!t?m=!p.match(l):m=p.match(l),m&&f.push(p)}}var g=f.length;if(g!==0){if(n.length===1&&!this.mark&&!this.stat){this.matches[i]||(this.matches[i]=Object.create(null));for(var d=0;d<g;d++){var p=f[d];t&&(t.slice(-1)!=="/"?p=t+"/"+p:p=t+p),p.charAt(0)==="/"&&!this.nomount&&(p=Cc.join(this.root,p)),this._emitMatch(i,p)}return}n.shift();for(var d=0;d<g;d++){var p=f[d],y;t?y=[t,p]:y=[p],this._process(y.concat(n),i,s)}}}};ce.prototype._emitMatch=function(t,e){if(!EE(this,e)){var r=this._makeAbs(e);if(this.mark&&(e=this._mark(e)),this.absolute&&(e=r),!this.matches[t][e]){if(this.nodir){var n=this.cache[r];if(n==="DIR"||Array.isArray(n))return}this.matches[t][e]=!0,this.stat&&this._stat(e)}}};ce.prototype._readdirInGlobStar=function(t){if(this.follow)return this._readdir(t,!1);var e,r,n;try{r=this.fs.lstatSync(t)}catch(s){if(s.code==="ENOENT")return null}var i=r&&r.isSymbolicLink();return this.symlinks[t]=i,!i&&r&&!r.isDirectory()?this.cache[t]="FILE":e=this._readdir(t,!1),e};ce.prototype._readdir=function(t,e){var r;if(e&&!Ec(this.symlinks,t))return this._readdirInGlobStar(t);if(Ec(this.cache,t)){var n=this.cache[t];if(!n||n==="FILE")return null;if(Array.isArray(n))return n}try{return this._readdirEntries(t,this.fs.readdirSync(t))}catch(i){return this._readdirError(t,i),null}};ce.prototype._readdirEntries=function(t,e){if(!this.mark&&!this.stat)for(var r=0;r<e.length;r++){var n=e[r];t==="/"?n=t+n:n=t+"/"+n,this.cache[n]=!0}return this.cache[t]=e,e};ce.prototype._readdirError=function(t,e){switch(e.code){case"ENOTSUP":case"ENOTDIR":var r=this._makeAbs(t);if(this.cache[r]="FILE",r===this.cwdAbs){var n=new Error(e.code+" invalid cwd "+this.cwd);throw n.path=this.cwd,n.code=e.code,n}break;case"ENOENT":case"ELOOP":case"ENAMETOOLONG":case"UNKNOWN":this.cache[this._makeAbs(t)]=!1;break;default:if(this.cache[this._makeAbs(t)]=!1,this.strict)throw e;this.silent||console.error("glob error",e);break}};ce.prototype._processGlobStar=function(t,e,r,n,i,s){var a=this._readdir(r,s);if(a){var l=n.slice(1),c=t?[t]:[],u=c.concat(l);this._process(u,i,!1);var h=a.length,f=this.symlinks[r];if(!(f&&s))for(var d=0;d<h;d++){var p=a[d];if(!(p.charAt(0)==="."&&!this.dot)){var m=c.concat(a[d],l);this._process(m,i,!0);var g=c.concat(a[d],n);this._process(g,i,!0)}}}};ce.prototype._processSimple=function(t,e){var r=this._stat(t);if(this.matches[e]||(this.matches[e]=Object.create(null)),!!r){if(t&&oo(t)&&!this.nomount){var n=/[\/\\]$/.test(t);t.charAt(0)==="/"?t=Cc.join(this.root,t):(t=Cc.resolve(this.root,t),n&&(t+="/"))}process.platform==="win32"&&(t=t.replace(/\\/g,"/")),this._emitMatch(e,t)}};ce.prototype._stat=function(t){var e=this._makeAbs(t),r=t.slice(-1)==="/";if(t.length>this.maxLength)return!1;if(!this.stat&&Ec(this.cache,e)){var a=this.cache[e];if(Array.isArray(a)&&(a="DIR"),!r||a==="DIR")return a;if(r&&a==="FILE")return!1}var n,i=this.statCache[e];if(!i){var s;try{s=this.fs.lstatSync(e)}catch(l){if(l&&(l.code==="ENOENT"||l.code==="ENOTDIR"))return this.statCache[e]=!1,!1}if(s&&s.isSymbolicLink())try{i=this.fs.statSync(e)}catch{i=s}else i=s}this.statCache[e]=i;var a=!0;return i&&(a=i.isDirectory()?"DIR":"FILE"),this.cache[e]=this.cache[e]||a,r&&a==="FILE"?!1:a};ce.prototype._mark=function(t){return Br.mark(this,t)};ce.prototype._makeAbs=function(t){return Br.makeAbs(this,t)}});var xc=$((XF,eg)=>{eg.exports=Xm;function Xm(t,e){if(t&&e)return Xm(t)(e);if(typeof t!="function")throw new TypeError("need wrapper function");return Object.keys(t).forEach(function(n){r[n]=t[n]}),r;function r(){for(var n=new Array(arguments.length),i=0;i<n.length;i++)n[i]=arguments[i];var s=t.apply(this,n),a=n[n.length-1];return typeof s=="function"&&s!==a&&Object.keys(a).forEach(function(l){s[l]=a[l]}),s}}});var Fc=$((eP,kc)=>{var tg=xc();kc.exports=tg(ao);kc.exports.strict=tg(rg);ao.proto=ao(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return ao(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return rg(this)},configurable:!0})});function ao(t){var e=function(){return e.called?e.value:(e.called=!0,e.value=t.apply(this,arguments))};return e.called=!1,e}function rg(t){var e=function(){if(e.called)throw new Error(e.onceError);return e.called=!0,e.value=t.apply(this,arguments)},r=t.name||"Function wrapped with `once`";return e.onceError=r+" shouldn't be called more than once",e.called=!1,e}});var ig=$((tP,ng)=>{var _E=xc(),wi=Object.create(null),xE=Fc();ng.exports=_E(kE);function kE(t,e){return wi[t]?(wi[t].push(e),null):(wi[t]=[e],FE(t))}function FE(t){return xE(function e(){var r=wi[t],n=r.length,i=PE(arguments);try{for(var s=0;s<n;s++)r[s].apply(null,i)}finally{r.length>n?(r.splice(0,n),process.nextTick(function(){e.apply(null,i)})):delete wi[t]}})}function PE(t){for(var e=t.length,r=[],n=0;n<e;n++)r[n]=t[n];return r}});var _c=$((iP,og)=>{og.exports=Lr;var TE=hc(),sg=no(),rP=sg.Minimatch,AE=qm(),OE=require("events").EventEmitter,Pc=require("path"),Tc=require("assert"),Si=so(),Oc=Qm(),Nr=Sc(),IE=Nr.setopts,Ac=Nr.ownProp,Ic=ig(),nP=require("util"),RE=Nr.childrenIgnored,ME=Nr.isIgnored,jE=Fc();function Lr(t,e,r){if(typeof e=="function"&&(r=e,e={}),e||(e={}),e.sync){if(r)throw new TypeError("callback provided to sync glob");return Oc(t,e)}return new ee(t,e,r)}Lr.sync=Oc;var BE=Lr.GlobSync=Oc.GlobSync;Lr.glob=Lr;function LE(t,e){if(e===null||typeof e!="object")return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}Lr.hasMagic=function(t,e){var r=LE({},e);r.noprocess=!0;var n=new ee(t,r),i=n.minimatch.set;if(!t)return!1;if(i.length>1)return!0;for(var s=0;s<i[0].length;s++)if(typeof i[0][s]!="string")return!0;return!1};Lr.Glob=ee;AE(ee,OE);function ee(t,e,r){if(typeof e=="function"&&(r=e,e=null),e&&e.sync){if(r)throw new TypeError("callback provided to sync glob");return new BE(t,e)}if(!(this instanceof ee))return new ee(t,e,r);IE(this,t,e),this._didRealPath=!1;var n=this.minimatch.set.length;this.matches=new Array(n),typeof r=="function"&&(r=jE(r),this.on("error",r),this.on("end",function(c){r(null,c)}));var i=this;if(this._processing=0,this._emitQueue=[],this._processQueue=[],this.paused=!1,this.noprocess)return this;if(n===0)return l();for(var s=!0,a=0;a<n;a++)this._process(this.minimatch.set[a],a,!1,l);s=!1;function l(){--i._processing,i._processing<=0&&(s?process.nextTick(function(){i._finish()}):i._finish())}}ee.prototype._finish=function(){if(Tc(this instanceof ee),!this.aborted){if(this.realpath&&!this._didRealpath)return this._realpath();Nr.finish(this),this.emit("end",this.found)}};ee.prototype._realpath=function(){if(this._didRealpath)return;this._didRealpath=!0;var t=this.matches.length;if(t===0)return this._finish();for(var e=this,r=0;r<this.matches.length;r++)this._realpathSet(r,n);function n(){--t===0&&e._finish()}};ee.prototype._realpathSet=function(t,e){var r=this.matches[t];if(!r)return e();var n=Object.keys(r),i=this,s=n.length;if(s===0)return e();var a=this.matches[t]=Object.create(null);n.forEach(function(l,c){l=i._makeAbs(l),TE.realpath(l,i.realpathCache,function(u,h){u?u.syscall==="stat"?a[l]=!0:i.emit("error",u):a[h]=!0,--s===0&&(i.matches[t]=a,e())})})};ee.prototype._mark=function(t){return Nr.mark(this,t)};ee.prototype._makeAbs=function(t){return Nr.makeAbs(this,t)};ee.prototype.abort=function(){this.aborted=!0,this.emit("abort")};ee.prototype.pause=function(){this.paused||(this.paused=!0,this.emit("pause"))};ee.prototype.resume=function(){if(this.paused){if(this.emit("resume"),this.paused=!1,this._emitQueue.length){var t=this._emitQueue.slice(0);this._emitQueue.length=0;for(var e=0;e<t.length;e++){var r=t[e];this._emitMatch(r[0],r[1])}}if(this._processQueue.length){var n=this._processQueue.slice(0);this._processQueue.length=0;for(var e=0;e<n.length;e++){var i=n[e];this._processing--,this._process(i[0],i[1],i[2],i[3])}}}};ee.prototype._process=function(t,e,r,n){if(Tc(this instanceof ee),Tc(typeof n=="function"),!this.aborted){if(this._processing++,this.paused){this._processQueue.push([t,e,r,n]);return}for(var i=0;typeof t[i]=="string";)i++;var s;switch(i){case t.length:this._processSimple(t.join("/"),e,n);return;case 0:s=null;break;default:s=t.slice(0,i).join("/");break}var a=t.slice(i),l;s===null?l=".":((Si(s)||Si(t.map(function(h){return typeof h=="string"?h:"[*]"}).join("/")))&&(!s||!Si(s))&&(s="/"+s),l=s);var c=this._makeAbs(l);if(RE(this,l))return n();var u=a[0]===sg.GLOBSTAR;u?this._processGlobStar(s,l,c,a,e,r,n):this._processReaddir(s,l,c,a,e,r,n)}};ee.prototype._processReaddir=function(t,e,r,n,i,s,a){var l=this;this._readdir(r,s,function(c,u){return l._processReaddir2(t,e,r,n,i,s,u,a)})};ee.prototype._processReaddir2=function(t,e,r,n,i,s,a,l){if(!a)return l();for(var c=n[0],u=!!this.minimatch.negate,h=c._glob,f=this.dot||h.charAt(0)===".",d=[],p=0;p<a.length;p++){var m=a[p];if(m.charAt(0)!=="."||f){var g;u&&!t?g=!m.match(c):g=m.match(c),g&&d.push(m)}}var y=d.length;if(y===0)return l();if(n.length===1&&!this.mark&&!this.stat){this.matches[i]||(this.matches[i]=Object.create(null));for(var p=0;p<y;p++){var m=d[p];t&&(t!=="/"?m=t+"/"+m:m=t+m),m.charAt(0)==="/"&&!this.nomount&&(m=Pc.join(this.root,m)),this._emitMatch(i,m)}return l()}n.shift();for(var p=0;p<y;p++){var m=d[p],b;t&&(t!=="/"?m=t+"/"+m:m=t+m),this._process([m].concat(n),i,s,l)}l()};ee.prototype._emitMatch=function(t,e){if(!this.aborted&&!ME(this,e)){if(this.paused){this._emitQueue.push([t,e]);return}var r=Si(e)?e:this._makeAbs(e);if(this.mark&&(e=this._mark(e)),this.absolute&&(e=r),!this.matches[t][e]){if(this.nodir){var n=this.cache[r];if(n==="DIR"||Array.isArray(n))return}this.matches[t][e]=!0;var i=this.statCache[r];i&&this.emit("stat",e,i),this.emit("match",e)}}};ee.prototype._readdirInGlobStar=function(t,e){if(this.aborted)return;if(this.follow)return this._readdir(t,!1,e);var r="lstat\0"+t,n=this,i=Ic(r,s);i&&n.fs.lstat(t,i);function s(a,l){if(a&&a.code==="ENOENT")return e();var c=l&&l.isSymbolicLink();n.symlinks[t]=c,!c&&l&&!l.isDirectory()?(n.cache[t]="FILE",e()):n._readdir(t,!1,e)}};ee.prototype._readdir=function(t,e,r){if(!this.aborted&&(r=Ic("readdir\0"+t+"\0"+e,r),!!r)){if(e&&!Ac(this.symlinks,t))return this._readdirInGlobStar(t,r);if(Ac(this.cache,t)){var n=this.cache[t];if(!n||n==="FILE")return r();if(Array.isArray(n))return r(null,n)}var i=this;i.fs.readdir(t,NE(this,t,r))}};function NE(t,e,r){return function(n,i){n?t._readdirError(e,n,r):t._readdirEntries(e,i,r)}}ee.prototype._readdirEntries=function(t,e,r){if(!this.aborted){if(!this.mark&&!this.stat)for(var n=0;n<e.length;n++){var i=e[n];t==="/"?i=t+i:i=t+"/"+i,this.cache[i]=!0}return this.cache[t]=e,r(null,e)}};ee.prototype._readdirError=function(t,e,r){if(!this.aborted){switch(e.code){case"ENOTSUP":case"ENOTDIR":var n=this._makeAbs(t);if(this.cache[n]="FILE",n===this.cwdAbs){var i=new Error(e.code+" invalid cwd "+this.cwd);i.path=this.cwd,i.code=e.code,this.emit("error",i),this.abort()}break;case"ENOENT":case"ELOOP":case"ENAMETOOLONG":case"UNKNOWN":this.cache[this._makeAbs(t)]=!1;break;default:this.cache[this._makeAbs(t)]=!1,this.strict&&(this.emit("error",e),this.abort()),this.silent||console.error("glob error",e);break}return r()}};ee.prototype._processGlobStar=function(t,e,r,n,i,s,a){var l=this;this._readdir(r,s,function(c,u){l._processGlobStar2(t,e,r,n,i,s,u,a)})};ee.prototype._processGlobStar2=function(t,e,r,n,i,s,a,l){if(!a)return l();var c=n.slice(1),u=t?[t]:[],h=u.concat(c);this._process(h,i,!1,l);var f=this.symlinks[r],d=a.length;if(f&&s)return l();for(var p=0;p<d;p++){var m=a[p];if(!(m.charAt(0)==="."&&!this.dot)){var g=u.concat(a[p],c);this._process(g,i,!0,l);var y=u.concat(a[p],n);this._process(y,i,!0,l)}}l()};ee.prototype._processSimple=function(t,e,r){var n=this;this._stat(t,function(i,s){n._processSimple2(t,e,i,s,r)})};ee.prototype._processSimple2=function(t,e,r,n,i){if(this.matches[e]||(this.matches[e]=Object.create(null)),!n)return i();if(t&&Si(t)&&!this.nomount){var s=/[\/\\]$/.test(t);t.charAt(0)==="/"?t=Pc.join(this.root,t):(t=Pc.resolve(this.root,t),s&&(t+="/"))}process.platform==="win32"&&(t=t.replace(/\\/g,"/")),this._emitMatch(e,t),i()};ee.prototype._stat=function(t,e){var r=this._makeAbs(t),n=t.slice(-1)==="/";if(t.length>this.maxLength)return e();if(!this.stat&&Ac(this.cache,r)){var i=this.cache[r];if(Array.isArray(i)&&(i="DIR"),!n||i==="DIR")return e(null,i);if(n&&i==="FILE")return e()}var s,a=this.statCache[r];if(a!==void 0){if(a===!1)return e(null,a);var l=a.isDirectory()?"DIR":"FILE";return n&&l==="FILE"?e():e(null,l,a)}var c=this,u=Ic("stat\0"+r,h);u&&c.fs.lstat(r,u);function h(f,d){if(d&&d.isSymbolicLink())return c.fs.stat(r,function(p,m){p?c._stat2(t,r,null,d,e):c._stat2(t,r,p,m,e)});c._stat2(t,r,f,d,e)}};ee.prototype._stat2=function(t,e,r,n,i){if(r&&(r.code==="ENOENT"||r.code==="ENOTDIR"))return this.statCache[e]=!1,i();var s=t.slice(-1)==="/";if(this.statCache[e]=n,e.slice(-1)==="/"&&n&&!n.isDirectory())return i(null,!1,n);var a=!0;return n&&(a=n.isDirectory()?"DIR":"FILE"),this.cache[e]=this.cache[e]||a,s&&a==="FILE"?i():i(null,a,n)}});var mg=$((sP,pg)=>{pg.exports=jc;jc.sync=hg;var Q=require("assert"),ug=require("path"),ag=require("fs"),uo=_c(),dg=parseInt("666",8),$E={nosort:!0,silent:!0},Rc=0,Ci=process.platform==="win32";function fg(t){var e=["unlink","chmod","stat","lstat","rmdir","readdir"];e.forEach(function(r){t[r]=t[r]||ag[r],r=r+"Sync",t[r]=t[r]||ag[r]}),t.maxBusyTries=t.maxBusyTries||3,t.emfileWait=t.emfileWait||1e3,t.glob===!1&&(t.disableGlob=!0),t.disableGlob=t.disableGlob||!1,t.glob=t.glob||$E}function jc(t,e,r){typeof e=="function"&&(r=e,e={}),Q(t,"rimraf: missing path"),Q.equal(typeof t,"string","rimraf: path should be a string"),Q.equal(typeof r,"function","rimraf: callback function required"),Q(e,"rimraf: invalid options argument provided"),Q.equal(typeof e,"object","rimraf: options should be object"),fg(e);var n=0,i=null,s=0;if(e.disableGlob||!uo.hasMagic(t))return l(null,[t]);e.lstat(t,function(c,u){if(!c)return l(null,[t]);uo(t,e.glob,l)});function a(c){i=i||c,--s===0&&r(i)}function l(c,u){if(c)return r(c);if(s=u.length,s===0)return r();u.forEach(function(h){Mc(h,e,function f(d){if(d){if((d.code==="EBUSY"||d.code==="ENOTEMPTY"||d.code==="EPERM")&&n<e.maxBusyTries){n++;var p=n*100;return setTimeout(function(){Mc(h,e,f)},p)}if(d.code==="EMFILE"&&Rc<e.emfileWait)return setTimeout(function(){Mc(h,e,f)},Rc++);d.code==="ENOENT"&&(d=null)}Rc=0,a(d)})})}}function Mc(t,e,r){Q(t),Q(e),Q(typeof r=="function"),e.lstat(t,function(n,i){if(n&&n.code==="ENOENT")return r(null);if(n&&n.code==="EPERM"&&Ci&&lg(t,e,n,r),i&&i.isDirectory())return lo(t,e,n,r);e.unlink(t,function(s){if(s){if(s.code==="ENOENT")return r(null);if(s.code==="EPERM")return Ci?lg(t,e,s,r):lo(t,e,s,r);if(s.code==="EISDIR")return lo(t,e,s,r)}return r(s)})})}function lg(t,e,r,n){Q(t),Q(e),Q(typeof n=="function"),r&&Q(r instanceof Error),e.chmod(t,dg,function(i){i?n(i.code==="ENOENT"?null:r):e.stat(t,function(s,a){s?n(s.code==="ENOENT"?null:r):a.isDirectory()?lo(t,e,r,n):e.unlink(t,n)})})}function cg(t,e,r){Q(t),Q(e),r&&Q(r instanceof Error);try{e.chmodSync(t,dg)}catch(i){if(i.code==="ENOENT")return;throw r}try{var n=e.statSync(t)}catch(i){if(i.code==="ENOENT")return;throw r}n.isDirectory()?co(t,e,r):e.unlinkSync(t)}function lo(t,e,r,n){Q(t),Q(e),r&&Q(r instanceof Error),Q(typeof n=="function"),e.rmdir(t,function(i){i&&(i.code==="ENOTEMPTY"||i.code==="EEXIST"||i.code==="EPERM")?UE(t,e,n):i&&i.code==="ENOTDIR"?n(r):n(i)})}function UE(t,e,r){Q(t),Q(e),Q(typeof r=="function"),e.readdir(t,function(n,i){if(n)return r(n);var s=i.length;if(s===0)return e.rmdir(t,r);var a;i.forEach(function(l){jc(ug.join(t,l),e,function(c){if(!a){if(c)return r(a=c);--s===0&&e.rmdir(t,r)}})})})}function hg(t,e){e=e||{},fg(e),Q(t,"rimraf: missing path"),Q.equal(typeof t,"string","rimraf: path should be a string"),Q(e,"rimraf: missing options"),Q.equal(typeof e,"object","rimraf: options should be object");var r;if(e.disableGlob||!uo.hasMagic(t))r=[t];else try{e.lstatSync(t),r=[t]}catch{r=uo.sync(t,e.glob)}if(r.length)for(var n=0;n<r.length;n++){var t=r[n];try{var i=e.lstatSync(t)}catch(a){if(a.code==="ENOENT")return;a.code==="EPERM"&&Ci&&cg(t,e,a)}try{i&&i.isDirectory()?co(t,e,null):e.unlinkSync(t)}catch(a){if(a.code==="ENOENT")return;if(a.code==="EPERM")return Ci?cg(t,e,a):co(t,e,a);if(a.code!=="EISDIR")throw a;co(t,e,a)}}}function co(t,e,r){Q(t),Q(e),r&&Q(r instanceof Error);try{e.rmdirSync(t)}catch(n){if(n.code==="ENOENT")return;if(n.code==="ENOTDIR")throw r;(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM")&&qE(t,e)}}function qE(t,e){Q(t),Q(e),e.readdirSync(t).forEach(function(a){hg(ug.join(t,a),e)});var r=Ci?100:1,n=0;do{var i=!0;try{var s=e.rmdirSync(t,e);return i=!1,s}finally{if(++n<r&&i)continue}}while(!0)}});var vg=$((oP,bg)=>{var Ei=require("path"),gg=require("fs"),yg=parseInt("0777",8);bg.exports=xn.mkdirp=xn.mkdirP=xn;function xn(t,e,r,n){typeof e=="function"?(r=e,e={}):(!e||typeof e!="object")&&(e={mode:e});var i=e.mode,s=e.fs||gg;i===void 0&&(i=yg),n||(n=null);var a=r||function(){};t=Ei.resolve(t),s.mkdir(t,i,function(l){if(!l)return n=n||t,a(null,n);switch(l.code){case"ENOENT":if(Ei.dirname(t)===t)return a(l);xn(Ei.dirname(t),e,function(c,u){c?a(c,u):xn(t,e,a,u)});break;default:s.stat(t,function(c,u){c||!u.isDirectory()?a(l,n):a(null,n)});break}})}xn.sync=function t(e,r,n){(!r||typeof r!="object")&&(r={mode:r});var i=r.mode,s=r.fs||gg;i===void 0&&(i=yg),n||(n=null),e=Ei.resolve(e);try{s.mkdirSync(e,i),n=n||e}catch(l){switch(l.code){case"ENOENT":n=t(Ei.dirname(e),r,n),t(e,r,n);break;default:var a;try{a=s.statSync(e)}catch{throw l}if(!a.isDirectory())throw l;break}}return n}});var Uc=$((Ke,Fg)=>{var Bc=require("fs"),wg=require("path"),fo=require("constants"),zE=require("os"),Lc=mg(),Sg=vg(),aP=require("os").tmpdir(),Cg=Lc.sync,Eg=wg.resolve(zE.tmpdir()),Nc=fo.O_CREAT|fo.O_TRUNC|fo.O_RDWR|fo.O_EXCL,_i=function(t){if(typeof t=="function")return[void 0,t];var e,r=new Promise(function(n,i){e=function(){var s=Array.from(arguments),a=s.shift();process.nextTick(function(){a?i(a):s.length===1?n(s[0]):n(s)})}});return[r,e]},kn=function(t,e){var r=VE(t,e),n=new Date,i=[r.prefix,n.getFullYear(),n.getMonth(),n.getDate(),"-",process.pid,"-",(Math.random()*4294967296+1).toString(36),r.suffix].join("");return wg.join(r.dir||Eg,i)},VE=function(t,e){var r={prefix:null,suffix:null};if(t)switch(typeof t){case"string":r.prefix=t;break;case"object":r=t;break;default:throw new Error("Unknown affix declaration: "+r)}else r.prefix=e;return r},ct=!1,WE=function(t){return ct=t!==!1,Fg.exports},Dg=!1,ho=[],po=[];function $c(t){if(!ct)return!1;xg(),ho.push(t)}function _g(t){if(!ct)return!1;xg(),po.push(t)}function xg(){if(!ct)return!1;Dg||(process.addListener("exit",function(){try{kg()}catch(t){throw console.warn("Fail to clean temporary files on exit : ",t),t}}),Dg=!0)}function GE(){if(!ct)return!1;for(var t=0,e;(e=ho.shift())!==void 0;)Cg(e,{maxBusyTries:6}),t++;return t}function ZE(t){var e=_i(t),r=e[0];if(t=e[1],!ct)return t(new Error("not tracking")),r;var n=0,i=ho.length;if(!i)return t(null,n),r;for(var s,a=function(l){if(i){if(l){t(l),i=0;return}else n++;i--,i||t(null,n)}};(s=ho.shift())!==void 0;)Lc(s,{maxBusyTries:6},a);return r}function KE(){if(!ct)return!1;for(var t=0,e;(e=po.shift())!==void 0;)Cg(e,{maxBusyTries:6}),t++;return t}function HE(t){var e=_i(t),r=e[0];if(t=e[1],!ct)return t(new Error("not tracking")),r;var n=0,i=po.length;if(!i)return t(null,n),r;for(var s,a=function(l){if(i){if(l){t(l,n),i=0;return}else n++;i--,i||t(null,n)}};(s=po.shift())!==void 0;)Lc(s,{maxBusyTries:6},a);return r}function kg(){if(!ct)return!1;var t=GE(),e=KE();return{files:t,dirs:e}}function YE(t){var e=_i(t),r=e[0];return t=e[1],ct?(ZE(function(n,i){n?t(n,{files:i}):HE(function(s,a){t(s,{files:i,dirs:a})})}),r):(t(new Error("not tracking")),r)}var JE=(t,e)=>{let r=_i(e),n=r[0];e=r[1];let i=kn(t,"d-");return Sg(i,448,s=>{s||_g(i),e(s,i)}),n},QE=t=>{let e=kn(t,"d-");return Sg.sync(e,448),_g(e),e},XE=(t,e)=>{let r=_i(e),n=r[0];e=r[1];let i=kn(t,"f-");return Bc.open(i,Nc,384,(s,a)=>{s||$c(i),e(s,{path:i,fd:a})}),n},e_=t=>{let e=kn(t,"f-"),r=Bc.openSync(e,Nc,384);return $c(e),{path:e,fd:r}},t_=t=>{let e=kn(t,"s-"),r=Bc.createWriteStream(e,{flags:Nc,mode:384});return $c(e),r};Ke.dir=Eg;Ke.track=WE;Ke.mkdir=JE;Ke.mkdirSync=QE;Ke.open=XE;Ke.openSync=e_;Ke.path=kn;Ke.cleanup=YE;Ke.cleanupSync=kg;Ke.createWriteStream=t_});var Rg=$((lP,Ig)=>{var Pg=require("child_process").exec,Tg=Uc(),r_=require("fs"),n_=eo(),i_=require("path"),{unlinkP:s_,readAndUnlinkP:o_}=n_;function xi(t={}){let e=r=>new Promise((n,i)=>{let s=r.length;if(s===0)return i(new Error("No displays detected try dropping screen option"));let a=s-1,l=t.screen||0;if(!Number.isInteger(l)||l<0||l>a){let g=a===0?"(valid choice is 0 or drop screen option altogether)":`(valid choice is an integer between 0 and ${a})`;return i(new Error(`Invalid choice of displayId: ${l} ${g}`))}let c=["jpg","jpeg","png","tiff","bmp","gif","pdf"],u=(t.format||"jpg").toLowerCase();if(!c.includes(u))return i(new Error("Invalid format"));let h,f;if(t.filename){let g=t.filename.replace(/[^a-zA-Z0-9._\-/]/g,""),y=g.lastIndexOf(".");f=y>=0?g.slice(y):`.${u}`,h=g}else f=`.${u}`;let d=Array(l+1).fill(null).map(()=>Tg.path({suffix:f})),p=[];t.filename&&(d[l]=h),p=d.slice(0,l+1);let m=["-x","-t",u,...p];require("child_process").execFile("screencapture",m,function(g,y){if(g)return i(g);t.filename?n(i_.resolve(h)):r_.readFile(d[l],function(b,D){if(b)return i(b);Promise.all(p.map(s_)).then(()=>n(D)).catch(v=>i(v))})})});return qc().then(r=>e(r))}var a_=`
99
99
  Graphics/Displays:
100
100
 
101
101
  Intel Iris:
@@ -125,54 +125,54 @@ Graphics/Displays:
125
125
  Online: Yes
126
126
  Rotation: Supported
127
127
  Television: Yes
128
- `;function a_(t){let e=[],r=/(\s*)(.*?):(.*)\n/g,n;for(;(n=r.exec(t))!==null;)e.push({indent:n[1].length,key:n[2].trim(),value:n[3].trim()});return e}function Tg(t,e,r){let n;for(;n=r.shift();)if(n.value==="")if(t<n.indent){for(;n.key in e;)n.key+="_1";e[n.key]={},Tg(n.indent,e[n.key],r)}else{r.unshift(n);return}else{for(;n.key in e;)n.key+="_1";e[n.key]=n.value}}function l_(t){let e=t.filter(n=>n.primary),r=t.filter(n=>!n.primary);return[...e,...r]}function c_(t){let e=0;return t.map(r=>Object.assign({},r,{id:e++}))}function Ag(t){let e={};if(Tg(-1,e,a_(t)),!e["Graphics/Displays"])return[];let r=Object.keys(e["Graphics/Displays"]);if(!r||r.length<=0)return[];let n=[];return r.forEach(i=>{let s=e["Graphics/Displays"][i];if(s.Displays){let a=Object.entries(s.Displays).map(([l,c])=>{let u=c["Main Display"]==="Yes";return{name:l,primary:u}});n=n.concat(a)}}),c_(l_(n))}function Uc(){return new Promise((t,e)=>{Fg("system_profiler SPDisplaysDataType",(r,n)=>{if(r)return e(r);t(Ag(n))})})}function u_(){return new Promise((t,e)=>{Uc().then(r=>{let n=r.map(()=>Pg.path({suffix:".jpg"}));Fg("screencapture -x -t jpg "+n.join(" "),function(i,s){if(i)return e(i);Promise.all(n.map(s_)).then(t).catch(e)})})})}xi.listDisplays=Uc;xi.all=u_;xi.parseDisplaysOutput=Ag;xi.EXAMPLE_DISPLAYS_OUTPUT=o_;Og.exports=xi});var Ng=$((lP,Lg)=>{var d_=require("child_process").exec,Rg=$c(),Te=require("path"),f_=eo(),lt=require("fs"),ki=require("os"),{readAndUnlinkP:h_,defaultAll:p_}=f_;function Mg(){let t=Te.join(ki.tmpdir(),"screenCapture","screenCapture_1.3.2.bat"),e=Te.join(ki.tmpdir(),"screenCapture","app.manifest"),r=Te.join(__dirname,"screenCapture_1.3.2.bat").replace("app.asar","app.asar.unpacked"),n=Te.join(__dirname,"app.manifest").replace("app.asar","app.asar.unpacked");if(!lt.existsSync(t)){let i=Te.join(ki.tmpdir(),"screenCapture");lt.existsSync(i)||lt.mkdirSync(i);let s={bat:lt.readFileSync(r),manifest:lt.readFileSync(n)};lt.writeFileSync(t,s.bat),lt.writeFileSync(e,s.manifest)}return t}function $r(t={}){return new Promise((e,r)=>{let n=["jpg","jpeg","png","bmp"],i=(t.format||"jpg").toLowerCase();if(!n.includes(i))return r(new Error("Invalid format"));let s,a=null;if(t.filename){s=Rg.path({suffix:`.${i}`});let f=Te.dirname(t.filename),p=Te.basename(t.filename).replace(/[^a-zA-Z0-9._\- ]/g,"");a=Te.isAbsolute(t.filename)?Te.join(f,p):Te.join(process.cwd(),f,p),a=Te.normalize(a);let m=Te.dirname(a);lt.existsSync(m)||lt.mkdirSync(m,{recursive:!0})}else s=Rg.path({suffix:`.${i}`});let l=t.screen?String(t.screen):"",c=Mg(),u=[s];l&&u.push("/d",l);let h=["/c",c,...u];require("child_process").execFile("cmd.exe",h,{cwd:Te.join(ki.tmpdir(),"screenCapture"),windowsHide:!0},(f,d,p)=>{if(f)return r(f);t.filename?lt.copyFile(s,a,m=>{if(m)return r(m);e(a)}):h_(s).then(e).catch(r)})})}var m_=`\r
128
+ `;function l_(t){let e=[],r=/(\s*)(.*?):(.*)\n/g,n;for(;(n=r.exec(t))!==null;)e.push({indent:n[1].length,key:n[2].trim(),value:n[3].trim()});return e}function Ag(t,e,r){let n;for(;n=r.shift();)if(n.value==="")if(t<n.indent){for(;n.key in e;)n.key+="_1";e[n.key]={},Ag(n.indent,e[n.key],r)}else{r.unshift(n);return}else{for(;n.key in e;)n.key+="_1";e[n.key]=n.value}}function c_(t){let e=t.filter(n=>n.primary),r=t.filter(n=>!n.primary);return[...e,...r]}function u_(t){let e=0;return t.map(r=>Object.assign({},r,{id:e++}))}function Og(t){let e={};if(Ag(-1,e,l_(t)),!e["Graphics/Displays"])return[];let r=Object.keys(e["Graphics/Displays"]);if(!r||r.length<=0)return[];let n=[];return r.forEach(i=>{let s=e["Graphics/Displays"][i];if(s.Displays){let a=Object.entries(s.Displays).map(([l,c])=>{let u=c["Main Display"]==="Yes";return{name:l,primary:u}});n=n.concat(a)}}),u_(c_(n))}function qc(){return new Promise((t,e)=>{Pg("system_profiler SPDisplaysDataType",(r,n)=>{if(r)return e(r);t(Og(n))})})}function d_(){return new Promise((t,e)=>{qc().then(r=>{let n=r.map(()=>Tg.path({suffix:".jpg"}));Pg("screencapture -x -t jpg "+n.join(" "),function(i,s){if(i)return e(i);Promise.all(n.map(o_)).then(t).catch(e)})})})}xi.listDisplays=qc;xi.all=d_;xi.parseDisplaysOutput=Og;xi.EXAMPLE_DISPLAYS_OUTPUT=a_;Ig.exports=xi});var $g=$((cP,Ng)=>{var f_=require("child_process").exec,Mg=Uc(),Te=require("path"),h_=eo(),ut=require("fs"),ki=require("os"),{readAndUnlinkP:p_,defaultAll:m_}=h_;function jg(){let t=Te.join(ki.tmpdir(),"screenCapture","screenCapture_1.3.2.bat"),e=Te.join(ki.tmpdir(),"screenCapture","app.manifest"),r=Te.join(__dirname,"screenCapture_1.3.2.bat").replace("app.asar","app.asar.unpacked"),n=Te.join(__dirname,"app.manifest").replace("app.asar","app.asar.unpacked");if(!ut.existsSync(t)){let i=Te.join(ki.tmpdir(),"screenCapture");ut.existsSync(i)||ut.mkdirSync(i);let s={bat:ut.readFileSync(r),manifest:ut.readFileSync(n)};ut.writeFileSync(t,s.bat),ut.writeFileSync(e,s.manifest)}return t}function $r(t={}){return new Promise((e,r)=>{let n=["jpg","jpeg","png","bmp"],i=(t.format||"jpg").toLowerCase();if(!n.includes(i))return r(new Error("Invalid format"));let s,a=null;if(t.filename){s=Mg.path({suffix:`.${i}`});let f=Te.dirname(t.filename),p=Te.basename(t.filename).replace(/[^a-zA-Z0-9._\- ]/g,"");a=Te.isAbsolute(t.filename)?Te.join(f,p):Te.join(process.cwd(),f,p),a=Te.normalize(a);let m=Te.dirname(a);ut.existsSync(m)||ut.mkdirSync(m,{recursive:!0})}else s=Mg.path({suffix:`.${i}`});let l=t.screen?String(t.screen):"",c=jg(),u=[s];l&&u.push("/d",l);let h=["/c",c,...u];require("child_process").execFile("cmd.exe",h,{cwd:Te.join(ki.tmpdir(),"screenCapture"),windowsHide:!0},(f,d,p)=>{if(f)return r(f);t.filename?ut.copyFile(s,a,m=>{if(m)return r(m);e(a)}):p_(s).then(e).catch(r)})})}var g_=`\r
129
129
  C:\\Users\\devetry\\screenshot-desktop\\lib\\win32>// 2>nul || \r
130
130
  \\.\\DISPLAY1;0;1920;1080;0\r
131
131
  \\.\\DISPLAY2;0;3840;1080;1920\r
132
- `;function jg(t){let e=/2>nul {2}\|\| /,{0:r,index:n}=e.exec(t);return t.slice(n+r.length).split(`
133
- `).map(i=>i.replace(/[\n\r]/g,"")).map(i=>i.match(/(.*?);(.?\d+);(.?\d+);(.?\d+);(.?\d+);(.?\d*[\.,]?\d+)/)).filter(i=>i).map(i=>({id:i[1],name:i[1],top:+i[2],right:+i[3],bottom:+i[4],left:+i[5],dpiScale:+i[6].replace(",",".")})).map(i=>Object.assign(i,{height:i.bottom-i.top,width:i.right-i.left}))}function Bg(){return new Promise((t,e)=>{let r=Mg();d_('"'+r+'" /list',{cwd:Te.join(ki.tmpdir(),"screenCapture")},(n,i)=>{if(n)return e(n);t(jg(i))})})}$r.listDisplays=Bg;$r.availableDisplays=Bg;$r.parseDisplaysOutput=jg;$r.EXAMPLE_DISPLAYS_OUTPUT=m_;$r.all=()=>p_($r);Lg.exports=$r});var $g=$((cP,Fi)=>{"strict mode";process.platform==="linux"?Fi.exports=pm():process.platform==="darwin"?Fi.exports=Ig():process.platform==="win32"?Fi.exports=Ng():Fi.exports=function(){return Promise.reject(new Error("Currently unsupported platform. Pull requests welcome!"))}});var Ai=Me(require("fs")),Wc=Me(require("path"));function Gc(t){let e="";try{let n=Ai.readdirSync(t).filter(i=>!i.startsWith(".")&&i!=="node_modules"&&i!=="dist");for(let i of n.slice(0,100)){let a=Ai.statSync(Wc.join(t,i)).isDirectory();e+=`${i} [${a?"folder":"file"}]
134
- `}}catch{}return e}function Zc(t){try{let e=t.match(/\[[\s\S]*\]/);if(!e)throw new Error("No JSON array found in response");let r=JSON.parse(e[0]);if(!Array.isArray(r))throw new Error("Response is not an array");return r.filter(n=>!n.type||!n.path?!1:["view","create","modify","delete","rename","list"].includes(n.type))}catch(e){let r=e instanceof Error?e.message:"Unknown error";return console.error("Failed to parse workspace actions:",r),[]}}function Oi(t){return t.replace(/\\n/g,`
135
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Kc(t){let e=t.trim();return e.startsWith("```")&&(e=e.replace(/^```[a-z]*\n?/,"").replace(/\n?```$/,"").trim()),e}var Hc=["(\u25D5\u203F\u25D5)","\u30FD(\xB4\u25BD`)/","(\uFF61\u25D5\u203F\u25D5\uFF61)","(\u3065\uFF61\u25D5\u203F\u203F\u25D5\uFF61)\u3065","\u0295\u2022\u1D25\u2022\u0294","(\uFF89\u25D5\u30EE\u25D5)\uFF89*:\uFF65\uFF9F\u2727","(\u25D5\u1D17\u25D5\u273F)","(\uFF61\u2665\u203F\u2665\uFF61)","\u266A(\u250C\u30FB\u3002\u30FB)\u250C","(\uFF89\xB4\u30EE`)\uFF89*: \uFF65\uFF9F","(\uFFE3\u25BD\uFFE3)\u30CE","(\u25E0\u203F\u25E0)","(\u2022\u203F\u2022)","\u2570(*\xB0\u25BD\xB0*)\u256F","(\u2267\u25E1\u2266)","(\u261E\uFF9F\u30EE\uFF9F)\u261E","(\u3065\uFFE3 \xB3\uFFE3)\u3065","\u30FE(\u2310\u25A0_\u25A0)\u30CE\u266A","(\u0E07 \u2022\u0300_\u2022\u0301)\u0E07","(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B","\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)","( \u2022_\u2022)>\u2310\u25A0-\u25A0","(\u2310\u25A0_\u25A0)","\xAF\\_(\u30C4)_/\xAF","( \u0361\xB0 \u035C\u0296 \u0361\xB0)","\u0CA0_\u0CA0"],Yc=["(\u0E51\u2022\uFE4F\u2022)","(\u30FB_\u30FB\u30FE","( \u02D8\u03C9\u02D8 )","(\xB4-\u03C9-`)","( \xB4 \u25BD ` )"];function Ii(){return Hc[Math.floor(Math.random()*Hc.length)]}function Fn(){return Yc[Math.floor(Math.random()*Yc.length)]}var Pn=Me(require("node:fs"),1),xo=require("node:path");var C_=Me(yo(),1),Qc="11434",Xc=`http://127.0.0.1:${Qc}`,oy="0.6.3",ay=Object.defineProperty,ly=(t,e,r)=>e in t?ay(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bo=(t,e,r)=>(ly(t,typeof e!="symbol"?e+"":e,r),r),wo=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)}},So=class{constructor(e,r,n){bo(this,"abortController"),bo(this,"itr"),bo(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.")}},Co=async t=>{if(t.ok)return;let e=`Error ${t.status}: ${t.statusText}`,r=null;if(t.headers.get("content-type")?.includes("application/json"))try{r=await t.json(),e=r.error||e}catch{console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await t.text()||e}catch{console.log("Failed to get text from error response")}throw new wo(e,t.status)};function cy(){if(typeof window<"u"&&window.navigator){let t=navigator;return"userAgentData"in t&&t.userAgentData?.platform?`${t.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<"u")return`${process.arch} ${process.platform} Node.js/${process.version}`;return""}function uy(t){if(t instanceof Headers){let e={};return t.forEach((r,n)=>{e[n]=r}),e}else return Array.isArray(t)?Object.fromEntries(t):t||{}}var dy=(t,e)=>t[e],Eo=async(t,e,r={})=>{let n={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${oy} (${cy()})`};r.headers=uy(r.headers);try{let s=new URL(e);if(s.protocol==="https:"&&s.hostname==="ollama.com"){let a=typeof process=="object"&&process!==null&&typeof process.env=="object"&&process.env!==null?dy(process.env,"OLLAMA_API_KEY"):void 0;!(r.headers.authorization||r.headers.Authorization)&&a&&(r.headers.Authorization=`Bearer ${a}`)}}catch(s){console.error("error parsing url",s)}let i=Object.fromEntries(Object.entries(r.headers).filter(([s])=>!Object.keys(n).some(a=>a.toLowerCase()===s.toLowerCase())));return r.headers={...n,...i},t(e,r)},vo=async(t,e,r)=>{let n=await Eo(t,e,{headers:r?.headers});return await Co(n),n},At=async(t,e,r,n)=>{let s=(l=>l!==null&&typeof l=="object"&&!Array.isArray(l))(r)?JSON.stringify(r):r,a=await Eo(t,e,{method:"POST",body:s,signal:n?.signal,headers:n?.headers});return await Co(a),a},fy=async(t,e,r,n)=>{let i=await Eo(t,e,{method:"DELETE",body:JSON.stringify(r),headers:n?.headers});return await Co(i),i},hy=async function*(t){let e=new TextDecoder("utf-8"),r="",n=t.getReader();for(;;){let{done:i,value:s}=await n.read();if(i)break;r+=e.decode(s,{stream:!0});let a=r.split(`
132
+ `;function Bg(t){let e=/2>nul {2}\|\| /,{0:r,index:n}=e.exec(t);return t.slice(n+r.length).split(`
133
+ `).map(i=>i.replace(/[\n\r]/g,"")).map(i=>i.match(/(.*?);(.?\d+);(.?\d+);(.?\d+);(.?\d+);(.?\d*[\.,]?\d+)/)).filter(i=>i).map(i=>({id:i[1],name:i[1],top:+i[2],right:+i[3],bottom:+i[4],left:+i[5],dpiScale:+i[6].replace(",",".")})).map(i=>Object.assign(i,{height:i.bottom-i.top,width:i.right-i.left}))}function Lg(){return new Promise((t,e)=>{let r=jg();f_('"'+r+'" /list',{cwd:Te.join(ki.tmpdir(),"screenCapture")},(n,i)=>{if(n)return e(n);t(Bg(i))})})}$r.listDisplays=Lg;$r.availableDisplays=Lg;$r.parseDisplaysOutput=Bg;$r.EXAMPLE_DISPLAYS_OUTPUT=g_;$r.all=()=>m_($r);Ng.exports=$r});var Ug=$((uP,Fi)=>{"strict mode";process.platform==="linux"?Fi.exports=mm():process.platform==="darwin"?Fi.exports=Rg():process.platform==="win32"?Fi.exports=$g():Fi.exports=function(){return Promise.reject(new Error("Currently unsupported platform. Pull requests welcome!"))}});var Ai=je(require("fs")),Gc=je(require("path"));function Zc(t){let e="";try{let n=Ai.readdirSync(t).filter(i=>!i.startsWith(".")&&i!=="node_modules"&&i!=="dist");for(let i of n.slice(0,100)){let a=Ai.statSync(Gc.join(t,i)).isDirectory();e+=`${i} [${a?"folder":"file"}]
134
+ `}}catch{}return e}function Kc(t){try{let e=t.match(/\[[\s\S]*\]/);if(!e)throw new Error("No JSON array found in response");let r=JSON.parse(e[0]);if(!Array.isArray(r))throw new Error("Response is not an array");return r.filter(n=>!n.type||!n.path?!1:["view","create","modify","delete","rename","list"].includes(n.type))}catch(e){let r=e instanceof Error?e.message:"Unknown error";return console.error("Failed to parse workspace actions:",r),[]}}function Oi(t){return t.replace(/\\n/g,`
135
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function Hc(t){let e=t.trim();return e.startsWith("```")&&(e=e.replace(/^```[a-z]*\n?/,"").replace(/\n?```$/,"").trim()),e}var Yc=["(\u25D5\u203F\u25D5)","\u30FD(\xB4\u25BD`)/","(\uFF61\u25D5\u203F\u25D5\uFF61)","(\u3065\uFF61\u25D5\u203F\u203F\u25D5\uFF61)\u3065","\u0295\u2022\u1D25\u2022\u0294","(\uFF89\u25D5\u30EE\u25D5)\uFF89*:\uFF65\uFF9F\u2727","(\u25D5\u1D17\u25D5\u273F)","(\uFF61\u2665\u203F\u2665\uFF61)","\u266A(\u250C\u30FB\u3002\u30FB)\u250C","(\uFF89\xB4\u30EE`)\uFF89*: \uFF65\uFF9F","(\uFFE3\u25BD\uFFE3)\u30CE","(\u25E0\u203F\u25E0)","(\u2022\u203F\u2022)","\u2570(*\xB0\u25BD\xB0*)\u256F","(\u2267\u25E1\u2266)","(\u261E\uFF9F\u30EE\uFF9F)\u261E","(\u3065\uFFE3 \xB3\uFFE3)\u3065","\u30FE(\u2310\u25A0_\u25A0)\u30CE\u266A","(\u0E07 \u2022\u0300_\u2022\u0301)\u0E07","(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B","\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)","( \u2022_\u2022)>\u2310\u25A0-\u25A0","(\u2310\u25A0_\u25A0)","\xAF\\_(\u30C4)_/\xAF","( \u0361\xB0 \u035C\u0296 \u0361\xB0)","\u0CA0_\u0CA0"],Jc=["(\u0E51\u2022\uFE4F\u2022)","(\u30FB_\u30FB\u30FE","( \u02D8\u03C9\u02D8 )","(\xB4-\u03C9-`)","( \xB4 \u25BD ` )"];function Ii(){return Yc[Math.floor(Math.random()*Yc.length)]}function Fn(){return Jc[Math.floor(Math.random()*Jc.length)]}var Pn=je(require("node:fs"),1),ko=require("node:path");var E_=je(bo(),1),Xc="11434",eu=`http://127.0.0.1:${Xc}`,ay="0.6.3",ly=Object.defineProperty,cy=(t,e,r)=>e in t?ly(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vo=(t,e,r)=>(cy(t,typeof e!="symbol"?e+"":e,r),r),So=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)}},Co=class{constructor(e,r,n){vo(this,"abortController"),vo(this,"itr"),vo(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.")}},Eo=async t=>{if(t.ok)return;let e=`Error ${t.status}: ${t.statusText}`,r=null;if(t.headers.get("content-type")?.includes("application/json"))try{r=await t.json(),e=r.error||e}catch{console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await t.text()||e}catch{console.log("Failed to get text from error response")}throw new So(e,t.status)};function uy(){if(typeof window<"u"&&window.navigator){let t=navigator;return"userAgentData"in t&&t.userAgentData?.platform?`${t.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<"u")return`${process.arch} ${process.platform} Node.js/${process.version}`;return""}function dy(t){if(t instanceof Headers){let e={};return t.forEach((r,n)=>{e[n]=r}),e}else return Array.isArray(t)?Object.fromEntries(t):t||{}}var fy=(t,e)=>t[e],_o=async(t,e,r={})=>{let n={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${ay} (${uy()})`};r.headers=dy(r.headers);try{let s=new URL(e);if(s.protocol==="https:"&&s.hostname==="ollama.com"){let a=typeof process=="object"&&process!==null&&typeof process.env=="object"&&process.env!==null?fy(process.env,"OLLAMA_API_KEY"):void 0;!(r.headers.authorization||r.headers.Authorization)&&a&&(r.headers.Authorization=`Bearer ${a}`)}}catch(s){console.error("error parsing url",s)}let i=Object.fromEntries(Object.entries(r.headers).filter(([s])=>!Object.keys(n).some(a=>a.toLowerCase()===s.toLowerCase())));return r.headers={...n,...i},t(e,r)},Do=async(t,e,r)=>{let n=await _o(t,e,{headers:r?.headers});return await Eo(n),n},At=async(t,e,r,n)=>{let s=(l=>l!==null&&typeof l=="object"&&!Array.isArray(l))(r)?JSON.stringify(r):r,a=await _o(t,e,{method:"POST",body:s,signal:n?.signal,headers:n?.headers});return await Eo(a),a},hy=async(t,e,r,n)=>{let i=await _o(t,e,{method:"DELETE",body:JSON.stringify(r),headers:n?.headers});return await Eo(i),i},py=async function*(t){let e=new TextDecoder("utf-8"),r="",n=t.getReader();for(;;){let{done:i,value:s}=await n.read();if(i)break;r+=e.decode(s,{stream:!0});let a=r.split(`
136
136
  `);r=a.pop()??"";for(let l of a)try{yield JSON.parse(l)}catch{console.warn("invalid json: ",l)}}r+=e.decode();for(let i of r.split(`
137
- `).filter(s=>s!==""))try{yield JSON.parse(i)}catch{console.warn("invalid json: ",i)}},py=t=>{if(!t)return Xc;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=Qc);let i="";r.username&&(i=r.username,r.password&&(i+=`:${r.password}`),i+="@");let s=`${r.protocol}//${i}${r.hostname}:${n}${r.pathname}`;return s.endsWith("/")&&(s=s.slice(0,-1)),s},my=Object.defineProperty,gy=(t,e,r)=>e in t?my(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Do=(t,e,r)=>(gy(t,typeof e!="symbol"?e+"":e,r),r),_o=class{constructor(e){Do(this,"config"),Do(this,"fetch"),Do(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=py(e?.host??Xc)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,r){r.stream=r.stream??!1;let n=`${this.config.host}/api/${e}`;if(r.stream){let s=new AbortController,a=await At(this.fetch,n,r,{signal:s.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let l=hy(a.body),c=new So(s,l,()=>{let u=this.ongoingStreamedRequests.indexOf(c);u>-1&&this.ongoingStreamedRequests.splice(u,1)});return this.ongoingStreamedRequests.push(c),c}return await(await At(this.fetch,n,r,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let r=new Uint8Array(e),n="",i=r.byteLength;for(let s=0;s<i;s++)n+=String.fromCharCode(r[s]);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 fy(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await At(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await vo(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await At(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await At(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await At(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await vo(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await vo(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await At(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await At(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},__=new _o;var F_=Me(yo(),1),Tn=class extends _o{async encodeImage(e){if(typeof e!="string")return Buffer.from(e).toString("base64");try{if(Pn.default.existsSync(e)){let r=await Pn.promises.readFile((0,xo.resolve)(e));return Buffer.from(r).toString("base64")}}catch{}return e}async fileExists(e){try{return await Pn.promises.access(e),!0}catch{return!1}}async create(e){if(e.from&&await this.fileExists((0,xo.resolve)(e.from)))throw Error("Creating with a local path is not currently supported from ollama-js");return e.stream?super.create(e):super.create(e)}},P_=new Tn;var o={};iy(o,{BRAND:()=>qy,DIRTY:()=>Xt,EMPTY_PATH:()=>Dy,INVALID:()=>U,NEVER:()=>x0,OK:()=>Se,ParseStatus:()=>ye,Schema:()=>Z,ZodAny:()=>Rt,ZodArray:()=>ht,ZodBigInt:()=>tr,ZodBoolean:()=>rr,ZodBranded:()=>On,ZodCatch:()=>hr,ZodDate:()=>nr,ZodDefault:()=>fr,ZodDiscriminatedUnion:()=>Bi,ZodEffects:()=>Le,ZodEnum:()=>ur,ZodError:()=>xe,ZodFirstPartyTypeKind:()=>F,ZodFunction:()=>Ni,ZodIntersection:()=>ar,ZodIssueCode:()=>k,ZodLazy:()=>lr,ZodLiteral:()=>cr,ZodMap:()=>Zr,ZodNaN:()=>Hr,ZodNativeEnum:()=>dr,ZodNever:()=>qe,ZodNull:()=>sr,ZodNullable:()=>Ye,ZodNumber:()=>er,ZodObject:()=>ke,ZodOptional:()=>je,ZodParsedType:()=>O,ZodPipeline:()=>In,ZodPromise:()=>Mt,ZodReadonly:()=>pr,ZodRecord:()=>Li,ZodSchema:()=>Z,ZodSet:()=>Kr,ZodString:()=>It,ZodSymbol:()=>Wr,ZodTransformer:()=>Le,ZodTuple:()=>He,ZodType:()=>Z,ZodUndefined:()=>ir,ZodUnion:()=>or,ZodUnknown:()=>ft,ZodVoid:()=>Gr,addIssueToContext:()=>T,any:()=>Jy,array:()=>t0,bigint:()=>Gy,boolean:()=>uu,coerce:()=>_0,custom:()=>au,date:()=>Zy,datetimeRegex:()=>su,defaultErrorMap:()=>ut,discriminatedUnion:()=>s0,effect:()=>y0,enum:()=>p0,function:()=>d0,getErrorMap:()=>qr,getParsedType:()=>Ke,instanceof:()=>Vy,intersection:()=>o0,isAborted:()=>Mi,isAsync:()=>zr,isDirty:()=>ji,isValid:()=>Ot,late:()=>zy,lazy:()=>f0,literal:()=>h0,makeIssue:()=>An,map:()=>c0,nan:()=>Wy,nativeEnum:()=>m0,never:()=>Xy,null:()=>Yy,nullable:()=>v0,number:()=>cu,object:()=>r0,objectUtil:()=>ko,oboolean:()=>E0,onumber:()=>C0,optional:()=>b0,ostring:()=>S0,pipeline:()=>w0,preprocess:()=>D0,promise:()=>g0,quotelessJson:()=>yy,record:()=>l0,set:()=>u0,setErrorMap:()=>vy,strictObject:()=>n0,string:()=>lu,symbol:()=>Ky,transformer:()=>y0,tuple:()=>a0,undefined:()=>Hy,union:()=>i0,unknown:()=>Qy,util:()=>K,void:()=>e0});var K;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(l=>typeof i[i[l]]!="number"),a={};for(let l of s)a[l]=i[l];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},t.find=(i,s)=>{for(let a of i)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(K||(K={}));var ko;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(ko||(ko={}));var O=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ke=t=>{switch(typeof t){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(t)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(t)?O.array:t===null?O.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?O.promise:typeof Map<"u"&&t instanceof Map?O.map:typeof Set<"u"&&t instanceof Set?O.set:typeof Date<"u"&&t instanceof Date?O.date:O.object;default:return O.unknown}};var k=K.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),yy=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),xe=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let l=n,c=0;for(;c<a.path.length;){let u=a.path[c];c===a.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(r(a))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};xe.create=t=>new xe(t);var by=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===O.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,K.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${K.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${K.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${K.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:K.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case k.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case k.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=e.defaultError,K.assertNever(t)}return{message:r}},ut=by;var eu=ut;function vy(t){eu=t}function qr(){return eu}var An=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let l="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)l=u(a,{data:e,defaultError:l}).message;return{...i,path:s,message:l}},Dy=[];function T(t,e){let r=qr(),n=An({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ut?void 0:ut].filter(i=>!!i)});t.common.issues.push(n)}var ye=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return U;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,a=await i.value;n.push({key:s,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return U;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}},U=Object.freeze({status:"aborted"}),Xt=t=>({status:"dirty",value:t}),Se=t=>({status:"valid",value:t}),Mi=t=>t.status==="aborted",ji=t=>t.status==="dirty",Ot=t=>t.status==="valid",zr=t=>typeof Promise<"u"&&t instanceof Promise;var R;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(R||(R={}));var Be=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},tu=(t,e)=>{if(Ot(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new xe(t.common.issues);return this._error=r,this._error}}};function G(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,l)=>{let{message:c}=t;return a.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??n??l.defaultError}:a.code!=="invalid_type"?{message:l.defaultError}:{message:c??r??l.defaultError}},description:i}}var Z=class{get description(){return this._def.description}_getType(e){return Ke(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ye,ctx:{common:e.parent.common,data:e.data,parsedType:Ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(zr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)},i=this._parseSync({data:e,path:n.path,parent:n});return tu(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Ot(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Ot(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ke(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(zr(i)?i:Promise.resolve(i));return tu(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let a=e(i),l=()=>s.addIssue({code:k.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(l(),!1)):a?!0:(l(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Le({schema:this,typeName:F.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return je.create(this,this._def)}nullable(){return Ye.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ht.create(this)}promise(){return Mt.create(this,this._def)}or(e){return or.create([this,e],this._def)}and(e){return ar.create(this,e,this._def)}transform(e){return new Le({...G(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new fr({...G(this._def),innerType:this,defaultValue:r,typeName:F.ZodDefault})}brand(){return new On({typeName:F.ZodBranded,type:this,...G(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new hr({...G(this._def),innerType:this,catchValue:r,typeName:F.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return In.create(this,e)}readonly(){return pr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},wy=/^c[^\s-]{8,}$/i,Sy=/^[0-9a-z]+$/,Cy=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ey=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,_y=/^[a-z0-9_-]{21}$/i,xy=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ky=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Fy=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Py="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fo,Ty=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ay=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Oy=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Iy=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ry=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,My=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nu="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",jy=new RegExp(`^${nu}$`);function iu(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function By(t){return new RegExp(`^${iu(t)}$`)}function su(t){let e=`${nu}T${iu(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Ly(t,e){return!!((e==="v4"||!e)&&Ty.test(t)||(e==="v6"||!e)&&Oy.test(t))}function Ny(t,e){if(!xy.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function $y(t,e){return!!((e==="v4"||!e)&&Ay.test(t)||(e==="v6"||!e)&&Iy.test(t))}var It=class t extends Z{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:O.string,received:s.parsedType}),U}let n=new ye,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,l=e.data.length<s.value;(a||l)&&(i=this._getOrReturnCtx(e,i),a?T(i,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):l&&T(i,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Fy.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Fo||(Fo=new RegExp(Py,"u")),Fo.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Ey.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")_y.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")wy.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Sy.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Cy.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),T(i,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?su(s).test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?jy.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?By(s).test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?ky.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Ly(e.data,s.version)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Ny(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?$y(e.data,s.version)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Ry.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?My.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):K.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:k.invalid_string,...R.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...R.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...R.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...R.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...R.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...R.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...R.errToObj(r)})}nonempty(e){return this.min(1,R.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};It.create=t=>new It({checks:[],typeName:F.ZodString,coerce:t?.coerce??!1,...G(t)});function Uy(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return s%a/10**i}var er=class t extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:O.number,received:s.parsedType}),U}let n,i=new ye;for(let s of this._def.checks)s.kind==="int"?K.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?Uy(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_finite,message:s.message}),i.dirty()):K.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,R.toString(r))}gt(e,r){return this.setLimit("min",e,!1,R.toString(r))}lte(e,r){return this.setLimit("max",e,!0,R.toString(r))}lt(e,r){return this.setLimit("max",e,!1,R.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:R.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&K.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};er.create=t=>new er({checks:[],typeName:F.ZodNumber,coerce:t?.coerce||!1,...G(t)});var tr=class t extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let n,i=new ye;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):K.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:O.bigint,received:r.parsedType}),U}gte(e,r){return this.setLimit("min",e,!0,R.toString(r))}gt(e,r){return this.setLimit("min",e,!1,R.toString(r))}lte(e,r){return this.setLimit("max",e,!0,R.toString(r))}lt(e,r){return this.setLimit("max",e,!1,R.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:R.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};tr.create=t=>new tr({checks:[],typeName:F.ZodBigInt,coerce:t?.coerce??!1,...G(t)});var rr=class extends Z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.boolean,received:n.parsedType}),U}return Se(e.data)}};rr.create=t=>new rr({typeName:F.ZodBoolean,coerce:t?.coerce||!1,...G(t)});var nr=class t extends Z{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:O.date,received:s.parsedType}),U}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_date}),U}let n=new ye,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):K.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:R.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:R.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};nr.create=t=>new nr({checks:[],coerce:t?.coerce||!1,typeName:F.ZodDate,...G(t)});var Wr=class extends Z{_parse(e){if(this._getType(e)!==O.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.symbol,received:n.parsedType}),U}return Se(e.data)}};Wr.create=t=>new Wr({typeName:F.ZodSymbol,...G(t)});var ir=class extends Z{_parse(e){if(this._getType(e)!==O.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.undefined,received:n.parsedType}),U}return Se(e.data)}};ir.create=t=>new ir({typeName:F.ZodUndefined,...G(t)});var sr=class extends Z{_parse(e){if(this._getType(e)!==O.null){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.null,received:n.parsedType}),U}return Se(e.data)}};sr.create=t=>new sr({typeName:F.ZodNull,...G(t)});var Rt=class extends Z{constructor(){super(...arguments),this._any=!0}_parse(e){return Se(e.data)}};Rt.create=t=>new Rt({typeName:F.ZodAny,...G(t)});var ft=class extends Z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Se(e.data)}};ft.create=t=>new ft({typeName:F.ZodUnknown,...G(t)});var qe=class extends Z{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:O.never,received:r.parsedType}),U}};qe.create=t=>new qe({typeName:F.ZodNever,...G(t)});var Gr=class extends Z{_parse(e){if(this._getType(e)!==O.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.void,received:n.parsedType}),U}return Se(e.data)}};Gr.create=t=>new Gr({typeName:F.ZodVoid,...G(t)});var ht=class t extends Z{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==O.array)return T(r,{code:k.invalid_type,expected:O.array,received:r.parsedType}),U;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,l=r.data.length<i.exactLength.value;(a||l)&&(T(r,{code:a?k.too_big:k.too_small,minimum:l?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(T(r,{code:k.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(T(r,{code:k.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,l)=>i.type._parseAsync(new Be(r,a,r.path,l)))).then(a=>ye.mergeArray(n,a));let s=[...r.data].map((a,l)=>i.type._parseSync(new Be(r,a,r.path,l)));return ye.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:R.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:R.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:R.toString(r)}})}nonempty(e){return this.min(1,e)}};ht.create=(t,e)=>new ht({type:t,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...G(e)});function Vr(t){if(t instanceof ke){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=je.create(Vr(n))}return new ke({...t._def,shape:()=>e})}else return t instanceof ht?new ht({...t._def,type:Vr(t.element)}):t instanceof je?je.create(Vr(t.unwrap())):t instanceof Ye?Ye.create(Vr(t.unwrap())):t instanceof He?He.create(t.items.map(e=>Vr(e))):t}var ke=class t extends Z{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=K.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==O.object){let u=this._getOrReturnCtx(e);return T(u,{code:k.invalid_type,expected:O.object,received:u.parsedType}),U}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),l=[];if(!(this._def.catchall instanceof qe&&this._def.unknownKeys==="strip"))for(let u in i.data)a.includes(u)||l.push(u);let c=[];for(let u of a){let h=s[u],f=i.data[u];c.push({key:{status:"valid",value:u},value:h._parse(new Be(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof qe){let u=this._def.unknownKeys;if(u==="passthrough")for(let h of l)c.push({key:{status:"valid",value:h},value:{status:"valid",value:i.data[h]}});else if(u==="strict")l.length>0&&(T(i,{code:k.unrecognized_keys,keys:l}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let h of l){let f=i.data[h];c.push({key:{status:"valid",value:h},value:u._parse(new Be(i,f,i.path,h)),alwaysSet:h in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let h of c){let f=await h.key,d=await h.value;u.push({key:f,value:d,alwaysSet:h.alwaysSet})}return u}).then(u=>ye.mergeObjectSync(n,u)):ye.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return R.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:R.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:F.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of K.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of K.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Vr(this)}partial(e){let r={};for(let n of K.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of K.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof je;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return ou(K.objectKeys(this.shape))}};ke.create=(t,e)=>new ke({shape:()=>t,unknownKeys:"strip",catchall:qe.create(),typeName:F.ZodObject,...G(e)});ke.strictCreate=(t,e)=>new ke({shape:()=>t,unknownKeys:"strict",catchall:qe.create(),typeName:F.ZodObject,...G(e)});ke.lazycreate=(t,e)=>new ke({shape:t,unknownKeys:"strip",catchall:qe.create(),typeName:F.ZodObject,...G(e)});var or=class extends Z{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let l of s)if(l.result.status==="valid")return l.result;for(let l of s)if(l.result.status==="dirty")return r.common.issues.push(...l.ctx.common.issues),l.result;let a=s.map(l=>new xe(l.ctx.common.issues));return T(r,{code:k.invalid_union,unionErrors:a}),U}if(r.common.async)return Promise.all(n.map(async s=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let s,a=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},h=c._parseSync({data:r.data,path:r.path,parent:u});if(h.status==="valid")return h;h.status==="dirty"&&!s&&(s={result:h,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let l=a.map(c=>new xe(c));return T(r,{code:k.invalid_union,unionErrors:l}),U}}get options(){return this._def.options}};or.create=(t,e)=>new or({options:t,typeName:F.ZodUnion,...G(e)});var dt=t=>t instanceof lr?dt(t.schema):t instanceof Le?dt(t.innerType()):t instanceof cr?[t.value]:t instanceof ur?t.options:t instanceof dr?K.objectValues(t.enum):t instanceof fr?dt(t._def.innerType):t instanceof ir?[void 0]:t instanceof sr?[null]:t instanceof je?[void 0,...dt(t.unwrap())]:t instanceof Ye?[null,...dt(t.unwrap())]:t instanceof On||t instanceof pr?dt(t.unwrap()):t instanceof hr?dt(t._def.innerType):[],Bi=class t extends Z{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.object)return T(r,{code:k.invalid_type,expected:O.object,received:r.parsedType}),U;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),U)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let a=dt(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of a){if(i.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);i.set(l,s)}}return new t({typeName:F.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...G(n)})}};function Po(t,e){let r=Ke(t),n=Ke(e);if(t===e)return{valid:!0,data:t};if(r===O.object&&n===O.object){let i=K.objectKeys(e),s=K.objectKeys(t).filter(l=>i.indexOf(l)!==-1),a={...t,...e};for(let l of s){let c=Po(t[l],e[l]);if(!c.valid)return{valid:!1};a[l]=c.data}return{valid:!0,data:a}}else if(r===O.array&&n===O.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let a=t[s],l=e[s],c=Po(a,l);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===O.date&&n===O.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ar=class extends Z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(s,a)=>{if(Mi(s)||Mi(a))return U;let l=Po(s.value,a.value);return l.valid?((ji(s)||ji(a))&&r.dirty(),{status:r.value,value:l.data}):(T(n,{code:k.invalid_intersection_types}),U)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ar.create=(t,e,r)=>new ar({left:t,right:e,typeName:F.ZodIntersection,...G(r)});var He=class t extends Z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.array)return T(n,{code:k.invalid_type,expected:O.array,received:n.parsedType}),U;if(n.data.length<this._def.items.length)return T(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((a,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new Be(n,a,n.path,l)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>ye.mergeArray(r,a)):ye.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};He.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new He({items:t,typeName:F.ZodTuple,rest:null,...G(e)})};var Li=class t extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.object)return T(n,{code:k.invalid_type,expected:O.object,received:n.parsedType}),U;let i=[],s=this._def.keyType,a=this._def.valueType;for(let l in n.data)i.push({key:s._parse(new Be(n,l,n.path,l)),value:a._parse(new Be(n,n.data[l],n.path,l)),alwaysSet:l in n.data});return n.common.async?ye.mergeObjectAsync(r,i):ye.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Z?new t({keyType:e,valueType:r,typeName:F.ZodRecord,...G(n)}):new t({keyType:It.create(),valueType:e,typeName:F.ZodRecord,...G(r)})}},Zr=class extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.map)return T(n,{code:k.invalid_type,expected:O.map,received:n.parsedType}),U;let i=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([l,c],u)=>({key:i._parse(new Be(n,l,n.path,[u,"key"])),value:s._parse(new Be(n,c,n.path,[u,"value"]))}));if(n.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of a){let u=await c.key,h=await c.value;if(u.status==="aborted"||h.status==="aborted")return U;(u.status==="dirty"||h.status==="dirty")&&r.dirty(),l.set(u.value,h.value)}return{status:r.value,value:l}})}else{let l=new Map;for(let c of a){let u=c.key,h=c.value;if(u.status==="aborted"||h.status==="aborted")return U;(u.status==="dirty"||h.status==="dirty")&&r.dirty(),l.set(u.value,h.value)}return{status:r.value,value:l}}}};Zr.create=(t,e,r)=>new Zr({valueType:e,keyType:t,typeName:F.ZodMap,...G(r)});var Kr=class t extends Z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.set)return T(n,{code:k.invalid_type,expected:O.set,received:n.parsedType}),U;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(T(n,{code:k.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(T(n,{code:k.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function a(c){let u=new Set;for(let h of c){if(h.status==="aborted")return U;h.status==="dirty"&&r.dirty(),u.add(h.value)}return{status:r.value,value:u}}let l=[...n.data.values()].map((c,u)=>s._parse(new Be(n,c,n.path,u)));return n.common.async?Promise.all(l).then(c=>a(c)):a(l)}min(e,r){return new t({...this._def,minSize:{value:e,message:R.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:R.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Kr.create=(t,e)=>new Kr({valueType:t,minSize:null,maxSize:null,typeName:F.ZodSet,...G(e)});var Ni=class t extends Z{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.function)return T(r,{code:k.invalid_type,expected:O.function,received:r.parsedType}),U;function n(l,c){return An({data:l,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qr(),ut].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function i(l,c){return An({data:l,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qr(),ut].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Mt){let l=this;return Se(async function(...c){let u=new xe([]),h=await l._def.args.parseAsync(c,s).catch(p=>{throw u.addIssue(n(c,p)),u}),f=await Reflect.apply(a,this,h);return await l._def.returns._def.type.parseAsync(f,s).catch(p=>{throw u.addIssue(i(f,p)),u})})}else{let l=this;return Se(function(...c){let u=l._def.args.safeParse(c,s);if(!u.success)throw new xe([n(c,u.error)]);let h=Reflect.apply(a,this,u.data),f=l._def.returns.safeParse(h,s);if(!f.success)throw new xe([i(h,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:He.create(e).rest(ft.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||He.create([]).rest(ft.create()),returns:r||ft.create(),typeName:F.ZodFunction,...G(n)})}},lr=class extends Z{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};lr.create=(t,e)=>new lr({getter:t,typeName:F.ZodLazy,...G(e)});var cr=class extends Z{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}};cr.create=(t,e)=>new cr({value:t,typeName:F.ZodLiteral,...G(e)});function ou(t,e){return new ur({values:t,typeName:F.ZodEnum,...G(e)})}var ur=class t extends Z{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:K.joinValues(n),received:r.parsedType,code:k.invalid_type}),U}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:k.invalid_enum_value,options:n}),U}return Se(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};ur.create=ou;var dr=class extends Z{_parse(e){let r=K.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==O.string&&n.parsedType!==O.number){let i=K.objectValues(r);return T(n,{expected:K.joinValues(i),received:n.parsedType,code:k.invalid_type}),U}if(this._cache||(this._cache=new Set(K.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=K.objectValues(r);return T(n,{received:n.data,code:k.invalid_enum_value,options:i}),U}return Se(e.data)}get enum(){return this._def.values}};dr.create=(t,e)=>new dr({values:t,typeName:F.ZodNativeEnum,...G(e)});var Mt=class extends Z{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.promise&&r.common.async===!1)return T(r,{code:k.invalid_type,expected:O.promise,received:r.parsedType}),U;let n=r.parsedType===O.promise?r.data:Promise.resolve(r.data);return Se(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Mt.create=(t,e)=>new Mt({type:t,typeName:F.ZodPromise,...G(e)});var Le=class extends Z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:a=>{T(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async l=>{if(r.value==="aborted")return U;let c=await this._def.schema._parseAsync({data:l,path:n.path,parent:n});return c.status==="aborted"?U:c.status==="dirty"?Xt(c.value):r.value==="dirty"?Xt(c.value):c});{if(r.value==="aborted")return U;let l=this._def.schema._parseSync({data:a,path:n.path,parent:n});return l.status==="aborted"?U:l.status==="dirty"?Xt(l.value):r.value==="dirty"?Xt(l.value):l}}if(i.type==="refinement"){let a=l=>{let c=i.refinement(l,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(n.common.async===!1){let l=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return l.status==="aborted"?U:(l.status==="dirty"&&r.dirty(),a(l.value),{status:r.value,value:l.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(l=>l.status==="aborted"?U:(l.status==="dirty"&&r.dirty(),a(l.value).then(()=>({status:r.value,value:l.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ot(a))return U;let l=i.transform(a.value,s);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:l}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Ot(a)?Promise.resolve(i.transform(a.value,s)).then(l=>({status:r.value,value:l})):U);K.assertNever(i)}};Le.create=(t,e,r)=>new Le({schema:t,typeName:F.ZodEffects,effect:e,...G(r)});Le.createWithPreprocess=(t,e,r)=>new Le({schema:e,effect:{type:"preprocess",transform:t},typeName:F.ZodEffects,...G(r)});var je=class extends Z{_parse(e){return this._getType(e)===O.undefined?Se(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};je.create=(t,e)=>new je({innerType:t,typeName:F.ZodOptional,...G(e)});var Ye=class extends Z{_parse(e){return this._getType(e)===O.null?Se(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ye.create=(t,e)=>new Ye({innerType:t,typeName:F.ZodNullable,...G(e)});var fr=class extends Z{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===O.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};fr.create=(t,e)=>new fr({innerType:t,typeName:F.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...G(e)});var hr=class extends Z{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return zr(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xe(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new xe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};hr.create=(t,e)=>new hr({innerType:t,typeName:F.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...G(e)});var Hr=class extends Z{_parse(e){if(this._getType(e)!==O.nan){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.nan,received:n.parsedType}),U}return{status:"valid",value:e.data}}};Hr.create=t=>new Hr({typeName:F.ZodNaN,...G(t)});var qy=Symbol("zod_brand"),On=class extends Z{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},In=class t extends Z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?U:s.status==="dirty"?(r.dirty(),Xt(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?U:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:F.ZodPipeline})}},pr=class extends Z{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Ot(i)&&(i.value=Object.freeze(i.value)),i);return zr(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};pr.create=(t,e)=>new pr({innerType:t,typeName:F.ZodReadonly,...G(e)});function ru(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function au(t,e={},r){return t?Rt.create().superRefine((n,i)=>{let s=t(n);if(s instanceof Promise)return s.then(a=>{if(!a){let l=ru(e,n),c=l.fatal??r??!0;i.addIssue({code:"custom",...l,fatal:c})}});if(!s){let a=ru(e,n),l=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:l})}}):Rt.create()}var zy={object:ke.lazycreate},F;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(F||(F={}));var Vy=(t,e={message:`Input not instance of ${t.name}`})=>au(r=>r instanceof t,e),lu=It.create,cu=er.create,Wy=Hr.create,Gy=tr.create,uu=rr.create,Zy=nr.create,Ky=Wr.create,Hy=ir.create,Yy=sr.create,Jy=Rt.create,Qy=ft.create,Xy=qe.create,e0=Gr.create,t0=ht.create,r0=ke.create,n0=ke.strictCreate,i0=or.create,s0=Bi.create,o0=ar.create,a0=He.create,l0=Li.create,c0=Zr.create,u0=Kr.create,d0=Ni.create,f0=lr.create,h0=cr.create,p0=ur.create,m0=dr.create,g0=Mt.create,y0=Le.create,b0=je.create,v0=Ye.create,D0=Le.createWithPreprocess,w0=In.create,S0=()=>lu().optional(),C0=()=>cu().optional(),E0=()=>uu().optional(),_0={string:(t=>It.create({...t,coerce:!0})),number:(t=>er.create({...t,coerce:!0})),boolean:(t=>rr.create({...t,coerce:!0})),bigint:(t=>tr.create({...t,coerce:!0})),date:(t=>nr.create({...t,coerce:!0}))};var x0=U;var Yn=Me(require("process"),1),I=Me(zu(),1),st=Me(sf(),1);var af=Symbol("Let zodToJsonSchema decide on which parser to use");var of={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},lf=t=>typeof t=="string"?{...of,name:t}:{...of,...t};var cf=t=>{let e=lf(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function fa(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function H(t,e,r,n,i){t[e]=r,fa(t,e,n,i)}var as=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function ie(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?as(e,t.currentPath):e.join("/")}}function uf(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==F.ZodAny&&(r.items=z(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&H(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&H(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(H(r,"minItems",t.exactLength.value,t.exactLength.message,e),H(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function df(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?H(r,"minimum",n.value,n.message,e):H(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),H(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?H(r,"maximum",n.value,n.message,e):H(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),H(r,"maximum",n.value,n.message,e));break;case"multipleOf":H(r,"multipleOf",n.value,n.message,e);break}return r}function ff(){return{type:"boolean"}}function ls(t,e){return z(t.type._def,e)}var hf=(t,e)=>z(t.innerType._def,e);function ha(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,s)=>ha(t,e,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Tv(t,e)}}var Tv=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":H(r,"minimum",n.value,n.message,e);break;case"max":H(r,"maximum",n.value,n.message,e);break}return r};function pf(t,e){return{...z(t.innerType._def,e),default:t.defaultValue()}}function mf(t,e){return e.effectStrategy==="input"?z(t.schema._def,e):ie(e)}function gf(t){return{type:"string",enum:Array.from(t.values)}}var Av=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function yf(t,e){let r=[z(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),z(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(s=>{if(Av(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:l,...c}=s;a=c}else n=void 0;i.push(a)}}),i.length?{allOf:i,...n}:void 0}function bf(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var pa,Ve={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(pa===void 0&&(pa=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),pa),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function cs(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":H(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":H(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":We(r,"email",n.message,e);break;case"format:idn-email":We(r,"idn-email",n.message,e);break;case"pattern:zod":_e(r,Ve.email,n.message,e);break}break;case"url":We(r,"uri",n.message,e);break;case"uuid":We(r,"uuid",n.message,e);break;case"regex":_e(r,n.regex,n.message,e);break;case"cuid":_e(r,Ve.cuid,n.message,e);break;case"cuid2":_e(r,Ve.cuid2,n.message,e);break;case"startsWith":_e(r,RegExp(`^${ma(n.value,e)}`),n.message,e);break;case"endsWith":_e(r,RegExp(`${ma(n.value,e)}$`),n.message,e);break;case"datetime":We(r,"date-time",n.message,e);break;case"date":We(r,"date",n.message,e);break;case"time":We(r,"time",n.message,e);break;case"duration":We(r,"duration",n.message,e);break;case"length":H(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),H(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{_e(r,RegExp(ma(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&We(r,"ipv4",n.message,e),n.version!=="v4"&&We(r,"ipv6",n.message,e);break}case"base64url":_e(r,Ve.base64url,n.message,e);break;case"jwt":_e(r,Ve.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&_e(r,Ve.ipv4Cidr,n.message,e),n.version!=="v4"&&_e(r,Ve.ipv6Cidr,n.message,e);break}case"emoji":_e(r,Ve.emoji(),n.message,e);break;case"ulid":{_e(r,Ve.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{We(r,"binary",n.message,e);break}case"contentEncoding:base64":{H(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{_e(r,Ve.base64,n.message,e);break}}break}case"nanoid":_e(r,Ve.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ma(t,e){return e.patternStrategy==="escape"?Iv(t):t}var Ov=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Iv(t){let e="";for(let r=0;r<t.length;r++)Ov.has(t[r])||(e+="\\"),e+=t[r];return e}function We(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):H(t,"format",e,r,n)}function _e(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:vf(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):H(t,"pattern",vf(e,n),r,n)}function vf(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,i="",s=!1,a=!1,l=!1;for(let c=0;c<n.length;c++){if(s){i+=n[c],s=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){l?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),l=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],l=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
137
+ `).filter(s=>s!==""))try{yield JSON.parse(i)}catch{console.warn("invalid json: ",i)}},my=t=>{if(!t)return eu;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=Xc);let i="";r.username&&(i=r.username,r.password&&(i+=`:${r.password}`),i+="@");let s=`${r.protocol}//${i}${r.hostname}:${n}${r.pathname}`;return s.endsWith("/")&&(s=s.slice(0,-1)),s},gy=Object.defineProperty,yy=(t,e,r)=>e in t?gy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wo=(t,e,r)=>(yy(t,typeof e!="symbol"?e+"":e,r),r),xo=class{constructor(e){wo(this,"config"),wo(this,"fetch"),wo(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=my(e?.host??eu)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,r){r.stream=r.stream??!1;let n=`${this.config.host}/api/${e}`;if(r.stream){let s=new AbortController,a=await At(this.fetch,n,r,{signal:s.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let l=py(a.body),c=new Co(s,l,()=>{let u=this.ongoingStreamedRequests.indexOf(c);u>-1&&this.ongoingStreamedRequests.splice(u,1)});return this.ongoingStreamedRequests.push(c),c}return await(await At(this.fetch,n,r,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let r=new Uint8Array(e),n="",i=r.byteLength;for(let s=0;s<i;s++)n+=String.fromCharCode(r[s]);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 hy(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await At(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Do(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await At(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await At(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await At(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Do(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await Do(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await At(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await At(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},x_=new xo;var P_=je(bo(),1),Tn=class extends xo{async encodeImage(e){if(typeof e!="string")return Buffer.from(e).toString("base64");try{if(Pn.default.existsSync(e)){let r=await Pn.promises.readFile((0,ko.resolve)(e));return Buffer.from(r).toString("base64")}}catch{}return e}async fileExists(e){try{return await Pn.promises.access(e),!0}catch{return!1}}async create(e){if(e.from&&await this.fileExists((0,ko.resolve)(e.from)))throw Error("Creating with a local path is not currently supported from ollama-js");return e.stream?super.create(e):super.create(e)}},T_=new Tn;var o={};sy(o,{BRAND:()=>zy,DIRTY:()=>Xt,EMPTY_PATH:()=>wy,INVALID:()=>U,NEVER:()=>k0,OK:()=>Se,ParseStatus:()=>ye,Schema:()=>Z,ZodAny:()=>Rt,ZodArray:()=>pt,ZodBigInt:()=>tr,ZodBoolean:()=>rr,ZodBranded:()=>On,ZodCatch:()=>hr,ZodDate:()=>nr,ZodDefault:()=>fr,ZodDiscriminatedUnion:()=>Bi,ZodEffects:()=>Ne,ZodEnum:()=>ur,ZodError:()=>xe,ZodFirstPartyTypeKind:()=>F,ZodFunction:()=>Ni,ZodIntersection:()=>ar,ZodIssueCode:()=>k,ZodLazy:()=>lr,ZodLiteral:()=>cr,ZodMap:()=>Zr,ZodNaN:()=>Hr,ZodNativeEnum:()=>dr,ZodNever:()=>ze,ZodNull:()=>sr,ZodNullable:()=>Qe,ZodNumber:()=>er,ZodObject:()=>ke,ZodOptional:()=>Be,ZodParsedType:()=>O,ZodPipeline:()=>In,ZodPromise:()=>Mt,ZodReadonly:()=>pr,ZodRecord:()=>Li,ZodSchema:()=>Z,ZodSet:()=>Kr,ZodString:()=>It,ZodSymbol:()=>Wr,ZodTransformer:()=>Ne,ZodTuple:()=>Je,ZodType:()=>Z,ZodUndefined:()=>ir,ZodUnion:()=>or,ZodUnknown:()=>ht,ZodVoid:()=>Gr,addIssueToContext:()=>T,any:()=>Qy,array:()=>r0,bigint:()=>Zy,boolean:()=>du,coerce:()=>x0,custom:()=>lu,date:()=>Ky,datetimeRegex:()=>ou,defaultErrorMap:()=>dt,discriminatedUnion:()=>o0,effect:()=>b0,enum:()=>m0,function:()=>f0,getErrorMap:()=>qr,getParsedType:()=>Ye,instanceof:()=>Wy,intersection:()=>a0,isAborted:()=>Mi,isAsync:()=>zr,isDirty:()=>ji,isValid:()=>Ot,late:()=>Vy,lazy:()=>h0,literal:()=>p0,makeIssue:()=>An,map:()=>u0,nan:()=>Gy,nativeEnum:()=>g0,never:()=>e0,null:()=>Jy,nullable:()=>D0,number:()=>uu,object:()=>n0,objectUtil:()=>Fo,oboolean:()=>_0,onumber:()=>E0,optional:()=>v0,ostring:()=>C0,pipeline:()=>S0,preprocess:()=>w0,promise:()=>y0,quotelessJson:()=>by,record:()=>c0,set:()=>d0,setErrorMap:()=>Dy,strictObject:()=>i0,string:()=>cu,symbol:()=>Hy,transformer:()=>b0,tuple:()=>l0,undefined:()=>Yy,union:()=>s0,unknown:()=>Xy,util:()=>K,void:()=>t0});var K;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},t.getValidEnumValues=i=>{let s=t.objectKeys(i).filter(l=>typeof i[i[l]]!="number"),a={};for(let l of s)a[l]=i[l];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},t.find=(i,s)=>{for(let a of i)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(K||(K={}));var Fo;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Fo||(Fo={}));var O=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ye=t=>{switch(typeof t){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(t)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(t)?O.array:t===null?O.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?O.promise:typeof Map<"u"&&t instanceof Map?O.map:typeof Set<"u"&&t instanceof Set?O.set:typeof Date<"u"&&t instanceof Date?O.date:O.object;default:return O.unknown}};var k=K.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),by=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),xe=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let l=n,c=0;for(;c<a.path.length;){let u=a.path[c];c===a.path.length-1?(l[u]=l[u]||{_errors:[]},l[u]._errors.push(r(a))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];r[s]=r[s]||[],r[s].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};xe.create=t=>new xe(t);var vy=(t,e)=>{let r;switch(t.code){case k.invalid_type:t.received===O.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,K.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${K.joinValues(t.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${K.joinValues(t.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${K.joinValues(t.options)}, received '${t.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:K.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case k.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case k.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=e.defaultError,K.assertNever(t)}return{message:r}},dt=vy;var tu=dt;function Dy(t){tu=t}function qr(){return tu}var An=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let l="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)l=u(a,{data:e,defaultError:l}).message;return{...i,path:s,message:l}},wy=[];function T(t,e){let r=qr(),n=An({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===dt?void 0:dt].filter(i=>!!i)});t.common.issues.push(n)}var ye=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return U;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let s=await i.key,a=await i.value;n.push({key:s,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return U;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}},U=Object.freeze({status:"aborted"}),Xt=t=>({status:"dirty",value:t}),Se=t=>({status:"valid",value:t}),Mi=t=>t.status==="aborted",ji=t=>t.status==="dirty",Ot=t=>t.status==="valid",zr=t=>typeof Promise<"u"&&t instanceof Promise;var R;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(R||(R={}));var Le=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ru=(t,e)=>{if(Ot(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new xe(t.common.issues);return this._error=r,this._error}}};function G(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,l)=>{let{message:c}=t;return a.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??n??l.defaultError}:a.code!=="invalid_type"?{message:l.defaultError}:{message:c??r??l.defaultError}},description:i}}var Z=class{get description(){return this._def.description}_getType(e){return Ye(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ye(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ye,ctx:{common:e.parent.common,data:e.data,parsedType:Ye(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(zr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ye(e)},i=this._parseSync({data:e,path:n.path,parent:n});return ru(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ye(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Ot(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Ot(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ye(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(zr(i)?i:Promise.resolve(i));return ru(n,s)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{let a=e(i),l=()=>s.addIssue({code:k.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(l(),!1)):a?!0:(l(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Ne({schema:this,typeName:F.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Be.create(this,this._def)}nullable(){return Qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return Mt.create(this,this._def)}or(e){return or.create([this,e],this._def)}and(e){return ar.create(this,e,this._def)}transform(e){return new Ne({...G(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new fr({...G(this._def),innerType:this,defaultValue:r,typeName:F.ZodDefault})}brand(){return new On({typeName:F.ZodBranded,type:this,...G(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new hr({...G(this._def),innerType:this,catchValue:r,typeName:F.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return In.create(this,e)}readonly(){return pr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Sy=/^c[^\s-]{8,}$/i,Cy=/^[0-9a-z]+$/,Ey=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_y=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,xy=/^[a-z0-9_-]{21}$/i,ky=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fy=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Py=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ty="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Po,Ay=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Oy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Iy=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ry=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,My=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,iu="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",By=new RegExp(`^${iu}$`);function su(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Ly(t){return new RegExp(`^${su(t)}$`)}function ou(t){let e=`${iu}T${su(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Ny(t,e){return!!((e==="v4"||!e)&&Ay.test(t)||(e==="v6"||!e)&&Iy.test(t))}function $y(t,e){if(!ky.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Uy(t,e){return!!((e==="v4"||!e)&&Oy.test(t)||(e==="v6"||!e)&&Ry.test(t))}var It=class t extends Z{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:O.string,received:s.parsedType}),U}let n=new ye,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,l=e.data.length<s.value;(a||l)&&(i=this._getOrReturnCtx(e,i),a?T(i,{code:k.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):l&&T(i,{code:k.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Py.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"email",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Po||(Po=new RegExp(Ty,"u")),Po.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"emoji",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")_y.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"uuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")xy.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"nanoid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Sy.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cuid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Cy.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cuid2",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Ey.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"ulid",code:k.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),T(i,{validation:"url",code:k.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"regex",code:k.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?ou(s).test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?By.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Ly(s).test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Fy.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"duration",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Ny(e.data,s.version)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"ip",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?$y(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"jwt",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Uy(e.data,s.version)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cidr",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?My.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"base64",code:k.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?jy.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"base64url",code:k.invalid_string,message:s.message}),n.dirty()):K.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:k.invalid_string,...R.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...R.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...R.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...R.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...R.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...R.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...R.errToObj(r)})}nonempty(e){return this.min(1,R.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};It.create=t=>new It({checks:[],typeName:F.ZodString,coerce:t?.coerce??!1,...G(t)});function qy(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(t.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return s%a/10**i}var er=class t extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:O.number,received:s.parsedType}),U}let n,i=new ye;for(let s of this._def.checks)s.kind==="int"?K.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?qy(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_finite,message:s.message}),i.dirty()):K.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,R.toString(r))}gt(e,r){return this.setLimit("min",e,!1,R.toString(r))}lte(e,r){return this.setLimit("max",e,!0,R.toString(r))}lt(e,r){return this.setLimit("max",e,!1,R.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:R.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&K.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};er.create=t=>new er({checks:[],typeName:F.ZodNumber,coerce:t?.coerce||!1,...G(t)});var tr=class t extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let n,i=new ye;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):K.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:O.bigint,received:r.parsedType}),U}gte(e,r){return this.setLimit("min",e,!0,R.toString(r))}gt(e,r){return this.setLimit("min",e,!1,R.toString(r))}lte(e,r){return this.setLimit("max",e,!0,R.toString(r))}lt(e,r){return this.setLimit("max",e,!1,R.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:R.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};tr.create=t=>new tr({checks:[],typeName:F.ZodBigInt,coerce:t?.coerce??!1,...G(t)});var rr=class extends Z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.boolean,received:n.parsedType}),U}return Se(e.data)}};rr.create=t=>new rr({typeName:F.ZodBoolean,coerce:t?.coerce||!1,...G(t)});var nr=class t extends Z{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_type,expected:O.date,received:s.parsedType}),U}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:k.invalid_date}),U}let n=new ye,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:k.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:k.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):K.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:R.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:R.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};nr.create=t=>new nr({checks:[],coerce:t?.coerce||!1,typeName:F.ZodDate,...G(t)});var Wr=class extends Z{_parse(e){if(this._getType(e)!==O.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.symbol,received:n.parsedType}),U}return Se(e.data)}};Wr.create=t=>new Wr({typeName:F.ZodSymbol,...G(t)});var ir=class extends Z{_parse(e){if(this._getType(e)!==O.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.undefined,received:n.parsedType}),U}return Se(e.data)}};ir.create=t=>new ir({typeName:F.ZodUndefined,...G(t)});var sr=class extends Z{_parse(e){if(this._getType(e)!==O.null){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.null,received:n.parsedType}),U}return Se(e.data)}};sr.create=t=>new sr({typeName:F.ZodNull,...G(t)});var Rt=class extends Z{constructor(){super(...arguments),this._any=!0}_parse(e){return Se(e.data)}};Rt.create=t=>new Rt({typeName:F.ZodAny,...G(t)});var ht=class extends Z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Se(e.data)}};ht.create=t=>new ht({typeName:F.ZodUnknown,...G(t)});var ze=class extends Z{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:k.invalid_type,expected:O.never,received:r.parsedType}),U}};ze.create=t=>new ze({typeName:F.ZodNever,...G(t)});var Gr=class extends Z{_parse(e){if(this._getType(e)!==O.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.void,received:n.parsedType}),U}return Se(e.data)}};Gr.create=t=>new Gr({typeName:F.ZodVoid,...G(t)});var pt=class t extends Z{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==O.array)return T(r,{code:k.invalid_type,expected:O.array,received:r.parsedType}),U;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,l=r.data.length<i.exactLength.value;(a||l)&&(T(r,{code:a?k.too_big:k.too_small,minimum:l?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(T(r,{code:k.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(T(r,{code:k.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,l)=>i.type._parseAsync(new Le(r,a,r.path,l)))).then(a=>ye.mergeArray(n,a));let s=[...r.data].map((a,l)=>i.type._parseSync(new Le(r,a,r.path,l)));return ye.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:R.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:R.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:R.toString(r)}})}nonempty(e){return this.min(1,e)}};pt.create=(t,e)=>new pt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...G(e)});function Vr(t){if(t instanceof ke){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Be.create(Vr(n))}return new ke({...t._def,shape:()=>e})}else return t instanceof pt?new pt({...t._def,type:Vr(t.element)}):t instanceof Be?Be.create(Vr(t.unwrap())):t instanceof Qe?Qe.create(Vr(t.unwrap())):t instanceof Je?Je.create(t.items.map(e=>Vr(e))):t}var ke=class t extends Z{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=K.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==O.object){let u=this._getOrReturnCtx(e);return T(u,{code:k.invalid_type,expected:O.object,received:u.parsedType}),U}let{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),l=[];if(!(this._def.catchall instanceof ze&&this._def.unknownKeys==="strip"))for(let u in i.data)a.includes(u)||l.push(u);let c=[];for(let u of a){let h=s[u],f=i.data[u];c.push({key:{status:"valid",value:u},value:h._parse(new Le(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof ze){let u=this._def.unknownKeys;if(u==="passthrough")for(let h of l)c.push({key:{status:"valid",value:h},value:{status:"valid",value:i.data[h]}});else if(u==="strict")l.length>0&&(T(i,{code:k.unrecognized_keys,keys:l}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let h of l){let f=i.data[h];c.push({key:{status:"valid",value:h},value:u._parse(new Le(i,f,i.path,h)),alwaysSet:h in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let h of c){let f=await h.key,d=await h.value;u.push({key:f,value:d,alwaysSet:h.alwaysSet})}return u}).then(u=>ye.mergeObjectSync(n,u)):ye.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return R.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:R.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:F.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of K.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of K.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Vr(this)}partial(e){let r={};for(let n of K.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of K.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Be;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return au(K.objectKeys(this.shape))}};ke.create=(t,e)=>new ke({shape:()=>t,unknownKeys:"strip",catchall:ze.create(),typeName:F.ZodObject,...G(e)});ke.strictCreate=(t,e)=>new ke({shape:()=>t,unknownKeys:"strict",catchall:ze.create(),typeName:F.ZodObject,...G(e)});ke.lazycreate=(t,e)=>new ke({shape:t,unknownKeys:"strip",catchall:ze.create(),typeName:F.ZodObject,...G(e)});var or=class extends Z{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(let l of s)if(l.result.status==="valid")return l.result;for(let l of s)if(l.result.status==="dirty")return r.common.issues.push(...l.ctx.common.issues),l.result;let a=s.map(l=>new xe(l.ctx.common.issues));return T(r,{code:k.invalid_union,unionErrors:a}),U}if(r.common.async)return Promise.all(n.map(async s=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let s,a=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},h=c._parseSync({data:r.data,path:r.path,parent:u});if(h.status==="valid")return h;h.status==="dirty"&&!s&&(s={result:h,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let l=a.map(c=>new xe(c));return T(r,{code:k.invalid_union,unionErrors:l}),U}}get options(){return this._def.options}};or.create=(t,e)=>new or({options:t,typeName:F.ZodUnion,...G(e)});var ft=t=>t instanceof lr?ft(t.schema):t instanceof Ne?ft(t.innerType()):t instanceof cr?[t.value]:t instanceof ur?t.options:t instanceof dr?K.objectValues(t.enum):t instanceof fr?ft(t._def.innerType):t instanceof ir?[void 0]:t instanceof sr?[null]:t instanceof Be?[void 0,...ft(t.unwrap())]:t instanceof Qe?[null,...ft(t.unwrap())]:t instanceof On||t instanceof pr?ft(t.unwrap()):t instanceof hr?ft(t._def.innerType):[],Bi=class t extends Z{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.object)return T(r,{code:k.invalid_type,expected:O.object,received:r.parsedType}),U;let n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),U)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let s of r){let a=ft(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let l of a){if(i.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);i.set(l,s)}}return new t({typeName:F.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...G(n)})}};function To(t,e){let r=Ye(t),n=Ye(e);if(t===e)return{valid:!0,data:t};if(r===O.object&&n===O.object){let i=K.objectKeys(e),s=K.objectKeys(t).filter(l=>i.indexOf(l)!==-1),a={...t,...e};for(let l of s){let c=To(t[l],e[l]);if(!c.valid)return{valid:!1};a[l]=c.data}return{valid:!0,data:a}}else if(r===O.array&&n===O.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<t.length;s++){let a=t[s],l=e[s],c=To(a,l);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===O.date&&n===O.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ar=class extends Z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(s,a)=>{if(Mi(s)||Mi(a))return U;let l=To(s.value,a.value);return l.valid?((ji(s)||ji(a))&&r.dirty(),{status:r.value,value:l.data}):(T(n,{code:k.invalid_intersection_types}),U)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};ar.create=(t,e,r)=>new ar({left:t,right:e,typeName:F.ZodIntersection,...G(r)});var Je=class t extends Z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.array)return T(n,{code:k.invalid_type,expected:O.array,received:n.parsedType}),U;if(n.data.length<this._def.items.length)return T(n,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((a,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new Le(n,a,n.path,l)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>ye.mergeArray(r,a)):ye.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Je.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Je({items:t,typeName:F.ZodTuple,rest:null,...G(e)})};var Li=class t extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.object)return T(n,{code:k.invalid_type,expected:O.object,received:n.parsedType}),U;let i=[],s=this._def.keyType,a=this._def.valueType;for(let l in n.data)i.push({key:s._parse(new Le(n,l,n.path,l)),value:a._parse(new Le(n,n.data[l],n.path,l)),alwaysSet:l in n.data});return n.common.async?ye.mergeObjectAsync(r,i):ye.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Z?new t({keyType:e,valueType:r,typeName:F.ZodRecord,...G(n)}):new t({keyType:It.create(),valueType:e,typeName:F.ZodRecord,...G(r)})}},Zr=class extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.map)return T(n,{code:k.invalid_type,expected:O.map,received:n.parsedType}),U;let i=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([l,c],u)=>({key:i._parse(new Le(n,l,n.path,[u,"key"])),value:s._parse(new Le(n,c,n.path,[u,"value"]))}));if(n.common.async){let l=new Map;return Promise.resolve().then(async()=>{for(let c of a){let u=await c.key,h=await c.value;if(u.status==="aborted"||h.status==="aborted")return U;(u.status==="dirty"||h.status==="dirty")&&r.dirty(),l.set(u.value,h.value)}return{status:r.value,value:l}})}else{let l=new Map;for(let c of a){let u=c.key,h=c.value;if(u.status==="aborted"||h.status==="aborted")return U;(u.status==="dirty"||h.status==="dirty")&&r.dirty(),l.set(u.value,h.value)}return{status:r.value,value:l}}}};Zr.create=(t,e,r)=>new Zr({valueType:e,keyType:t,typeName:F.ZodMap,...G(r)});var Kr=class t extends Z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.set)return T(n,{code:k.invalid_type,expected:O.set,received:n.parsedType}),U;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(T(n,{code:k.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(T(n,{code:k.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let s=this._def.valueType;function a(c){let u=new Set;for(let h of c){if(h.status==="aborted")return U;h.status==="dirty"&&r.dirty(),u.add(h.value)}return{status:r.value,value:u}}let l=[...n.data.values()].map((c,u)=>s._parse(new Le(n,c,n.path,u)));return n.common.async?Promise.all(l).then(c=>a(c)):a(l)}min(e,r){return new t({...this._def,minSize:{value:e,message:R.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:R.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Kr.create=(t,e)=>new Kr({valueType:t,minSize:null,maxSize:null,typeName:F.ZodSet,...G(e)});var Ni=class t extends Z{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.function)return T(r,{code:k.invalid_type,expected:O.function,received:r.parsedType}),U;function n(l,c){return An({data:l,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qr(),dt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function i(l,c){return An({data:l,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qr(),dt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Mt){let l=this;return Se(async function(...c){let u=new xe([]),h=await l._def.args.parseAsync(c,s).catch(p=>{throw u.addIssue(n(c,p)),u}),f=await Reflect.apply(a,this,h);return await l._def.returns._def.type.parseAsync(f,s).catch(p=>{throw u.addIssue(i(f,p)),u})})}else{let l=this;return Se(function(...c){let u=l._def.args.safeParse(c,s);if(!u.success)throw new xe([n(c,u.error)]);let h=Reflect.apply(a,this,u.data),f=l._def.returns.safeParse(h,s);if(!f.success)throw new xe([i(h,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Je.create(e).rest(ht.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Je.create([]).rest(ht.create()),returns:r||ht.create(),typeName:F.ZodFunction,...G(n)})}},lr=class extends Z{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};lr.create=(t,e)=>new lr({getter:t,typeName:F.ZodLazy,...G(e)});var cr=class extends Z{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:e.data}}get value(){return this._def.value}};cr.create=(t,e)=>new cr({value:t,typeName:F.ZodLiteral,...G(e)});function au(t,e){return new ur({values:t,typeName:F.ZodEnum,...G(e)})}var ur=class t extends Z{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:K.joinValues(n),received:r.parsedType,code:k.invalid_type}),U}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:k.invalid_enum_value,options:n}),U}return Se(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};ur.create=au;var dr=class extends Z{_parse(e){let r=K.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==O.string&&n.parsedType!==O.number){let i=K.objectValues(r);return T(n,{expected:K.joinValues(i),received:n.parsedType,code:k.invalid_type}),U}if(this._cache||(this._cache=new Set(K.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=K.objectValues(r);return T(n,{received:n.data,code:k.invalid_enum_value,options:i}),U}return Se(e.data)}get enum(){return this._def.values}};dr.create=(t,e)=>new dr({values:t,typeName:F.ZodNativeEnum,...G(e)});var Mt=class extends Z{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.promise&&r.common.async===!1)return T(r,{code:k.invalid_type,expected:O.promise,received:r.parsedType}),U;let n=r.parsedType===O.promise?r.data:Promise.resolve(r.data);return Se(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Mt.create=(t,e)=>new Mt({type:t,typeName:F.ZodPromise,...G(e)});var Ne=class extends Z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:a=>{T(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async l=>{if(r.value==="aborted")return U;let c=await this._def.schema._parseAsync({data:l,path:n.path,parent:n});return c.status==="aborted"?U:c.status==="dirty"?Xt(c.value):r.value==="dirty"?Xt(c.value):c});{if(r.value==="aborted")return U;let l=this._def.schema._parseSync({data:a,path:n.path,parent:n});return l.status==="aborted"?U:l.status==="dirty"?Xt(l.value):r.value==="dirty"?Xt(l.value):l}}if(i.type==="refinement"){let a=l=>{let c=i.refinement(l,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(n.common.async===!1){let l=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return l.status==="aborted"?U:(l.status==="dirty"&&r.dirty(),a(l.value),{status:r.value,value:l.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(l=>l.status==="aborted"?U:(l.status==="dirty"&&r.dirty(),a(l.value).then(()=>({status:r.value,value:l.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ot(a))return U;let l=i.transform(a.value,s);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:l}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Ot(a)?Promise.resolve(i.transform(a.value,s)).then(l=>({status:r.value,value:l})):U);K.assertNever(i)}};Ne.create=(t,e,r)=>new Ne({schema:t,typeName:F.ZodEffects,effect:e,...G(r)});Ne.createWithPreprocess=(t,e,r)=>new Ne({schema:e,effect:{type:"preprocess",transform:t},typeName:F.ZodEffects,...G(r)});var Be=class extends Z{_parse(e){return this._getType(e)===O.undefined?Se(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Be.create=(t,e)=>new Be({innerType:t,typeName:F.ZodOptional,...G(e)});var Qe=class extends Z{_parse(e){return this._getType(e)===O.null?Se(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Qe.create=(t,e)=>new Qe({innerType:t,typeName:F.ZodNullable,...G(e)});var fr=class extends Z{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===O.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};fr.create=(t,e)=>new fr({innerType:t,typeName:F.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...G(e)});var hr=class extends Z{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return zr(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xe(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new xe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};hr.create=(t,e)=>new hr({innerType:t,typeName:F.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...G(e)});var Hr=class extends Z{_parse(e){if(this._getType(e)!==O.nan){let n=this._getOrReturnCtx(e);return T(n,{code:k.invalid_type,expected:O.nan,received:n.parsedType}),U}return{status:"valid",value:e.data}}};Hr.create=t=>new Hr({typeName:F.ZodNaN,...G(t)});var zy=Symbol("zod_brand"),On=class extends Z{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},In=class t extends Z{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?U:s.status==="dirty"?(r.dirty(),Xt(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?U:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:F.ZodPipeline})}},pr=class extends Z{_parse(e){let r=this._def.innerType._parse(e),n=i=>(Ot(i)&&(i.value=Object.freeze(i.value)),i);return zr(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};pr.create=(t,e)=>new pr({innerType:t,typeName:F.ZodReadonly,...G(e)});function nu(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function lu(t,e={},r){return t?Rt.create().superRefine((n,i)=>{let s=t(n);if(s instanceof Promise)return s.then(a=>{if(!a){let l=nu(e,n),c=l.fatal??r??!0;i.addIssue({code:"custom",...l,fatal:c})}});if(!s){let a=nu(e,n),l=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:l})}}):Rt.create()}var Vy={object:ke.lazycreate},F;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(F||(F={}));var Wy=(t,e={message:`Input not instance of ${t.name}`})=>lu(r=>r instanceof t,e),cu=It.create,uu=er.create,Gy=Hr.create,Zy=tr.create,du=rr.create,Ky=nr.create,Hy=Wr.create,Yy=ir.create,Jy=sr.create,Qy=Rt.create,Xy=ht.create,e0=ze.create,t0=Gr.create,r0=pt.create,n0=ke.create,i0=ke.strictCreate,s0=or.create,o0=Bi.create,a0=ar.create,l0=Je.create,c0=Li.create,u0=Zr.create,d0=Kr.create,f0=Ni.create,h0=lr.create,p0=cr.create,m0=ur.create,g0=dr.create,y0=Mt.create,b0=Ne.create,v0=Be.create,D0=Qe.create,w0=Ne.createWithPreprocess,S0=In.create,C0=()=>cu().optional(),E0=()=>uu().optional(),_0=()=>du().optional(),x0={string:(t=>It.create({...t,coerce:!0})),number:(t=>er.create({...t,coerce:!0})),boolean:(t=>rr.create({...t,coerce:!0})),bigint:(t=>tr.create({...t,coerce:!0})),date:(t=>nr.create({...t,coerce:!0}))};var k0=U;var Yn=je(require("process"),1),I=je(Vu(),1),at=je(of(),1);var lf=Symbol("Let zodToJsonSchema decide on which parser to use");var af={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},cf=t=>typeof t=="string"?{...af,name:t}:{...af,...t};var uf=t=>{let e=cf(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ha(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function H(t,e,r,n,i){t[e]=r,ha(t,e,n,i)}var as=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function ie(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?as(e,t.currentPath):e.join("/")}}function df(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==F.ZodAny&&(r.items=z(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&H(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&H(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(H(r,"minItems",t.exactLength.value,t.exactLength.message,e),H(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function ff(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?H(r,"minimum",n.value,n.message,e):H(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),H(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?H(r,"maximum",n.value,n.message,e):H(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),H(r,"maximum",n.value,n.message,e));break;case"multipleOf":H(r,"multipleOf",n.value,n.message,e);break}return r}function hf(){return{type:"boolean"}}function ls(t,e){return z(t.type._def,e)}var pf=(t,e)=>z(t.innerType._def,e);function pa(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,s)=>pa(t,e,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Av(t,e)}}var Av=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":H(r,"minimum",n.value,n.message,e);break;case"max":H(r,"maximum",n.value,n.message,e);break}return r};function mf(t,e){return{...z(t.innerType._def,e),default:t.defaultValue()}}function gf(t,e){return e.effectStrategy==="input"?z(t.schema._def,e):ie(e)}function yf(t){return{type:"string",enum:Array.from(t.values)}}var Ov=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function bf(t,e){let r=[z(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),z(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(s=>{if(Ov(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:l,...c}=s;a=c}else n=void 0;i.push(a)}}),i.length?{allOf:i,...n}:void 0}function vf(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var ma,We={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ma===void 0&&(ma=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ma),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function cs(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":H(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":H(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ge(r,"email",n.message,e);break;case"format:idn-email":Ge(r,"idn-email",n.message,e);break;case"pattern:zod":_e(r,We.email,n.message,e);break}break;case"url":Ge(r,"uri",n.message,e);break;case"uuid":Ge(r,"uuid",n.message,e);break;case"regex":_e(r,n.regex,n.message,e);break;case"cuid":_e(r,We.cuid,n.message,e);break;case"cuid2":_e(r,We.cuid2,n.message,e);break;case"startsWith":_e(r,RegExp(`^${ga(n.value,e)}`),n.message,e);break;case"endsWith":_e(r,RegExp(`${ga(n.value,e)}$`),n.message,e);break;case"datetime":Ge(r,"date-time",n.message,e);break;case"date":Ge(r,"date",n.message,e);break;case"time":Ge(r,"time",n.message,e);break;case"duration":Ge(r,"duration",n.message,e);break;case"length":H(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),H(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{_e(r,RegExp(ga(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Ge(r,"ipv4",n.message,e),n.version!=="v4"&&Ge(r,"ipv6",n.message,e);break}case"base64url":_e(r,We.base64url,n.message,e);break;case"jwt":_e(r,We.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&_e(r,We.ipv4Cidr,n.message,e),n.version!=="v4"&&_e(r,We.ipv6Cidr,n.message,e);break}case"emoji":_e(r,We.emoji(),n.message,e);break;case"ulid":{_e(r,We.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ge(r,"binary",n.message,e);break}case"contentEncoding:base64":{H(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{_e(r,We.base64,n.message,e);break}}break}case"nanoid":_e(r,We.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ga(t,e){return e.patternStrategy==="escape"?Rv(t):t}var Iv=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Rv(t){let e="";for(let r=0;r<t.length;r++)Iv.has(t[r])||(e+="\\"),e+=t[r];return e}function Ge(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):H(t,"format",e,r,n)}function _e(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Df(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):H(t,"pattern",Df(e,n),r,n)}function Df(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,i="",s=!1,a=!1,l=!1;for(let c=0;c<n.length;c++){if(s){i+=n[c],s=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){l?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),l=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],l=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
138
138
  ]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
139
139
  ]))`;continue}}if(r.s&&n[c]==="."){i+=a?`${n[c]}\r
140
140
  `:`[${n[c]}\r
141
- ]`;continue}i+=n[c],n[c]==="\\"?s=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function us(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===F.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,i)=>({...n,[i]:z(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??ie(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:z(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===F.ZodString&&t.keyType._def.checks?.length){let{type:n,...i}=cs(t.keyType._def,e);return{...r,propertyNames:i}}else{if(t.keyType?._def.typeName===F.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===F.ZodBranded&&t.keyType._def.type._def.typeName===F.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...i}=ls(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function Df(t,e){if(e.mapStrategy==="record")return us(t,e);let r=z(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ie(e),n=z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ie(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function wf(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),i=Array.from(new Set(n.map(s=>typeof s)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function Sf(t){return t.target==="openAi"?void 0:{not:ie({...t,currentPath:[...t.currentPath,"not"]})}}function Cf(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Wn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function _f(t,e){if(e.target==="openApi3")return Ef(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Wn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,s)=>{let a=Wn[s._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...i,a];case"bigint":return[...i,"integer"];case"object":if(s._def.value===null)return[...i,"null"];default:return i}},[]);if(n.length===r.length){let i=n.filter((s,a,l)=>l.indexOf(s)===a);return{type:i.length>1?i:i[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(s=>!n.includes(s))],[])};return Ef(t,e)}var Ef=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>z(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function xf(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Wn[t.innerType._def.typeName],nullable:!0}:{type:[Wn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=z(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function kf(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",fa(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?H(r,"minimum",n.value,n.message,e):H(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),H(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?H(r,"maximum",n.value,n.message,e):H(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),H(r,"maximum",n.value,n.message,e));break;case"multipleOf":H(r,"multipleOf",n.value,n.message,e);break}return r}function Ff(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},i=[],s=t.shape();for(let l in s){let c=s[l];if(c===void 0||c._def===void 0)continue;let u=Mv(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let h=z(c._def,{...e,currentPath:[...e.currentPath,"properties",l],propertyPath:[...e.currentPath,"properties",l]});h!==void 0&&(n.properties[l]=h,u||i.push(l))}i.length&&(n.required=i);let a=Rv(t,e);return a!==void 0&&(n.additionalProperties=a),n}function Rv(t,e){if(t.catchall._def.typeName!=="ZodNever")return z(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Mv(t){try{return t.isOptional()}catch{return!0}}var Pf=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return z(t.innerType._def,e);let r=z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ie(e)},r]}:ie(e)};var Tf=(t,e)=>{if(e.pipeStrategy==="input")return z(t.in._def,e);if(e.pipeStrategy==="output")return z(t.out._def,e);let r=z(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=z(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function Af(t,e){return z(t.type._def,e)}function Of(t,e){let n={type:"array",uniqueItems:!0,items:z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&H(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&H(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function If(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:z(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Rf(t){return{not:ie(t)}}function Mf(t){return ie(t)}var jf=(t,e)=>z(t.innerType._def,e);var Bf=(t,e,r)=>{switch(e){case F.ZodString:return cs(t,r);case F.ZodNumber:return kf(t,r);case F.ZodObject:return Ff(t,r);case F.ZodBigInt:return df(t,r);case F.ZodBoolean:return ff();case F.ZodDate:return ha(t,r);case F.ZodUndefined:return Rf(r);case F.ZodNull:return Cf(r);case F.ZodArray:return uf(t,r);case F.ZodUnion:case F.ZodDiscriminatedUnion:return _f(t,r);case F.ZodIntersection:return yf(t,r);case F.ZodTuple:return If(t,r);case F.ZodRecord:return us(t,r);case F.ZodLiteral:return bf(t,r);case F.ZodEnum:return gf(t);case F.ZodNativeEnum:return wf(t);case F.ZodNullable:return xf(t,r);case F.ZodOptional:return Pf(t,r);case F.ZodMap:return Df(t,r);case F.ZodSet:return Of(t,r);case F.ZodLazy:return()=>t.getter()._def;case F.ZodPromise:return Af(t,r);case F.ZodNaN:case F.ZodNever:return Sf(r);case F.ZodEffects:return mf(t,r);case F.ZodAny:return ie(r);case F.ZodUnknown:return Mf(r);case F.ZodDefault:return pf(t,r);case F.ZodBranded:return ls(t,r);case F.ZodReadonly:return jf(t,r);case F.ZodCatch:return hf(t,r);case F.ZodPipeline:return Tf(t,r);case F.ZodFunction:case F.ZodVoid:case F.ZodSymbol:return;default:return(n=>{})(e)}};function z(t,e,r=!1){let n=e.seen.get(t);if(e.override){let l=e.override?.(t,e,n,r);if(l!==af)return l}if(n&&!r){let l=jv(n,e);if(l!==void 0)return l}let i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);let s=Bf(t,t.typeName,e),a=typeof s=="function"?z(s(),e):s;if(a&&Bv(t,e,a),e.postProcess){let l=e.postProcess(a,t,e);return i.jsonSchema=a,l}return i.jsonSchema=a,a}var jv=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:as(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ie(e)):e.$refStrategy==="seen"?ie(e):void 0}},Bv=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ds=(t,e)=>{let r=cf(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,h])=>({...c,[u]:z(h._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ie(r)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=z(t._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??ie(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(s.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let l=i===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:s}};return r.target==="jsonSchema7"?l.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(l.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in l||"oneOf"in l||"allOf"in l||"type"in l&&Array.isArray(l.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),l};function Lv(t){return typeof t=="object"&&t!==null&&typeof t.get=="function"&&typeof t.subscribe=="function"}var Ut=class{subscribeWithCleaner(e,r){let n=this.subscribe(r);e.register(n)}subscribeOnce(e){let r=this.subscribe(n=>{r(),e(n)});return r}subscribeOnceWithCleaner(e,r){let n=this.subscribeOnce(r);e.register(n)}derive(e,r=(n,i)=>n===i){if(Lv(this))return Ge.deriveFrom([this],e);let n=this;if(n.get!==void 0){if(n.get()===Ge.NOT_AVAILABLE)return Ge.createWithoutInitialValue(a=>n.subscribe(l=>{wt(l)&&a(e(l))}));let s=n;return Ge.create(e(s.get()),a=>s.subscribe(l=>{a(e(l))}),r)}return Ge.createWithoutInitialValue(i=>this.subscribe(s=>{wt(s)&&i(e(s))}),r)}},Jn=class t extends Ut{constructor(){super(),this.subscribers=new Set,this.onSubscribed=null,this.onUnsubscribed=null}emit(e){queueMicrotask(()=>{for(let r of this.subscribers)r(e)})}static create(){let e=new t;return[e,n=>{e.emit(n)}]}subscribe(e){let r=this.subscribers.size;return this.subscribers.add(e),r===0&&this.subscribers.size===1&&this.onSubscribed?.(),()=>{let n=this.subscribers.size;this.subscribers.delete(e),n===1&&this.subscribers.size===0&&this.onUnsubscribed?.()}}batch({minIdleTimeMs:e=200,maxBatchTimeMs:r=1e3}){let[n,i]=t.create();return n.onSubscribed=()=>{let s=[],a=null,l=0,c=()=>{a=null,i(s),s=[]};n.onUnsubscribed=this.subscribe(u=>{if(s.push(u),a===null)l=Date.now(),a=setTimeout(c,Math.min(e,r));else{clearTimeout(a);let h=Date.now()-l;a=setTimeout(c,Math.min(e,Math.max(0,r-h)))}})},n}};function re(){let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}}var ql=Symbol.for("immer-nothing"),Zn=Symbol.for("immer-draftable"),X=Symbol.for("immer-state"),kh=process.env.NODE_ENV!=="production"?[function(t){return`The plugin for '${t}' has not been loaded into Immer. To enable the plugin, import and call \`enable${t}()\` when initializing your application.`},function(t){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${t}'`},"This object has been frozen and should not be mutated",function(t){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+t},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(t){return`'current' expects a draft, got: ${t}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(t){return`'original' expects a draft, got: ${t}`}]:[];function oe(t,...e){if(process.env.NODE_ENV!=="production"){let r=kh[t],n=typeof r=="function"?r.apply(null,e):r;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var Pr=Object.getPrototypeOf;function Tr(t){return!!t&&!!t[X]}function ot(t){return t?Fh(t)||Array.isArray(t)||!!t[Zn]||!!t.constructor?.[Zn]||pi(t)||mi(t):!1}var Nv=Object.prototype.constructor.toString();function Fh(t){if(!t||typeof t!="object")return!1;let e=Pr(t);if(e===null)return!0;let r=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===Nv}function yn(t,e){Ar(t)===0?Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)}):t.forEach((r,n)=>e(n,r,t))}function Ar(t){let e=t[X];return e?e.type_:Array.isArray(t)?1:pi(t)?2:mi(t)?3:0}function Qn(t,e){return Ar(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function ga(t,e){return Ar(t)===2?t.get(e):t[e]}function Ph(t,e,r){let n=Ar(t);n===2?t.set(e,r):n===3?t.add(r):t[e]=r}function $v(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function pi(t){return t instanceof Map}function mi(t){return t instanceof Set}function fe(t){return t.copy_||t.base_}function Ma(t,e){if(pi(t))return new Map(t);if(mi(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);let r=Fh(t);if(e===!0||e==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(t);delete n[X];let i=Reflect.ownKeys(n);for(let s=0;s<i.length;s++){let a=i[s],l=n[a];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[a]={configurable:!0,writable:!0,enumerable:l.enumerable,value:t[a]})}return Object.create(Pr(t),n)}else{let n=Pr(t);if(n!==null&&r)return{...t};let i=Object.create(n);return Object.assign(i,t)}}function zl(t,e=!1){return Hs(t)||Tr(t)||!ot(t)||(Ar(t)>1&&(t.set=t.add=t.clear=t.delete=Uv),Object.freeze(t),e&&Object.values(t).forEach(r=>zl(r,!0))),t}function Uv(){oe(2)}function Hs(t){return Object.isFrozen(t)}var ja={};function Or(t){let e=ja[t];return e||oe(0,t),e}function Th(t,e){ja[t]||(ja[t]=e)}var Xn;function xs(){return Xn}function qv(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Lf(t,e){e&&(Or("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function Ba(t){La(t),t.drafts_.forEach(zv),t.drafts_=null}function La(t){t===Xn&&(Xn=t.parent_)}function Nf(t){return Xn=qv(Xn,t)}function zv(t){let e=t[X];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function $f(t,e){e.unfinalizedDrafts_=e.drafts_.length;let r=e.drafts_[0];return t!==void 0&&t!==r?(r[X].modified_&&(Ba(e),oe(4)),ot(t)&&(t=ks(e,t),e.parent_||Fs(e,t)),e.patches_&&Or("Patches").generateReplacementPatches_(r[X].base_,t,e.patches_,e.inversePatches_)):t=ks(e,r,[]),Ba(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==ql?t:void 0}function ks(t,e,r){if(Hs(e))return e;let n=e[X];if(!n)return yn(e,(i,s)=>Uf(t,n,e,i,s,r)),e;if(n.scope_!==t)return e;if(!n.modified_)return Fs(t,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let i=n.copy_,s=i,a=!1;n.type_===3&&(s=new Set(i),i.clear(),a=!0),yn(s,(l,c)=>Uf(t,n,i,l,c,r,a)),Fs(t,i,!1),r&&t.patches_&&Or("Patches").generatePatches_(n,r,t.patches_,t.inversePatches_)}return n.copy_}function Uf(t,e,r,n,i,s,a){if(process.env.NODE_ENV!=="production"&&i===r&&oe(5),Tr(i)){let l=s&&e&&e.type_!==3&&!Qn(e.assigned_,n)?s.concat(n):void 0,c=ks(t,i,l);if(Ph(r,n,c),Tr(c))t.canAutoFreeze_=!1;else return}else a&&r.add(i);if(ot(i)&&!Hs(i)){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;ks(t,i),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Fs(t,i)}}function Fs(t,e,r=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&zl(e,r)}function Vv(t,e){let r=Array.isArray(t),n={type_:r?1:0,scope_:e?e.scope_:xs(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1},i=n,s=Vl;r&&(i=[n],s=ei);let{revoke:a,proxy:l}=Proxy.revocable(i,s);return n.draft_=l,n.revoke_=a,l}var Vl={get(t,e){if(e===X)return t;let r=fe(t);if(!Qn(r,e))return Wv(t,r,e);let n=r[e];return t.finalized_||!ot(n)?n:n===ya(t.base_,e)?(ba(t),t.copy_[e]=ti(n,t)):n},has(t,e){return e in fe(t)},ownKeys(t){return Reflect.ownKeys(fe(t))},set(t,e,r){let n=Ah(fe(t),e);if(n?.set)return n.set.call(t.draft_,r),!0;if(!t.modified_){let i=ya(fe(t),e),s=i?.[X];if(s&&s.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if($v(r,i)&&(r!==void 0||Qn(t.base_,e)))return!0;ba(t),Dt(t)}return t.copy_[e]===r&&(r!==void 0||e in t.copy_)||Number.isNaN(r)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=r,t.assigned_[e]=!0),!0},deleteProperty(t,e){return ya(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,ba(t),Dt(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){let r=fe(t),n=Reflect.getOwnPropertyDescriptor(r,e);return n&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:n.enumerable,value:r[e]}},defineProperty(){oe(11)},getPrototypeOf(t){return Pr(t.base_)},setPrototypeOf(){oe(12)}},ei={};yn(Vl,(t,e)=>{ei[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});ei.deleteProperty=function(t,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&oe(13),ei.set.call(this,t,e,void 0)};ei.set=function(t,e,r){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&oe(14),Vl.set.call(this,t[0],e,r,t[0])};function ya(t,e){let r=t[X];return(r?fe(r):t)[e]}function Wv(t,e,r){let n=Ah(e,r);return n?"value"in n?n.value:n.get?.call(t.draft_):void 0}function Ah(t,e){if(!(e in t))return;let r=Pr(t);for(;r;){let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=Pr(r)}}function Dt(t){t.modified_||(t.modified_=!0,t.parent_&&Dt(t.parent_))}function ba(t){t.copy_||(t.copy_=Ma(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var Gv=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,r,n)=>{if(typeof e=="function"&&typeof r!="function"){let s=r;r=e;let a=this;return function(c=s,...u){return a.produce(c,h=>r.call(this,h,...u))}}typeof r!="function"&&oe(6),n!==void 0&&typeof n!="function"&&oe(7);let i;if(ot(e)){let s=Nf(this),a=ti(e,void 0),l=!0;try{i=r(a),l=!1}finally{l?Ba(s):La(s)}return Lf(s,n),$f(i,s)}else if(!e||typeof e!="object"){if(i=r(e),i===void 0&&(i=e),i===ql&&(i=void 0),this.autoFreeze_&&zl(i,!0),n){let s=[],a=[];Or("Patches").generateReplacementPatches_(e,i,s,a),n(s,a)}return i}else oe(1,e)},this.produceWithPatches=(e,r)=>{if(typeof e=="function")return(a,...l)=>this.produceWithPatches(a,c=>e(c,...l));let n,i;return[this.produce(e,r,(a,l)=>{n=a,i=l}),n,i]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy)}createDraft(t){ot(t)||oe(8),Tr(t)&&(t=Zv(t));let e=Nf(this),r=ti(t,void 0);return r[X].isManual_=!0,La(e),r}finishDraft(t,e){let r=t&&t[X];(!r||!r.isManual_)&&oe(9);let{scope_:n}=r;return Lf(n,e),$f(void 0,n)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}applyPatches(t,e){let r;for(r=e.length-1;r>=0;r--){let i=e[r];if(i.path.length===0&&i.op==="replace"){t=i.value;break}}r>-1&&(e=e.slice(r+1));let n=Or("Patches").applyPatches_;return Tr(t)?n(t,e):this.produce(t,i=>n(i,e))}};function ti(t,e){let r=pi(t)?Or("MapSet").proxyMap_(t,e):mi(t)?Or("MapSet").proxySet_(t,e):Vv(t,e);return(e?e.scope_:xs()).drafts_.push(r),r}function Zv(t){return Tr(t)||oe(10,t),Oh(t)}function Oh(t){if(!ot(t)||Hs(t))return t;let e=t[X],r;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,r=Ma(t,e.scope_.immer_.useStrictShallowCopy_)}else r=Ma(t,!0);return yn(r,(n,i)=>{Ph(r,n,Oh(i))}),e&&(e.finalized_=!1),r}function Kv(){class t extends Map{constructor(c,u){super(),this[X]={type_:2,parent_:u,scope_:u?u.scope_:xs(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return fe(this[X]).size}has(c){return fe(this[X]).has(c)}set(c,u){let h=this[X];return a(h),(!fe(h).has(c)||fe(h).get(c)!==u)&&(r(h),Dt(h),h.assigned_.set(c,!0),h.copy_.set(c,u),h.assigned_.set(c,!0)),this}delete(c){if(!this.has(c))return!1;let u=this[X];return a(u),r(u),Dt(u),u.base_.has(c)?u.assigned_.set(c,!1):u.assigned_.delete(c),u.copy_.delete(c),!0}clear(){let c=this[X];a(c),fe(c).size&&(r(c),Dt(c),c.assigned_=new Map,yn(c.base_,u=>{c.assigned_.set(u,!1)}),c.copy_.clear())}forEach(c,u){let h=this[X];fe(h).forEach((f,d,p)=>{c.call(u,this.get(d),d,this)})}get(c){let u=this[X];a(u);let h=fe(u).get(c);if(u.finalized_||!ot(h)||h!==u.base_.get(c))return h;let f=ti(h,u);return r(u),u.copy_.set(c,f),f}keys(){return fe(this[X]).keys()}values(){let c=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{let u=c.next();return u.done?u:{done:!1,value:this.get(u.value)}}}}entries(){let c=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{let u=c.next();if(u.done)return u;let h=this.get(u.value);return{done:!1,value:[u.value,h]}}}}[Symbol.iterator](){return this.entries()}}function e(l,c){return new t(l,c)}function r(l){l.copy_||(l.assigned_=new Map,l.copy_=new Map(l.base_))}class n extends Set{constructor(c,u){super(),this[X]={type_:3,parent_:u,scope_:u?u.scope_:xs(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return fe(this[X]).size}has(c){let u=this[X];return a(u),u.copy_?!!(u.copy_.has(c)||u.drafts_.has(c)&&u.copy_.has(u.drafts_.get(c))):u.base_.has(c)}add(c){let u=this[X];return a(u),this.has(c)||(s(u),Dt(u),u.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let u=this[X];return a(u),s(u),Dt(u),u.copy_.delete(c)||(u.drafts_.has(c)?u.copy_.delete(u.drafts_.get(c)):!1)}clear(){let c=this[X];a(c),fe(c).size&&(s(c),Dt(c),c.copy_.clear())}values(){let c=this[X];return a(c),s(c),c.copy_.values()}entries(){let c=this[X];return a(c),s(c),c.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(c,u){let h=this.values(),f=h.next();for(;!f.done;)c.call(u,f.value,f.value,this),f=h.next()}}function i(l,c){return new n(l,c)}function s(l){l.copy_||(l.copy_=new Set,l.base_.forEach(c=>{if(ot(c)){let u=ti(c,l);l.drafts_.set(c,u),l.copy_.add(u)}else l.copy_.add(c)}))}function a(l){l.revoked_&&oe(3,JSON.stringify(fe(l)))}Th("MapSet",{proxyMap_:e,proxySet_:i})}function Hv(){process.env.NODE_ENV!=="production"&&kh.push('Sets cannot have "replace" patches.',function(d){return"Unsupported patch operation: "+d},function(d){return"Cannot apply patch, path doesn't resolve: "+d},"Patching reserved attributes like __proto__, prototype and constructor is not allowed");let e="replace",r="add",n="remove";function i(d,p,m,g){switch(d.type_){case 0:case 2:return a(d,p,m,g);case 1:return s(d,p,m,g);case 3:return l(d,p,m,g)}}function s(d,p,m,g){let{base_:y,assigned_:b}=d,D=d.copy_;D.length<y.length&&([y,D]=[D,y],[m,g]=[g,m]);for(let v=0;v<y.length;v++)if(b[v]&&D[v]!==y[v]){let S=p.concat([v]);m.push({op:e,path:S,value:f(D[v])}),g.push({op:e,path:S,value:f(y[v])})}for(let v=y.length;v<D.length;v++){let S=p.concat([v]);m.push({op:r,path:S,value:f(D[v])})}for(let v=D.length-1;y.length<=v;--v){let S=p.concat([v]);g.push({op:n,path:S})}}function a(d,p,m,g){let{base_:y,copy_:b}=d;yn(d.assigned_,(D,v)=>{let S=ga(y,D),C=ga(b,D),x=v?Qn(y,D)?e:r:n;if(S===C&&x===e)return;let _=p.concat(D);m.push(x===n?{op:x,path:_}:{op:x,path:_,value:C}),g.push(x===r?{op:n,path:_}:x===n?{op:r,path:_,value:f(S)}:{op:e,path:_,value:f(S)})})}function l(d,p,m,g){let{base_:y,copy_:b}=d,D=0;y.forEach(v=>{if(!b.has(v)){let S=p.concat([D]);m.push({op:n,path:S,value:v}),g.unshift({op:r,path:S,value:v})}D++}),D=0,b.forEach(v=>{if(!y.has(v)){let S=p.concat([D]);m.push({op:r,path:S,value:v}),g.unshift({op:n,path:S,value:v})}D++})}function c(d,p,m,g){m.push({op:e,path:[],value:p===ql?void 0:p}),g.push({op:e,path:[],value:d})}function u(d,p){return p.forEach(m=>{let{path:g,op:y}=m,b=d;for(let C=0;C<g.length-1;C++){let x=Ar(b),_=g[C];typeof _!="string"&&typeof _!="number"&&(_=""+_),(x===0||x===1)&&(_==="__proto__"||_==="constructor")&&oe(19),typeof b=="function"&&_==="prototype"&&oe(19),b=ga(b,_),typeof b!="object"&&oe(18,g.join("/"))}let D=Ar(b),v=h(m.value),S=g[g.length-1];switch(y){case e:switch(D){case 2:return b.set(S,v);case 3:oe(16);default:return b[S]=v}case r:switch(D){case 1:return S==="-"?b.push(v):b.splice(S,0,v);case 2:return b.set(S,v);case 3:return b.add(v);default:return b[S]=v}case n:switch(D){case 1:return b.splice(S,1);case 2:return b.delete(S);case 3:return b.delete(m.value);default:return delete b[S]}default:oe(17,y)}}),d}function h(d){if(!ot(d))return d;if(Array.isArray(d))return d.map(h);if(pi(d))return new Map(Array.from(d.entries()).map(([m,g])=>[m,h(g)]));if(mi(d))return new Set(Array.from(d).map(h));let p=Object.create(Pr(d));for(let m in d)p[m]=h(d[m]);return Qn(d,Zn)&&(p[Zn]=d[Zn]),p}function f(d){return Tr(d)?h(d):d}Th("Patches",{applyPatches_:u,generatePatches_:i,generateReplacementPatches_:c})}var Ie=new Gv;Ie.produce;var Yv=Ie.produceWithPatches.bind(Ie);Ie.setAutoFreeze.bind(Ie);Ie.setUseStrictShallowCopy.bind(Ie);var Na=Ie.applyPatches.bind(Ie);Ie.createDraft.bind(Ie);Ie.finishDraft.bind(Ie);Kv();Hv();function un(...t){return t.filter(e=>e!==void 0).reduce((e,r)=>e.concat(r),[])}function qf(t){return[{op:"replace",path:[],value:t}]}function Wl(t,e){let r=(n,i)=>{t(()=>[n,qf(n)],un(e?.(),i))};return r.withProducer=(n,i)=>{t(s=>{let[a,l]=Yv(s,n);if(wt(a))return[a,l];throw new Error("Cannot update value to NOT_AVAILABLE")},un(e?.(),i))},r.withUpdater=(n,i)=>{t(s=>{let a=n(s);return[a,qf(a)]},un(e?.(),i))},r.withPatchUpdater=(n,i)=>{t(n,un(e?.(),i))},r.withPatches=(n,i)=>{t(s=>[Na(s,n),n],un(e?.(),i))},r.withValueAndPatches=(n,i,s)=>{t(()=>[n,i],un(e?.(),s))},r}var Jv=(t,e)=>t===e,ri=class t extends Ut{static create(e,r=Jv){let n=new t(e,r),s=Wl((a,l)=>{n.update(a,l)});return[n,s]}static createReadonly(e){return t.create(e)[0]}constructor(e,r){super(),this.value=e,this.equalsPredicate=r,this.subscribers=new Set,this.queuedUpdaters=[],this.isEmitting=!1}get(){return this.value}pull(){return this.value}notifyFull(e,r,n){for(let{type:i,callback:s}of this.subscribers)i==="full"&&s(e,r,n)}notifyAll(e,r,n){for(let{type:i,callback:s}of this.subscribers)i==="regular"?s(e):s(e,r,n)}notifyAndUpdateIfChanged(e,r,n){this.equalsPredicate(this.value,e)?n.length>0&&this.notifyFull(e,r,n):(this.value=e,this.notifyAll(e,r,n))}isReplaceRoot(e){return e.path.length===0&&e.op==="replace"}update(e,r){if(this.queuedUpdaters.push([e,r]),!this.isEmitting){this.isEmitting=!0;try{for(;this.queuedUpdaters.length>0;){let n=this.value,i=[],s=[];for(;this.queuedUpdaters.length>0;){let[a,l]=this.queuedUpdaters.shift(),[c,u]=a(n);n=c;let h=u.findIndex(this.isReplaceRoot);h!==-1?i=u.slice(h):i.push(...u),l!==void 0&&s.push(...l)}this.notifyAndUpdateIfChanged(n,i,s)}}finally{this.isEmitting=!1}}}subscribe(e){let r={type:"regular",callback:e};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}}subscribeAndNow(e){let r=this.subscribe(e);return e(this.value),r}subscribeFull(e){let r={type:"full",callback:e};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}}async until(e){let r=this.get();if(e(r))return r;let{promise:n,resolve:i}=re(),s=this.subscribe(a=>{e(a)&&(i(a),s())});return await n}};function wt(t){return t!==Ge.NOT_AVAILABLE}var Ge=class t extends Ut{static{this.NOT_AVAILABLE=Symbol("notAvailable")}static create(e,r,n=(i,s)=>i===s){return new t(e,r,n)}static createWithoutInitialValue(e,r=(n,i)=>n===i){let n=(i,s)=>i===t.NOT_AVAILABLE||s===t.NOT_AVAILABLE?i===s:r(i,s);return new t(t.NOT_AVAILABLE,e,n)}static deriveFrom(e,r,n){let i;n!==void 0&&(i=(a,l)=>a===t.NOT_AVAILABLE||l===t.NOT_AVAILABLE?a===l:n(a,l));let s=()=>{let a=e.map(l=>l.get());return a.some(l=>l===t.NOT_AVAILABLE)?t.NOT_AVAILABLE:r(...a)};return new t(s(),a=>{let l=e.map(u=>u.subscribe(()=>{let h=s();wt(h)&&a(h)})),c=s();return wt(c)&&a(c),()=>{l.forEach(u=>u())}},i)}static asyncDeriveFrom(e,r,n,i){let s;i!==void 0&&(s=(c,u)=>c===t.NOT_AVAILABLE||u===t.NOT_AVAILABLE?c===u:i(c,u));let a=-1,l=-1;return new t(t.NOT_AVAILABLE,c=>{let u=()=>{l++;let f=l,d=r.map(p=>p.get());d.some(p=>p===t.NOT_AVAILABLE)||n(...d).then(p=>{if(wt(p))if(e==="eager")f>a&&(a=f,c(p));else{let m=e;throw new Error(`Unknown strategy: ${m}`)}})},h=r.map(f=>f.subscribe(()=>{u()}));return u(),()=>{h.forEach(f=>f())}},s)}constructor(e,r,n=(i,s)=>i===s){super(),this.subscribeUpstream=r,this.dataIsStale=!0,this.upstreamUnsubscribe=null,this.subscribersCount=0,this.isSubscribedToUpstream=!1,this.updateReceivedSynchronousCallbacks=new Set,[this.signal,this.setValue]=ri.create(e,n),[this.updateReceivedEvent,this.emitUpdateReceivedEvent]=Jn.create()}isStale(){return this.dataIsStale}subscribeToUpstream(){this.isSubscribedToUpstream=!0;let e=!0,r=!1,n=this.subscribeUpstream(Wl((i,s)=>{if(e){this.setValue.withPatchUpdater(i,s),this.dataIsStale=r,this.emitUpdateReceivedEvent();for(let a of this.updateReceivedSynchronousCallbacks)a()}}),i=>{e&&(Promise.reject(i),this.dataIsStale=!0,this.isSubscribedToUpstream=!1,this.upstreamUnsubscribe=null,e=!1)});this.upstreamUnsubscribe=()=>{e&&(e=!1,r=!0,n())}}unsubscribeFromUpstream(){this.isSubscribedToUpstream=!1,this.upstreamUnsubscribe!==null&&(this.upstreamUnsubscribe(),this.upstreamUnsubscribe=null,this.dataIsStale=!0)}get(){return this.signal.get()}async pull(){let{promise:e,resolve:r}=re();if(!this.isStale())r(this.get());else{let n=this.subscribe(()=>{});this.updateReceivedEvent.subscribeOnce(()=>{r(this.get())}),e.then(n)}return e}runOnNextFreshData(e){if(!this.isStale())e(this.get());else{let r=null,n=()=>{this.updateReceivedSynchronousCallbacks.delete(n),e(this.get()),r?.()};this.updateReceivedSynchronousCallbacks.add(n),r=this.subscribe(()=>{})}}async ensureAvailable(){return await this.pull(),this}subscribe(e){this.isSubscribedToUpstream||this.subscribeToUpstream(),this.subscribersCount++;let r=this.signal.subscribe(e),n=!1;return()=>{n||(r(),n=!0,this.subscribersCount--,this.subscribersCount===0&&this.isSubscribedToUpstream&&this.unsubscribeFromUpstream())}}subscribeFull(e){this.isSubscribedToUpstream||this.subscribeToUpstream(),this.subscribersCount++;let r=this.signal.subscribeFull(e),n=!1;return()=>{n||(r(),n=!0,this.subscribersCount--,this.subscribersCount===0&&this.isSubscribedToUpstream&&this.unsubscribeFromUpstream())}}passiveSubscribe(e){return this.signal.subscribe(e)}passiveSubscribeFull(e){return this.signal.subscribeFull(e)}async until(e){let r=this.get();if(wt(r)&&e(r))return r;let{promise:n,resolve:i}=re(),s=this.subscribe(a=>{wt(a)&&e(a)&&(i(a),s())});return await n}},Qv=[41343,52993,16141,39414,22931],Gn=Symbol(),Ct=class t extends Ut{static create(){let e=new t;return[e,n=>{e.emit(n)}]}constructor(){super(),this.subscriber=null,this.queued=[],this.isNotifying=!1}emit(e){this.queued.length===0&&this.queued.at(-1)!==Gn&&this.queued.push(Gn),this.queued.push(e),this.isNotifying||this.notifier()}async notifier(){for(this.isNotifying=!0;this.subscriber!==null&&this.queued.length>0;){let e=this.queued.shift();e===Gn?await Promise.resolve():this.subscriber(e)}this.isNotifying=!1}subscribe(e){if(this.subscriber!==null)throw new Error("Cannot have more than one subscriber");return this.subscriber=e,!this.isNotifying&&this.queued.length>0&&(this.queued=[Gn,...this.queued.filter(r=>r!==Gn)],this.notifier()),()=>{this.subscriber=null}}flow(){let[e,r]=Jn.create();return this.subscribe(r),e}},$a=class extends Ut{constructor(){super(...arguments),this.canceled=!1,this.listeners=new Set}subscribe(e){if(this.canceled){let r=!1;return Promise.resolve().then(()=>{r||e()}),()=>{r=!0}}return this.listeners.add(e),()=>{this.listeners.delete(e)}}cancel(){if(this.canceled)throw new Error("Already canceled");this.canceled=!0;for(let e of this.listeners)e()}isCanceled(){return this.canceled}},Ps=class{constructor(){this.eagerCleaned=!1,this.disposed=!1,this.cleanups=[]}register(e){if(this.eagerCleaned)throw new Error("Cannot register a cleanup after eagerClean() was called.");if(this.disposed)throw new Error("Cannot register a cleanup after the Cleaner was disposed.");this.cleanups.push(e)}runCleanersInternal(){for(let e of this.cleanups)e();this.cleanups.length=0}[Symbol.dispose](){if(!this.eagerCleaned){if(this.disposed)throw new Error("Cannot dispose a Cleaner that was already disposed.");this.runCleanersInternal()}}eagerClean(){if(this.eagerCleaned)throw new Error("Cannot call eagerClean() twice.");if(this.disposed)throw new Error("Cannot call eagerClean() after the Cleaner was disposed.");this.eagerCleaned=!0,this.runCleanersInternal()}};function A(t=0){let e=new Error().stack;return e?e.split(`
141
+ ]`;continue}i+=n[c],n[c]==="\\"?s=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function us(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===F.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,i)=>({...n,[i]:z(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??ie(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:z(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===F.ZodString&&t.keyType._def.checks?.length){let{type:n,...i}=cs(t.keyType._def,e);return{...r,propertyNames:i}}else{if(t.keyType?._def.typeName===F.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===F.ZodBranded&&t.keyType._def.type._def.typeName===F.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...i}=ls(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function wf(t,e){if(e.mapStrategy==="record")return us(t,e);let r=z(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ie(e),n=z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ie(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Sf(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),i=Array.from(new Set(n.map(s=>typeof s)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function Cf(t){return t.target==="openAi"?void 0:{not:ie({...t,currentPath:[...t.currentPath,"not"]})}}function Ef(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Wn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function xf(t,e){if(e.target==="openApi3")return _f(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Wn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,s)=>{let a=Wn[s._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,s)=>{let a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...i,a];case"bigint":return[...i,"integer"];case"object":if(s._def.value===null)return[...i,"null"];default:return i}},[]);if(n.length===r.length){let i=n.filter((s,a,l)=>l.indexOf(s)===a);return{type:i.length>1?i:i[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(s=>!n.includes(s))],[])};return _f(t,e)}var _f=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>z(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function kf(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Wn[t.innerType._def.typeName],nullable:!0}:{type:[Wn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=z(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Ff(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",ha(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?H(r,"minimum",n.value,n.message,e):H(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),H(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?H(r,"maximum",n.value,n.message,e):H(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),H(r,"maximum",n.value,n.message,e));break;case"multipleOf":H(r,"multipleOf",n.value,n.message,e);break}return r}function Pf(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},i=[],s=t.shape();for(let l in s){let c=s[l];if(c===void 0||c._def===void 0)continue;let u=jv(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let h=z(c._def,{...e,currentPath:[...e.currentPath,"properties",l],propertyPath:[...e.currentPath,"properties",l]});h!==void 0&&(n.properties[l]=h,u||i.push(l))}i.length&&(n.required=i);let a=Mv(t,e);return a!==void 0&&(n.additionalProperties=a),n}function Mv(t,e){if(t.catchall._def.typeName!=="ZodNever")return z(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function jv(t){try{return t.isOptional()}catch{return!0}}var Tf=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return z(t.innerType._def,e);let r=z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ie(e)},r]}:ie(e)};var Af=(t,e)=>{if(e.pipeStrategy==="input")return z(t.in._def,e);if(e.pipeStrategy==="output")return z(t.out._def,e);let r=z(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=z(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function Of(t,e){return z(t.type._def,e)}function If(t,e){let n={type:"array",uniqueItems:!0,items:z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&H(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&H(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Rf(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:z(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Mf(t){return{not:ie(t)}}function jf(t){return ie(t)}var Bf=(t,e)=>z(t.innerType._def,e);var Lf=(t,e,r)=>{switch(e){case F.ZodString:return cs(t,r);case F.ZodNumber:return Ff(t,r);case F.ZodObject:return Pf(t,r);case F.ZodBigInt:return ff(t,r);case F.ZodBoolean:return hf();case F.ZodDate:return pa(t,r);case F.ZodUndefined:return Mf(r);case F.ZodNull:return Ef(r);case F.ZodArray:return df(t,r);case F.ZodUnion:case F.ZodDiscriminatedUnion:return xf(t,r);case F.ZodIntersection:return bf(t,r);case F.ZodTuple:return Rf(t,r);case F.ZodRecord:return us(t,r);case F.ZodLiteral:return vf(t,r);case F.ZodEnum:return yf(t);case F.ZodNativeEnum:return Sf(t);case F.ZodNullable:return kf(t,r);case F.ZodOptional:return Tf(t,r);case F.ZodMap:return wf(t,r);case F.ZodSet:return If(t,r);case F.ZodLazy:return()=>t.getter()._def;case F.ZodPromise:return Of(t,r);case F.ZodNaN:case F.ZodNever:return Cf(r);case F.ZodEffects:return gf(t,r);case F.ZodAny:return ie(r);case F.ZodUnknown:return jf(r);case F.ZodDefault:return mf(t,r);case F.ZodBranded:return ls(t,r);case F.ZodReadonly:return Bf(t,r);case F.ZodCatch:return pf(t,r);case F.ZodPipeline:return Af(t,r);case F.ZodFunction:case F.ZodVoid:case F.ZodSymbol:return;default:return(n=>{})(e)}};function z(t,e,r=!1){let n=e.seen.get(t);if(e.override){let l=e.override?.(t,e,n,r);if(l!==lf)return l}if(n&&!r){let l=Bv(n,e);if(l!==void 0)return l}let i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);let s=Lf(t,t.typeName,e),a=typeof s=="function"?z(s(),e):s;if(a&&Lv(t,e,a),e.postProcess){let l=e.postProcess(a,t,e);return i.jsonSchema=a,l}return i.jsonSchema=a,a}var Bv=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:as(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ie(e)):e.$refStrategy==="seen"?ie(e):void 0}},Lv=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ds=(t,e)=>{let r=uf(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,h])=>({...c,[u]:z(h._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ie(r)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=z(t._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??ie(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(s.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let l=i===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:s}};return r.target==="jsonSchema7"?l.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(l.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in l||"oneOf"in l||"allOf"in l||"type"in l&&Array.isArray(l.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),l};function Nv(t){return typeof t=="object"&&t!==null&&typeof t.get=="function"&&typeof t.subscribe=="function"}var Ut=class{subscribeWithCleaner(e,r){let n=this.subscribe(r);e.register(n)}subscribeOnce(e){let r=this.subscribe(n=>{r(),e(n)});return r}subscribeOnceWithCleaner(e,r){let n=this.subscribeOnce(r);e.register(n)}derive(e,r=(n,i)=>n===i){if(Nv(this))return Ze.deriveFrom([this],e);let n=this;if(n.get!==void 0){if(n.get()===Ze.NOT_AVAILABLE)return Ze.createWithoutInitialValue(a=>n.subscribe(l=>{St(l)&&a(e(l))}));let s=n;return Ze.create(e(s.get()),a=>s.subscribe(l=>{a(e(l))}),r)}return Ze.createWithoutInitialValue(i=>this.subscribe(s=>{St(s)&&i(e(s))}),r)}},Jn=class t extends Ut{constructor(){super(),this.subscribers=new Set,this.onSubscribed=null,this.onUnsubscribed=null}emit(e){queueMicrotask(()=>{for(let r of this.subscribers)r(e)})}static create(){let e=new t;return[e,n=>{e.emit(n)}]}subscribe(e){let r=this.subscribers.size;return this.subscribers.add(e),r===0&&this.subscribers.size===1&&this.onSubscribed?.(),()=>{let n=this.subscribers.size;this.subscribers.delete(e),n===1&&this.subscribers.size===0&&this.onUnsubscribed?.()}}batch({minIdleTimeMs:e=200,maxBatchTimeMs:r=1e3}){let[n,i]=t.create();return n.onSubscribed=()=>{let s=[],a=null,l=0,c=()=>{a=null,i(s),s=[]};n.onUnsubscribed=this.subscribe(u=>{if(s.push(u),a===null)l=Date.now(),a=setTimeout(c,Math.min(e,r));else{clearTimeout(a);let h=Date.now()-l;a=setTimeout(c,Math.min(e,Math.max(0,r-h)))}})},n}};function re(){let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}}var zl=Symbol.for("immer-nothing"),Zn=Symbol.for("immer-draftable"),X=Symbol.for("immer-state"),Fh=process.env.NODE_ENV!=="production"?[function(t){return`The plugin for '${t}' has not been loaded into Immer. To enable the plugin, import and call \`enable${t}()\` when initializing your application.`},function(t){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${t}'`},"This object has been frozen and should not be mutated",function(t){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+t},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(t){return`'current' expects a draft, got: ${t}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(t){return`'original' expects a draft, got: ${t}`}]:[];function oe(t,...e){if(process.env.NODE_ENV!=="production"){let r=Fh[t],n=typeof r=="function"?r.apply(null,e):r;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${t}. Full error at: https://bit.ly/3cXEKWf`)}var Pr=Object.getPrototypeOf;function Tr(t){return!!t&&!!t[X]}function lt(t){return t?Ph(t)||Array.isArray(t)||!!t[Zn]||!!t.constructor?.[Zn]||pi(t)||mi(t):!1}var $v=Object.prototype.constructor.toString();function Ph(t){if(!t||typeof t!="object")return!1;let e=Pr(t);if(e===null)return!0;let r=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===$v}function yn(t,e){Ar(t)===0?Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)}):t.forEach((r,n)=>e(n,r,t))}function Ar(t){let e=t[X];return e?e.type_:Array.isArray(t)?1:pi(t)?2:mi(t)?3:0}function Qn(t,e){return Ar(t)===2?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function ya(t,e){return Ar(t)===2?t.get(e):t[e]}function Th(t,e,r){let n=Ar(t);n===2?t.set(e,r):n===3?t.add(r):t[e]=r}function Uv(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function pi(t){return t instanceof Map}function mi(t){return t instanceof Set}function fe(t){return t.copy_||t.base_}function ja(t,e){if(pi(t))return new Map(t);if(mi(t))return new Set(t);if(Array.isArray(t))return Array.prototype.slice.call(t);let r=Ph(t);if(e===!0||e==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(t);delete n[X];let i=Reflect.ownKeys(n);for(let s=0;s<i.length;s++){let a=i[s],l=n[a];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[a]={configurable:!0,writable:!0,enumerable:l.enumerable,value:t[a]})}return Object.create(Pr(t),n)}else{let n=Pr(t);if(n!==null&&r)return{...t};let i=Object.create(n);return Object.assign(i,t)}}function Vl(t,e=!1){return Hs(t)||Tr(t)||!lt(t)||(Ar(t)>1&&(t.set=t.add=t.clear=t.delete=qv),Object.freeze(t),e&&Object.values(t).forEach(r=>Vl(r,!0))),t}function qv(){oe(2)}function Hs(t){return Object.isFrozen(t)}var Ba={};function Or(t){let e=Ba[t];return e||oe(0,t),e}function Ah(t,e){Ba[t]||(Ba[t]=e)}var Xn;function xs(){return Xn}function zv(t,e){return{drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Nf(t,e){e&&(Or("Patches"),t.patches_=[],t.inversePatches_=[],t.patchListener_=e)}function La(t){Na(t),t.drafts_.forEach(Vv),t.drafts_=null}function Na(t){t===Xn&&(Xn=t.parent_)}function $f(t){return Xn=zv(Xn,t)}function Vv(t){let e=t[X];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function Uf(t,e){e.unfinalizedDrafts_=e.drafts_.length;let r=e.drafts_[0];return t!==void 0&&t!==r?(r[X].modified_&&(La(e),oe(4)),lt(t)&&(t=ks(e,t),e.parent_||Fs(e,t)),e.patches_&&Or("Patches").generateReplacementPatches_(r[X].base_,t,e.patches_,e.inversePatches_)):t=ks(e,r,[]),La(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),t!==zl?t:void 0}function ks(t,e,r){if(Hs(e))return e;let n=e[X];if(!n)return yn(e,(i,s)=>qf(t,n,e,i,s,r)),e;if(n.scope_!==t)return e;if(!n.modified_)return Fs(t,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let i=n.copy_,s=i,a=!1;n.type_===3&&(s=new Set(i),i.clear(),a=!0),yn(s,(l,c)=>qf(t,n,i,l,c,r,a)),Fs(t,i,!1),r&&t.patches_&&Or("Patches").generatePatches_(n,r,t.patches_,t.inversePatches_)}return n.copy_}function qf(t,e,r,n,i,s,a){if(process.env.NODE_ENV!=="production"&&i===r&&oe(5),Tr(i)){let l=s&&e&&e.type_!==3&&!Qn(e.assigned_,n)?s.concat(n):void 0,c=ks(t,i,l);if(Th(r,n,c),Tr(c))t.canAutoFreeze_=!1;else return}else a&&r.add(i);if(lt(i)&&!Hs(i)){if(!t.immer_.autoFreeze_&&t.unfinalizedDrafts_<1)return;ks(t,i),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Fs(t,i)}}function Fs(t,e,r=!1){!t.parent_&&t.immer_.autoFreeze_&&t.canAutoFreeze_&&Vl(e,r)}function Wv(t,e){let r=Array.isArray(t),n={type_:r?1:0,scope_:e?e.scope_:xs(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:t,draft_:null,copy_:null,revoke_:null,isManual_:!1},i=n,s=Wl;r&&(i=[n],s=ei);let{revoke:a,proxy:l}=Proxy.revocable(i,s);return n.draft_=l,n.revoke_=a,l}var Wl={get(t,e){if(e===X)return t;let r=fe(t);if(!Qn(r,e))return Gv(t,r,e);let n=r[e];return t.finalized_||!lt(n)?n:n===ba(t.base_,e)?(va(t),t.copy_[e]=ti(n,t)):n},has(t,e){return e in fe(t)},ownKeys(t){return Reflect.ownKeys(fe(t))},set(t,e,r){let n=Oh(fe(t),e);if(n?.set)return n.set.call(t.draft_,r),!0;if(!t.modified_){let i=ba(fe(t),e),s=i?.[X];if(s&&s.base_===r)return t.copy_[e]=r,t.assigned_[e]=!1,!0;if(Uv(r,i)&&(r!==void 0||Qn(t.base_,e)))return!0;va(t),wt(t)}return t.copy_[e]===r&&(r!==void 0||e in t.copy_)||Number.isNaN(r)&&Number.isNaN(t.copy_[e])||(t.copy_[e]=r,t.assigned_[e]=!0),!0},deleteProperty(t,e){return ba(t.base_,e)!==void 0||e in t.base_?(t.assigned_[e]=!1,va(t),wt(t)):delete t.assigned_[e],t.copy_&&delete t.copy_[e],!0},getOwnPropertyDescriptor(t,e){let r=fe(t),n=Reflect.getOwnPropertyDescriptor(r,e);return n&&{writable:!0,configurable:t.type_!==1||e!=="length",enumerable:n.enumerable,value:r[e]}},defineProperty(){oe(11)},getPrototypeOf(t){return Pr(t.base_)},setPrototypeOf(){oe(12)}},ei={};yn(Wl,(t,e)=>{ei[t]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});ei.deleteProperty=function(t,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&oe(13),ei.set.call(this,t,e,void 0)};ei.set=function(t,e,r){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&oe(14),Wl.set.call(this,t[0],e,r,t[0])};function ba(t,e){let r=t[X];return(r?fe(r):t)[e]}function Gv(t,e,r){let n=Oh(e,r);return n?"value"in n?n.value:n.get?.call(t.draft_):void 0}function Oh(t,e){if(!(e in t))return;let r=Pr(t);for(;r;){let n=Object.getOwnPropertyDescriptor(r,e);if(n)return n;r=Pr(r)}}function wt(t){t.modified_||(t.modified_=!0,t.parent_&&wt(t.parent_))}function va(t){t.copy_||(t.copy_=ja(t.base_,t.scope_.immer_.useStrictShallowCopy_))}var Zv=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,r,n)=>{if(typeof e=="function"&&typeof r!="function"){let s=r;r=e;let a=this;return function(c=s,...u){return a.produce(c,h=>r.call(this,h,...u))}}typeof r!="function"&&oe(6),n!==void 0&&typeof n!="function"&&oe(7);let i;if(lt(e)){let s=$f(this),a=ti(e,void 0),l=!0;try{i=r(a),l=!1}finally{l?La(s):Na(s)}return Nf(s,n),Uf(i,s)}else if(!e||typeof e!="object"){if(i=r(e),i===void 0&&(i=e),i===zl&&(i=void 0),this.autoFreeze_&&Vl(i,!0),n){let s=[],a=[];Or("Patches").generateReplacementPatches_(e,i,s,a),n(s,a)}return i}else oe(1,e)},this.produceWithPatches=(e,r)=>{if(typeof e=="function")return(a,...l)=>this.produceWithPatches(a,c=>e(c,...l));let n,i;return[this.produce(e,r,(a,l)=>{n=a,i=l}),n,i]},typeof t?.autoFreeze=="boolean"&&this.setAutoFreeze(t.autoFreeze),typeof t?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(t.useStrictShallowCopy)}createDraft(t){lt(t)||oe(8),Tr(t)&&(t=Kv(t));let e=$f(this),r=ti(t,void 0);return r[X].isManual_=!0,Na(e),r}finishDraft(t,e){let r=t&&t[X];(!r||!r.isManual_)&&oe(9);let{scope_:n}=r;return Nf(n,e),Uf(void 0,n)}setAutoFreeze(t){this.autoFreeze_=t}setUseStrictShallowCopy(t){this.useStrictShallowCopy_=t}applyPatches(t,e){let r;for(r=e.length-1;r>=0;r--){let i=e[r];if(i.path.length===0&&i.op==="replace"){t=i.value;break}}r>-1&&(e=e.slice(r+1));let n=Or("Patches").applyPatches_;return Tr(t)?n(t,e):this.produce(t,i=>n(i,e))}};function ti(t,e){let r=pi(t)?Or("MapSet").proxyMap_(t,e):mi(t)?Or("MapSet").proxySet_(t,e):Wv(t,e);return(e?e.scope_:xs()).drafts_.push(r),r}function Kv(t){return Tr(t)||oe(10,t),Ih(t)}function Ih(t){if(!lt(t)||Hs(t))return t;let e=t[X],r;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,r=ja(t,e.scope_.immer_.useStrictShallowCopy_)}else r=ja(t,!0);return yn(r,(n,i)=>{Th(r,n,Ih(i))}),e&&(e.finalized_=!1),r}function Hv(){class t extends Map{constructor(c,u){super(),this[X]={type_:2,parent_:u,scope_:u?u.scope_:xs(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return fe(this[X]).size}has(c){return fe(this[X]).has(c)}set(c,u){let h=this[X];return a(h),(!fe(h).has(c)||fe(h).get(c)!==u)&&(r(h),wt(h),h.assigned_.set(c,!0),h.copy_.set(c,u),h.assigned_.set(c,!0)),this}delete(c){if(!this.has(c))return!1;let u=this[X];return a(u),r(u),wt(u),u.base_.has(c)?u.assigned_.set(c,!1):u.assigned_.delete(c),u.copy_.delete(c),!0}clear(){let c=this[X];a(c),fe(c).size&&(r(c),wt(c),c.assigned_=new Map,yn(c.base_,u=>{c.assigned_.set(u,!1)}),c.copy_.clear())}forEach(c,u){let h=this[X];fe(h).forEach((f,d,p)=>{c.call(u,this.get(d),d,this)})}get(c){let u=this[X];a(u);let h=fe(u).get(c);if(u.finalized_||!lt(h)||h!==u.base_.get(c))return h;let f=ti(h,u);return r(u),u.copy_.set(c,f),f}keys(){return fe(this[X]).keys()}values(){let c=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{let u=c.next();return u.done?u:{done:!1,value:this.get(u.value)}}}}entries(){let c=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{let u=c.next();if(u.done)return u;let h=this.get(u.value);return{done:!1,value:[u.value,h]}}}}[Symbol.iterator](){return this.entries()}}function e(l,c){return new t(l,c)}function r(l){l.copy_||(l.assigned_=new Map,l.copy_=new Map(l.base_))}class n extends Set{constructor(c,u){super(),this[X]={type_:3,parent_:u,scope_:u?u.scope_:xs(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return fe(this[X]).size}has(c){let u=this[X];return a(u),u.copy_?!!(u.copy_.has(c)||u.drafts_.has(c)&&u.copy_.has(u.drafts_.get(c))):u.base_.has(c)}add(c){let u=this[X];return a(u),this.has(c)||(s(u),wt(u),u.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let u=this[X];return a(u),s(u),wt(u),u.copy_.delete(c)||(u.drafts_.has(c)?u.copy_.delete(u.drafts_.get(c)):!1)}clear(){let c=this[X];a(c),fe(c).size&&(s(c),wt(c),c.copy_.clear())}values(){let c=this[X];return a(c),s(c),c.copy_.values()}entries(){let c=this[X];return a(c),s(c),c.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(c,u){let h=this.values(),f=h.next();for(;!f.done;)c.call(u,f.value,f.value,this),f=h.next()}}function i(l,c){return new n(l,c)}function s(l){l.copy_||(l.copy_=new Set,l.base_.forEach(c=>{if(lt(c)){let u=ti(c,l);l.drafts_.set(c,u),l.copy_.add(u)}else l.copy_.add(c)}))}function a(l){l.revoked_&&oe(3,JSON.stringify(fe(l)))}Ah("MapSet",{proxyMap_:e,proxySet_:i})}function Yv(){process.env.NODE_ENV!=="production"&&Fh.push('Sets cannot have "replace" patches.',function(d){return"Unsupported patch operation: "+d},function(d){return"Cannot apply patch, path doesn't resolve: "+d},"Patching reserved attributes like __proto__, prototype and constructor is not allowed");let e="replace",r="add",n="remove";function i(d,p,m,g){switch(d.type_){case 0:case 2:return a(d,p,m,g);case 1:return s(d,p,m,g);case 3:return l(d,p,m,g)}}function s(d,p,m,g){let{base_:y,assigned_:b}=d,D=d.copy_;D.length<y.length&&([y,D]=[D,y],[m,g]=[g,m]);for(let v=0;v<y.length;v++)if(b[v]&&D[v]!==y[v]){let S=p.concat([v]);m.push({op:e,path:S,value:f(D[v])}),g.push({op:e,path:S,value:f(y[v])})}for(let v=y.length;v<D.length;v++){let S=p.concat([v]);m.push({op:r,path:S,value:f(D[v])})}for(let v=D.length-1;y.length<=v;--v){let S=p.concat([v]);g.push({op:n,path:S})}}function a(d,p,m,g){let{base_:y,copy_:b}=d;yn(d.assigned_,(D,v)=>{let S=ya(y,D),C=ya(b,D),x=v?Qn(y,D)?e:r:n;if(S===C&&x===e)return;let _=p.concat(D);m.push(x===n?{op:x,path:_}:{op:x,path:_,value:C}),g.push(x===r?{op:n,path:_}:x===n?{op:r,path:_,value:f(S)}:{op:e,path:_,value:f(S)})})}function l(d,p,m,g){let{base_:y,copy_:b}=d,D=0;y.forEach(v=>{if(!b.has(v)){let S=p.concat([D]);m.push({op:n,path:S,value:v}),g.unshift({op:r,path:S,value:v})}D++}),D=0,b.forEach(v=>{if(!y.has(v)){let S=p.concat([D]);m.push({op:r,path:S,value:v}),g.unshift({op:n,path:S,value:v})}D++})}function c(d,p,m,g){m.push({op:e,path:[],value:p===zl?void 0:p}),g.push({op:e,path:[],value:d})}function u(d,p){return p.forEach(m=>{let{path:g,op:y}=m,b=d;for(let C=0;C<g.length-1;C++){let x=Ar(b),_=g[C];typeof _!="string"&&typeof _!="number"&&(_=""+_),(x===0||x===1)&&(_==="__proto__"||_==="constructor")&&oe(19),typeof b=="function"&&_==="prototype"&&oe(19),b=ya(b,_),typeof b!="object"&&oe(18,g.join("/"))}let D=Ar(b),v=h(m.value),S=g[g.length-1];switch(y){case e:switch(D){case 2:return b.set(S,v);case 3:oe(16);default:return b[S]=v}case r:switch(D){case 1:return S==="-"?b.push(v):b.splice(S,0,v);case 2:return b.set(S,v);case 3:return b.add(v);default:return b[S]=v}case n:switch(D){case 1:return b.splice(S,1);case 2:return b.delete(S);case 3:return b.delete(m.value);default:return delete b[S]}default:oe(17,y)}}),d}function h(d){if(!lt(d))return d;if(Array.isArray(d))return d.map(h);if(pi(d))return new Map(Array.from(d.entries()).map(([m,g])=>[m,h(g)]));if(mi(d))return new Set(Array.from(d).map(h));let p=Object.create(Pr(d));for(let m in d)p[m]=h(d[m]);return Qn(d,Zn)&&(p[Zn]=d[Zn]),p}function f(d){return Tr(d)?h(d):d}Ah("Patches",{applyPatches_:u,generatePatches_:i,generateReplacementPatches_:c})}var Re=new Zv;Re.produce;var Jv=Re.produceWithPatches.bind(Re);Re.setAutoFreeze.bind(Re);Re.setUseStrictShallowCopy.bind(Re);var $a=Re.applyPatches.bind(Re);Re.createDraft.bind(Re);Re.finishDraft.bind(Re);Hv();Yv();function un(...t){return t.filter(e=>e!==void 0).reduce((e,r)=>e.concat(r),[])}function zf(t){return[{op:"replace",path:[],value:t}]}function Gl(t,e){let r=(n,i)=>{t(()=>[n,zf(n)],un(e?.(),i))};return r.withProducer=(n,i)=>{t(s=>{let[a,l]=Jv(s,n);if(St(a))return[a,l];throw new Error("Cannot update value to NOT_AVAILABLE")},un(e?.(),i))},r.withUpdater=(n,i)=>{t(s=>{let a=n(s);return[a,zf(a)]},un(e?.(),i))},r.withPatchUpdater=(n,i)=>{t(n,un(e?.(),i))},r.withPatches=(n,i)=>{t(s=>[$a(s,n),n],un(e?.(),i))},r.withValueAndPatches=(n,i,s)=>{t(()=>[n,i],un(e?.(),s))},r}var Qv=(t,e)=>t===e,ri=class t extends Ut{static create(e,r=Qv){let n=new t(e,r),s=Gl((a,l)=>{n.update(a,l)});return[n,s]}static createReadonly(e){return t.create(e)[0]}constructor(e,r){super(),this.value=e,this.equalsPredicate=r,this.subscribers=new Set,this.queuedUpdaters=[],this.isEmitting=!1}get(){return this.value}pull(){return this.value}notifyFull(e,r,n){for(let{type:i,callback:s}of this.subscribers)i==="full"&&s(e,r,n)}notifyAll(e,r,n){for(let{type:i,callback:s}of this.subscribers)i==="regular"?s(e):s(e,r,n)}notifyAndUpdateIfChanged(e,r,n){this.equalsPredicate(this.value,e)?n.length>0&&this.notifyFull(e,r,n):(this.value=e,this.notifyAll(e,r,n))}isReplaceRoot(e){return e.path.length===0&&e.op==="replace"}update(e,r){if(this.queuedUpdaters.push([e,r]),!this.isEmitting){this.isEmitting=!0;try{for(;this.queuedUpdaters.length>0;){let n=this.value,i=[],s=[];for(;this.queuedUpdaters.length>0;){let[a,l]=this.queuedUpdaters.shift(),[c,u]=a(n);n=c;let h=u.findIndex(this.isReplaceRoot);h!==-1?i=u.slice(h):i.push(...u),l!==void 0&&s.push(...l)}this.notifyAndUpdateIfChanged(n,i,s)}}finally{this.isEmitting=!1}}}subscribe(e){let r={type:"regular",callback:e};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}}subscribeAndNow(e){let r=this.subscribe(e);return e(this.value),r}subscribeFull(e){let r={type:"full",callback:e};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}}async until(e){let r=this.get();if(e(r))return r;let{promise:n,resolve:i}=re(),s=this.subscribe(a=>{e(a)&&(i(a),s())});return await n}};function St(t){return t!==Ze.NOT_AVAILABLE}var Ze=class t extends Ut{static{this.NOT_AVAILABLE=Symbol("notAvailable")}static create(e,r,n=(i,s)=>i===s){return new t(e,r,n)}static createWithoutInitialValue(e,r=(n,i)=>n===i){let n=(i,s)=>i===t.NOT_AVAILABLE||s===t.NOT_AVAILABLE?i===s:r(i,s);return new t(t.NOT_AVAILABLE,e,n)}static deriveFrom(e,r,n){let i;n!==void 0&&(i=(a,l)=>a===t.NOT_AVAILABLE||l===t.NOT_AVAILABLE?a===l:n(a,l));let s=()=>{let a=e.map(l=>l.get());return a.some(l=>l===t.NOT_AVAILABLE)?t.NOT_AVAILABLE:r(...a)};return new t(s(),a=>{let l=e.map(u=>u.subscribe(()=>{let h=s();St(h)&&a(h)})),c=s();return St(c)&&a(c),()=>{l.forEach(u=>u())}},i)}static asyncDeriveFrom(e,r,n,i){let s;i!==void 0&&(s=(c,u)=>c===t.NOT_AVAILABLE||u===t.NOT_AVAILABLE?c===u:i(c,u));let a=-1,l=-1;return new t(t.NOT_AVAILABLE,c=>{let u=()=>{l++;let f=l,d=r.map(p=>p.get());d.some(p=>p===t.NOT_AVAILABLE)||n(...d).then(p=>{if(St(p))if(e==="eager")f>a&&(a=f,c(p));else{let m=e;throw new Error(`Unknown strategy: ${m}`)}})},h=r.map(f=>f.subscribe(()=>{u()}));return u(),()=>{h.forEach(f=>f())}},s)}constructor(e,r,n=(i,s)=>i===s){super(),this.subscribeUpstream=r,this.dataIsStale=!0,this.upstreamUnsubscribe=null,this.subscribersCount=0,this.isSubscribedToUpstream=!1,this.updateReceivedSynchronousCallbacks=new Set,[this.signal,this.setValue]=ri.create(e,n),[this.updateReceivedEvent,this.emitUpdateReceivedEvent]=Jn.create()}isStale(){return this.dataIsStale}subscribeToUpstream(){this.isSubscribedToUpstream=!0;let e=!0,r=!1,n=this.subscribeUpstream(Gl((i,s)=>{if(e){this.setValue.withPatchUpdater(i,s),this.dataIsStale=r,this.emitUpdateReceivedEvent();for(let a of this.updateReceivedSynchronousCallbacks)a()}}),i=>{e&&(Promise.reject(i),this.dataIsStale=!0,this.isSubscribedToUpstream=!1,this.upstreamUnsubscribe=null,e=!1)});this.upstreamUnsubscribe=()=>{e&&(e=!1,r=!0,n())}}unsubscribeFromUpstream(){this.isSubscribedToUpstream=!1,this.upstreamUnsubscribe!==null&&(this.upstreamUnsubscribe(),this.upstreamUnsubscribe=null,this.dataIsStale=!0)}get(){return this.signal.get()}async pull(){let{promise:e,resolve:r}=re();if(!this.isStale())r(this.get());else{let n=this.subscribe(()=>{});this.updateReceivedEvent.subscribeOnce(()=>{r(this.get())}),e.then(n)}return e}runOnNextFreshData(e){if(!this.isStale())e(this.get());else{let r=null,n=()=>{this.updateReceivedSynchronousCallbacks.delete(n),e(this.get()),r?.()};this.updateReceivedSynchronousCallbacks.add(n),r=this.subscribe(()=>{})}}async ensureAvailable(){return await this.pull(),this}subscribe(e){this.isSubscribedToUpstream||this.subscribeToUpstream(),this.subscribersCount++;let r=this.signal.subscribe(e),n=!1;return()=>{n||(r(),n=!0,this.subscribersCount--,this.subscribersCount===0&&this.isSubscribedToUpstream&&this.unsubscribeFromUpstream())}}subscribeFull(e){this.isSubscribedToUpstream||this.subscribeToUpstream(),this.subscribersCount++;let r=this.signal.subscribeFull(e),n=!1;return()=>{n||(r(),n=!0,this.subscribersCount--,this.subscribersCount===0&&this.isSubscribedToUpstream&&this.unsubscribeFromUpstream())}}passiveSubscribe(e){return this.signal.subscribe(e)}passiveSubscribeFull(e){return this.signal.subscribeFull(e)}async until(e){let r=this.get();if(St(r)&&e(r))return r;let{promise:n,resolve:i}=re(),s=this.subscribe(a=>{St(a)&&e(a)&&(i(a),s())});return await n}},Xv=[41343,52993,16141,39414,22931],Gn=Symbol(),Et=class t extends Ut{static create(){let e=new t;return[e,n=>{e.emit(n)}]}constructor(){super(),this.subscriber=null,this.queued=[],this.isNotifying=!1}emit(e){this.queued.length===0&&this.queued.at(-1)!==Gn&&this.queued.push(Gn),this.queued.push(e),this.isNotifying||this.notifier()}async notifier(){for(this.isNotifying=!0;this.subscriber!==null&&this.queued.length>0;){let e=this.queued.shift();e===Gn?await Promise.resolve():this.subscriber(e)}this.isNotifying=!1}subscribe(e){if(this.subscriber!==null)throw new Error("Cannot have more than one subscriber");return this.subscriber=e,!this.isNotifying&&this.queued.length>0&&(this.queued=[Gn,...this.queued.filter(r=>r!==Gn)],this.notifier()),()=>{this.subscriber=null}}flow(){let[e,r]=Jn.create();return this.subscribe(r),e}},Ua=class extends Ut{constructor(){super(...arguments),this.canceled=!1,this.listeners=new Set}subscribe(e){if(this.canceled){let r=!1;return Promise.resolve().then(()=>{r||e()}),()=>{r=!0}}return this.listeners.add(e),()=>{this.listeners.delete(e)}}cancel(){if(this.canceled)throw new Error("Already canceled");this.canceled=!0;for(let e of this.listeners)e()}isCanceled(){return this.canceled}},Ps=class{constructor(){this.eagerCleaned=!1,this.disposed=!1,this.cleanups=[]}register(e){if(this.eagerCleaned)throw new Error("Cannot register a cleanup after eagerClean() was called.");if(this.disposed)throw new Error("Cannot register a cleanup after the Cleaner was disposed.");this.cleanups.push(e)}runCleanersInternal(){for(let e of this.cleanups)e();this.cleanups.length=0}[Symbol.dispose](){if(!this.eagerCleaned){if(this.disposed)throw new Error("Cannot dispose a Cleaner that was already disposed.");this.runCleanersInternal()}}eagerClean(){if(this.eagerCleaned)throw new Error("Cannot call eagerClean() twice.");if(this.disposed)throw new Error("Cannot call eagerClean() after the Cleaner was disposed.");this.eagerCleaned=!0,this.runCleanersInternal()}};function A(t=0){let e=new Error().stack;return e?e.split(`
142
142
  `).slice(2+t).join(`
143
- `):""}function va(t,e){if(Yn.default.env.LMS_KEEP_INTERNAL_STACK)return;let r=t.stack??"";t.stack=(r.substring(0,r.indexOf(`
143
+ `):""}function Da(t,e){if(Yn.default.env.LMS_KEEP_INTERNAL_STACK)return;let r=t.stack??"";t.stack=(r.substring(0,r.indexOf(`
144
144
  at `)).trimEnd()+`
145
- `+e).trimEnd()}var Ts=class{constructor(e=0){this.nextId=e}next(){let e=this.nextId;return this.nextId++,e}};function Xv(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var fs={exports:{}},hs={exports:{}},Da,zf;function eD(){return zf||(zf=1,Da=({onlyFirst:t=!1}={})=>{let e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(e,t?void 0:"g")}),Da}var wa,Vf;function Ih(){if(Vf)return wa;Vf=1;let t=eD();return wa=e=>typeof e=="string"?e.replace(t(),""):e,wa}var ps={exports:{}},Wf;function tD(){if(Wf)return ps.exports;Wf=1;let t=e=>Number.isNaN(e)?!1:e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141);return ps.exports=t,ps.exports.default=t,ps.exports}var Sa,Gf;function rD(){return Gf||(Gf=1,Sa=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}),Sa}var Zf;function Ys(){if(Zf)return hs.exports;Zf=1;let t=Ih(),e=tD(),r=rD(),n=i=>{if(typeof i!="string"||i.length===0||(i=t(i),i.length===0))return 0;i=i.replace(r()," ");let s=0;for(let a=0;a<i.length;a++){let l=i.codePointAt(a);l<=31||l>=127&&l<=159||l>=768&&l<=879||(l>65535&&a++,s+=e(l)?2:1)}return s};return hs.exports=n,hs.exports.default=n,hs.exports}var ms={exports:{}},Kf;function nD(){if(Kf)return ms.exports;Kf=1;let t=Ys(),e=r=>{let n=0;for(let i of r.split(`
146
- `))n=Math.max(n,t(i));return n};return ms.exports=e,ms.exports.default=e,ms.exports}var gs={exports:{}},iD={topLeft:"\u250C",topRight:"\u2510",bottomRight:"\u2518",bottomLeft:"\u2514",vertical:"\u2502",horizontal:"\u2500"},sD={topLeft:"\u2554",topRight:"\u2557",bottomRight:"\u255D",bottomLeft:"\u255A",vertical:"\u2551",horizontal:"\u2550"},oD={topLeft:"\u256D",topRight:"\u256E",bottomRight:"\u256F",bottomLeft:"\u2570",vertical:"\u2502",horizontal:"\u2500"},aD={topLeft:"\u250F",topRight:"\u2513",bottomRight:"\u251B",bottomLeft:"\u2517",vertical:"\u2503",horizontal:"\u2501"},lD={topLeft:"\u2553",topRight:"\u2556",bottomRight:"\u255C",bottomLeft:"\u2559",vertical:"\u2551",horizontal:"\u2500"},cD={topLeft:"\u2552",topRight:"\u2555",bottomRight:"\u255B",bottomLeft:"\u2558",vertical:"\u2502",horizontal:"\u2550"},uD={topLeft:"+",topRight:"+",bottomRight:"+",bottomLeft:"+",vertical:"|",horizontal:"-"},dD={single:iD,double:sD,round:oD,bold:aD,singleDouble:lD,doubleSingle:cD,classic:uD},Hf;function fD(){if(Hf)return gs.exports;Hf=1;let t=dD;return gs.exports=t,gs.exports.default=t,gs.exports}var ys={exports:{}},Yf;function hD(){if(Yf)return ys.exports;Yf=1;let t=/[\p{Lu}]/u,e=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,i=/[_.\- ]+/,s=new RegExp("^"+i.source),a=new RegExp(i.source+n.source,"gu"),l=new RegExp("\\d+"+n.source,"gu"),c=(d,p,m)=>{let g=!1,y=!1,b=!1;for(let D=0;D<d.length;D++){let v=d[D];g&&t.test(v)?(d=d.slice(0,D)+"-"+d.slice(D),g=!1,b=y,y=!0,D++):y&&b&&e.test(v)?(d=d.slice(0,D-1)+"-"+d.slice(D-1),b=y,y=!1,g=!0):(g=p(v)===v&&m(v)!==v,b=y,y=m(v)===v&&p(v)!==v)}return d},u=(d,p)=>(r.lastIndex=0,d.replace(r,m=>p(m))),h=(d,p)=>(a.lastIndex=0,l.lastIndex=0,d.replace(a,(m,g)=>p(g)).replace(l,m=>p(m))),f=(d,p)=>{if(!(typeof d=="string"||Array.isArray(d)))throw new TypeError("Expected the input to be `string | string[]`");if(p={pascalCase:!1,preserveConsecutiveUppercase:!1,...p},Array.isArray(d)?d=d.map(b=>b.trim()).filter(b=>b.length).join("-"):d=d.trim(),d.length===0)return"";let m=p.locale===!1?b=>b.toLowerCase():b=>b.toLocaleLowerCase(p.locale),g=p.locale===!1?b=>b.toUpperCase():b=>b.toLocaleUpperCase(p.locale);return d.length===1?p.pascalCase?g(d):m(d):(d!==m(d)&&(d=c(d,m,g)),d=d.replace(s,""),p.preserveConsecutiveUppercase?d=u(d,m):d=m(d),p.pascalCase&&(d=g(d.charAt(0))+d.slice(1)),h(d,g))};return ys.exports=f,ys.exports.default=f,ys.exports}var Ca,Jf;function pD(){if(Jf)return Ca;Jf=1;let t=Ys();function e(i,s){if(!i)return i;s=s||{};let a=s.align||"center";if(a==="left")return i;let l=s.split||`
147
- `,c=s.pad||" ",u=a!=="right"?r:n,h=!1;Array.isArray(i)||(h=!0,i=String(i).split(l));let f,d=0;return i=i.map(function(p){return p=String(p),f=t(p),d=Math.max(f,d),{str:p,width:f}}).map(function(p){return new Array(u(d,p.width)+1).join(c)+p.str}),h?i.join(l):i}e.left=function(s){return e(s,{align:"left"})},e.center=function(s){return e(s,{align:"center"})},e.right=function(s){return e(s,{align:"right"})},Ca=e;function r(i,s){return Math.floor((i-s)/2)}function n(i,s){return i-s}return Ca}var Ss={exports:{}},Ea,Qf;function mD(){return Qf||(Qf=1,Ea={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),Ea}var _a,Xf;function Rh(){if(Xf)return _a;Xf=1;let t=mD(),e={};for(let i of Object.keys(t))e[t[i]]=i;let r={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};_a=r;for(let i of Object.keys(r)){if(!("channels"in r[i]))throw new Error("missing channels property: "+i);if(!("labels"in r[i]))throw new Error("missing channel labels property: "+i);if(r[i].labels.length!==r[i].channels)throw new Error("channel and label counts mismatch: "+i);let{channels:s,labels:a}=r[i];delete r[i].channels,delete r[i].labels,Object.defineProperty(r[i],"channels",{value:s}),Object.defineProperty(r[i],"labels",{value:a})}r.rgb.hsl=function(i){let s=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.min(s,a,l),u=Math.max(s,a,l),h=u-c,f,d;u===c?f=0:s===u?f=(a-l)/h:a===u?f=2+(l-s)/h:l===u&&(f=4+(s-a)/h),f=Math.min(f*60,360),f<0&&(f+=360);let p=(c+u)/2;return u===c?d=0:p<=.5?d=h/(u+c):d=h/(2-u-c),[f,d*100,p*100]},r.rgb.hsv=function(i){let s,a,l,c,u,h=i[0]/255,f=i[1]/255,d=i[2]/255,p=Math.max(h,f,d),m=p-Math.min(h,f,d),g=function(y){return(p-y)/6/m+1/2};return m===0?(c=0,u=0):(u=m/p,s=g(h),a=g(f),l=g(d),h===p?c=l-a:f===p?c=1/3+s-l:d===p&&(c=2/3+a-s),c<0?c+=1:c>1&&(c-=1)),[c*360,u*100,p*100]},r.rgb.hwb=function(i){let s=i[0],a=i[1],l=i[2],c=r.rgb.hsl(i)[0],u=1/255*Math.min(s,Math.min(a,l));return l=1-1/255*Math.max(s,Math.max(a,l)),[c,u*100,l*100]},r.rgb.cmyk=function(i){let s=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.min(1-s,1-a,1-l),u=(1-s-c)/(1-c)||0,h=(1-a-c)/(1-c)||0,f=(1-l-c)/(1-c)||0;return[u*100,h*100,f*100,c*100]};function n(i,s){return(i[0]-s[0])**2+(i[1]-s[1])**2+(i[2]-s[2])**2}return r.rgb.keyword=function(i){let s=e[i];if(s)return s;let a=1/0,l;for(let c of Object.keys(t)){let u=t[c],h=n(i,u);h<a&&(a=h,l=c)}return l},r.keyword.rgb=function(i){return t[i]},r.rgb.xyz=function(i){let s=i[0]/255,a=i[1]/255,l=i[2]/255;s=s>.04045?((s+.055)/1.055)**2.4:s/12.92,a=a>.04045?((a+.055)/1.055)**2.4:a/12.92,l=l>.04045?((l+.055)/1.055)**2.4:l/12.92;let c=s*.4124+a*.3576+l*.1805,u=s*.2126+a*.7152+l*.0722,h=s*.0193+a*.1192+l*.9505;return[c*100,u*100,h*100]},r.rgb.lab=function(i){let s=r.rgb.xyz(i),a=s[0],l=s[1],c=s[2];a/=95.047,l/=100,c/=108.883,a=a>.008856?a**(1/3):7.787*a+16/116,l=l>.008856?l**(1/3):7.787*l+16/116,c=c>.008856?c**(1/3):7.787*c+16/116;let u=116*l-16,h=500*(a-l),f=200*(l-c);return[u,h,f]},r.hsl.rgb=function(i){let s=i[0]/360,a=i[1]/100,l=i[2]/100,c,u,h;if(a===0)return h=l*255,[h,h,h];l<.5?c=l*(1+a):c=l+a-l*a;let f=2*l-c,d=[0,0,0];for(let p=0;p<3;p++)u=s+1/3*-(p-1),u<0&&u++,u>1&&u--,6*u<1?h=f+(c-f)*6*u:2*u<1?h=c:3*u<2?h=f+(c-f)*(2/3-u)*6:h=f,d[p]=h*255;return d},r.hsl.hsv=function(i){let s=i[0],a=i[1]/100,l=i[2]/100,c=a,u=Math.max(l,.01);l*=2,a*=l<=1?l:2-l,c*=u<=1?u:2-u;let h=(l+a)/2,f=l===0?2*c/(u+c):2*a/(l+a);return[s,f*100,h*100]},r.hsv.rgb=function(i){let s=i[0]/60,a=i[1]/100,l=i[2]/100,c=Math.floor(s)%6,u=s-Math.floor(s),h=255*l*(1-a),f=255*l*(1-a*u),d=255*l*(1-a*(1-u));switch(l*=255,c){case 0:return[l,d,h];case 1:return[f,l,h];case 2:return[h,l,d];case 3:return[h,f,l];case 4:return[d,h,l];case 5:return[l,h,f]}},r.hsv.hsl=function(i){let s=i[0],a=i[1]/100,l=i[2]/100,c=Math.max(l,.01),u,h;h=(2-a)*l;let f=(2-a)*c;return u=a*c,u/=f<=1?f:2-f,u=u||0,h/=2,[s,u*100,h*100]},r.hwb.rgb=function(i){let s=i[0]/360,a=i[1]/100,l=i[2]/100,c=a+l,u;c>1&&(a/=c,l/=c);let h=Math.floor(6*s),f=1-l;u=6*s-h,(h&1)!==0&&(u=1-u);let d=a+u*(f-a),p,m,g;switch(h){default:case 6:case 0:p=f,m=d,g=a;break;case 1:p=d,m=f,g=a;break;case 2:p=a,m=f,g=d;break;case 3:p=a,m=d,g=f;break;case 4:p=d,m=a,g=f;break;case 5:p=f,m=a,g=d;break}return[p*255,m*255,g*255]},r.cmyk.rgb=function(i){let s=i[0]/100,a=i[1]/100,l=i[2]/100,c=i[3]/100,u=1-Math.min(1,s*(1-c)+c),h=1-Math.min(1,a*(1-c)+c),f=1-Math.min(1,l*(1-c)+c);return[u*255,h*255,f*255]},r.xyz.rgb=function(i){let s=i[0]/100,a=i[1]/100,l=i[2]/100,c,u,h;return c=s*3.2406+a*-1.5372+l*-.4986,u=s*-.9689+a*1.8758+l*.0415,h=s*.0557+a*-.204+l*1.057,c=c>.0031308?1.055*c**(1/2.4)-.055:c*12.92,u=u>.0031308?1.055*u**(1/2.4)-.055:u*12.92,h=h>.0031308?1.055*h**(1/2.4)-.055:h*12.92,c=Math.min(Math.max(0,c),1),u=Math.min(Math.max(0,u),1),h=Math.min(Math.max(0,h),1),[c*255,u*255,h*255]},r.xyz.lab=function(i){let s=i[0],a=i[1],l=i[2];s/=95.047,a/=100,l/=108.883,s=s>.008856?s**(1/3):7.787*s+16/116,a=a>.008856?a**(1/3):7.787*a+16/116,l=l>.008856?l**(1/3):7.787*l+16/116;let c=116*a-16,u=500*(s-a),h=200*(a-l);return[c,u,h]},r.lab.xyz=function(i){let s=i[0],a=i[1],l=i[2],c,u,h;u=(s+16)/116,c=a/500+u,h=u-l/200;let f=u**3,d=c**3,p=h**3;return u=f>.008856?f:(u-16/116)/7.787,c=d>.008856?d:(c-16/116)/7.787,h=p>.008856?p:(h-16/116)/7.787,c*=95.047,u*=100,h*=108.883,[c,u,h]},r.lab.lch=function(i){let s=i[0],a=i[1],l=i[2],c;c=Math.atan2(l,a)*360/2/Math.PI,c<0&&(c+=360);let h=Math.sqrt(a*a+l*l);return[s,h,c]},r.lch.lab=function(i){let s=i[0],a=i[1],c=i[2]/360*2*Math.PI,u=a*Math.cos(c),h=a*Math.sin(c);return[s,u,h]},r.rgb.ansi16=function(i,s=null){let[a,l,c]=i,u=s===null?r.rgb.hsv(i)[2]:s;if(u=Math.round(u/50),u===0)return 30;let h=30+(Math.round(c/255)<<2|Math.round(l/255)<<1|Math.round(a/255));return u===2&&(h+=60),h},r.hsv.ansi16=function(i){return r.rgb.ansi16(r.hsv.rgb(i),i[2])},r.rgb.ansi256=function(i){let s=i[0],a=i[1],l=i[2];return s===a&&a===l?s<8?16:s>248?231:Math.round((s-8)/247*24)+232:16+36*Math.round(s/255*5)+6*Math.round(a/255*5)+Math.round(l/255*5)},r.ansi16.rgb=function(i){let s=i%10;if(s===0||s===7)return i>50&&(s+=3.5),s=s/10.5*255,[s,s,s];let a=(~~(i>50)+1)*.5,l=(s&1)*a*255,c=(s>>1&1)*a*255,u=(s>>2&1)*a*255;return[l,c,u]},r.ansi256.rgb=function(i){if(i>=232){let u=(i-232)*10+8;return[u,u,u]}i-=16;let s,a=Math.floor(i/36)/5*255,l=Math.floor((s=i%36)/6)/5*255,c=s%6/5*255;return[a,l,c]},r.rgb.hex=function(i){let a=(((Math.round(i[0])&255)<<16)+((Math.round(i[1])&255)<<8)+(Math.round(i[2])&255)).toString(16).toUpperCase();return"000000".substring(a.length)+a},r.hex.rgb=function(i){let s=i.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!s)return[0,0,0];let a=s[0];s[0].length===3&&(a=a.split("").map(f=>f+f).join(""));let l=parseInt(a,16),c=l>>16&255,u=l>>8&255,h=l&255;return[c,u,h]},r.rgb.hcg=function(i){let s=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.max(Math.max(s,a),l),u=Math.min(Math.min(s,a),l),h=c-u,f,d;return h<1?f=u/(1-h):f=0,h<=0?d=0:c===s?d=(a-l)/h%6:c===a?d=2+(l-s)/h:d=4+(s-a)/h,d/=6,d%=1,[d*360,h*100,f*100]},r.hsl.hcg=function(i){let s=i[1]/100,a=i[2]/100,l=a<.5?2*s*a:2*s*(1-a),c=0;return l<1&&(c=(a-.5*l)/(1-l)),[i[0],l*100,c*100]},r.hsv.hcg=function(i){let s=i[1]/100,a=i[2]/100,l=s*a,c=0;return l<1&&(c=(a-l)/(1-l)),[i[0],l*100,c*100]},r.hcg.rgb=function(i){let s=i[0]/360,a=i[1]/100,l=i[2]/100;if(a===0)return[l*255,l*255,l*255];let c=[0,0,0],u=s%1*6,h=u%1,f=1-h,d=0;switch(Math.floor(u)){case 0:c[0]=1,c[1]=h,c[2]=0;break;case 1:c[0]=f,c[1]=1,c[2]=0;break;case 2:c[0]=0,c[1]=1,c[2]=h;break;case 3:c[0]=0,c[1]=f,c[2]=1;break;case 4:c[0]=h,c[1]=0,c[2]=1;break;default:c[0]=1,c[1]=0,c[2]=f}return d=(1-a)*l,[(a*c[0]+d)*255,(a*c[1]+d)*255,(a*c[2]+d)*255]},r.hcg.hsv=function(i){let s=i[1]/100,a=i[2]/100,l=s+a*(1-s),c=0;return l>0&&(c=s/l),[i[0],c*100,l*100]},r.hcg.hsl=function(i){let s=i[1]/100,l=i[2]/100*(1-s)+.5*s,c=0;return l>0&&l<.5?c=s/(2*l):l>=.5&&l<1&&(c=s/(2*(1-l))),[i[0],c*100,l*100]},r.hcg.hwb=function(i){let s=i[1]/100,a=i[2]/100,l=s+a*(1-s);return[i[0],(l-s)*100,(1-l)*100]},r.hwb.hcg=function(i){let s=i[1]/100,l=1-i[2]/100,c=l-s,u=0;return c<1&&(u=(l-c)/(1-c)),[i[0],c*100,u*100]},r.apple.rgb=function(i){return[i[0]/65535*255,i[1]/65535*255,i[2]/65535*255]},r.rgb.apple=function(i){return[i[0]/255*65535,i[1]/255*65535,i[2]/255*65535]},r.gray.rgb=function(i){return[i[0]/100*255,i[0]/100*255,i[0]/100*255]},r.gray.hsl=function(i){return[0,0,i[0]]},r.gray.hsv=r.gray.hsl,r.gray.hwb=function(i){return[0,100,i[0]]},r.gray.cmyk=function(i){return[0,0,0,i[0]]},r.gray.lab=function(i){return[i[0],0,0]},r.gray.hex=function(i){let s=Math.round(i[0]/100*255)&255,l=((s<<16)+(s<<8)+s).toString(16).toUpperCase();return"000000".substring(l.length)+l},r.rgb.gray=function(i){return[(i[0]+i[1]+i[2])/3/255*100]},_a}var xa,eh;function gD(){if(eh)return xa;eh=1;let t=Rh();function e(){let s={},a=Object.keys(t);for(let l=a.length,c=0;c<l;c++)s[a[c]]={distance:-1,parent:null};return s}function r(s){let a=e(),l=[s];for(a[s].distance=0;l.length;){let c=l.pop(),u=Object.keys(t[c]);for(let h=u.length,f=0;f<h;f++){let d=u[f],p=a[d];p.distance===-1&&(p.distance=a[c].distance+1,p.parent=c,l.unshift(d))}}return a}function n(s,a){return function(l){return a(s(l))}}function i(s,a){let l=[a[s].parent,s],c=t[a[s].parent][s],u=a[s].parent;for(;a[u].parent;)l.unshift(a[u].parent),c=n(t[a[u].parent][u],c),u=a[u].parent;return c.conversion=l,c}return xa=function(s){let a=r(s),l={},c=Object.keys(a);for(let u=c.length,h=0;h<u;h++){let f=c[h];a[f].parent!==null&&(l[f]=i(f,a))}return l},xa}var ka,th;function yD(){if(th)return ka;th=1;let t=Rh(),e=gD(),r={},n=Object.keys(t);function i(a){let l=function(...c){let u=c[0];return u==null?u:(u.length>1&&(c=u),a(c))};return"conversion"in a&&(l.conversion=a.conversion),l}function s(a){let l=function(...c){let u=c[0];if(u==null)return u;u.length>1&&(c=u);let h=a(c);if(typeof h=="object")for(let f=h.length,d=0;d<f;d++)h[d]=Math.round(h[d]);return h};return"conversion"in a&&(l.conversion=a.conversion),l}return n.forEach(a=>{r[a]={},Object.defineProperty(r[a],"channels",{value:t[a].channels}),Object.defineProperty(r[a],"labels",{value:t[a].labels});let l=e(a);Object.keys(l).forEach(u=>{let h=l[u];r[a][u]=s(h),r[a][u].raw=i(h)})}),ka=r,ka}Ss.exports;var rh;function bD(){return rh||(rh=1,(function(t){let e=(h,f)=>(...d)=>`\x1B[${h(...d)+f}m`,r=(h,f)=>(...d)=>{let p=h(...d);return`\x1B[${38+f};5;${p}m`},n=(h,f)=>(...d)=>{let p=h(...d);return`\x1B[${38+f};2;${p[0]};${p[1]};${p[2]}m`},i=h=>h,s=(h,f,d)=>[h,f,d],a=(h,f,d)=>{Object.defineProperty(h,f,{get:()=>{let p=d();return Object.defineProperty(h,f,{value:p,enumerable:!0,configurable:!0}),p},enumerable:!0,configurable:!0})},l,c=(h,f,d,p)=>{l===void 0&&(l=yD());let m=p?10:0,g={};for(let[y,b]of Object.entries(l)){let D=y==="ansi16"?"ansi":y;y===f?g[D]=h(d,m):typeof b=="object"&&(g[D]=h(b[f],m))}return g};function u(){let h=new Map,f={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};f.color.gray=f.color.blackBright,f.bgColor.bgGray=f.bgColor.bgBlackBright,f.color.grey=f.color.blackBright,f.bgColor.bgGrey=f.bgColor.bgBlackBright;for(let[d,p]of Object.entries(f)){for(let[m,g]of Object.entries(p))f[m]={open:`\x1B[${g[0]}m`,close:`\x1B[${g[1]}m`},p[m]=f[m],h.set(g[0],g[1]);Object.defineProperty(f,d,{value:p,enumerable:!1})}return Object.defineProperty(f,"codes",{value:h,enumerable:!1}),f.color.close="\x1B[39m",f.bgColor.close="\x1B[49m",a(f.color,"ansi",()=>c(e,"ansi16",i,!1)),a(f.color,"ansi256",()=>c(r,"ansi256",i,!1)),a(f.color,"ansi16m",()=>c(n,"rgb",s,!1)),a(f.bgColor,"ansi",()=>c(e,"ansi16",i,!0)),a(f.bgColor,"ansi256",()=>c(r,"ansi256",i,!0)),a(f.bgColor,"ansi16m",()=>c(n,"rgb",s,!0)),f}Object.defineProperty(t,"exports",{enumerable:!0,get:u})})(Ss)),Ss.exports}var Fa,nh;function vD(){if(nh)return Fa;nh=1;let t=Ys(),e=Ih(),r=bD(),n=new Set(["\x1B","\x9B"]),i=39,s="\x07",a="[",l="]",c="m",u=`${l}8;;`,h=y=>`${n.values().next().value}${a}${y}${c}`,f=y=>`${n.values().next().value}${u}${y}${s}`,d=y=>y.split(" ").map(b=>t(b)),p=(y,b,D)=>{let v=[...b],S=!1,C=!1,x=t(e(y[y.length-1]));for(let[_,B]of v.entries()){let w=t(B);if(x+w<=D?y[y.length-1]+=B:(y.push(B),x=0),n.has(B)&&(S=!0,C=v.slice(_+1).join("").startsWith(u)),S){C?B===s&&(S=!1,C=!1):B===c&&(S=!1);continue}x+=w,x===D&&_<v.length-1&&(y.push(""),x=0)}!x&&y[y.length-1].length>0&&y.length>1&&(y[y.length-2]+=y.pop())},m=y=>{let b=y.split(" "),D=b.length;for(;D>0&&!(t(b[D-1])>0);)D--;return D===b.length?y:b.slice(0,D).join(" ")+b.slice(D).join("")},g=(y,b,D={})=>{if(D.trim!==!1&&y.trim()==="")return"";let v="",S,C,x=d(y),_=[""];for(let[w,E]of y.split(" ").entries()){D.trim!==!1&&(_[_.length-1]=_[_.length-1].trimStart());let P=t(_[_.length-1]);if(w!==0&&(P>=b&&(D.wordWrap===!1||D.trim===!1)&&(_.push(""),P=0),(P>0||D.trim===!1)&&(_[_.length-1]+=" ",P++)),D.hard&&x[w]>b){let q=b-P,W=1+Math.floor((x[w]-q-1)/b);Math.floor((x[w]-1)/b)<W&&_.push(""),p(_,E,b);continue}if(P+x[w]>b&&P>0&&x[w]>0){if(D.wordWrap===!1&&P<b){p(_,E,b);continue}_.push("")}if(P+x[w]>b&&D.wordWrap===!1){p(_,E,b);continue}_[_.length-1]+=E}D.trim!==!1&&(_=_.map(m));let B=[..._.join(`
145
+ `+e).trimEnd()}var Ts=class{constructor(e=0){this.nextId=e}next(){let e=this.nextId;return this.nextId++,e}};function eD(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var fs={exports:{}},hs={exports:{}},wa,Vf;function tD(){return Vf||(Vf=1,wa=({onlyFirst:t=!1}={})=>{let e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(e,t?void 0:"g")}),wa}var Sa,Wf;function Rh(){if(Wf)return Sa;Wf=1;let t=tD();return Sa=e=>typeof e=="string"?e.replace(t(),""):e,Sa}var ps={exports:{}},Gf;function rD(){if(Gf)return ps.exports;Gf=1;let t=e=>Number.isNaN(e)?!1:e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141);return ps.exports=t,ps.exports.default=t,ps.exports}var Ca,Zf;function nD(){return Zf||(Zf=1,Ca=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}),Ca}var Kf;function Ys(){if(Kf)return hs.exports;Kf=1;let t=Rh(),e=rD(),r=nD(),n=i=>{if(typeof i!="string"||i.length===0||(i=t(i),i.length===0))return 0;i=i.replace(r()," ");let s=0;for(let a=0;a<i.length;a++){let l=i.codePointAt(a);l<=31||l>=127&&l<=159||l>=768&&l<=879||(l>65535&&a++,s+=e(l)?2:1)}return s};return hs.exports=n,hs.exports.default=n,hs.exports}var ms={exports:{}},Hf;function iD(){if(Hf)return ms.exports;Hf=1;let t=Ys(),e=r=>{let n=0;for(let i of r.split(`
146
+ `))n=Math.max(n,t(i));return n};return ms.exports=e,ms.exports.default=e,ms.exports}var gs={exports:{}},sD={topLeft:"\u250C",topRight:"\u2510",bottomRight:"\u2518",bottomLeft:"\u2514",vertical:"\u2502",horizontal:"\u2500"},oD={topLeft:"\u2554",topRight:"\u2557",bottomRight:"\u255D",bottomLeft:"\u255A",vertical:"\u2551",horizontal:"\u2550"},aD={topLeft:"\u256D",topRight:"\u256E",bottomRight:"\u256F",bottomLeft:"\u2570",vertical:"\u2502",horizontal:"\u2500"},lD={topLeft:"\u250F",topRight:"\u2513",bottomRight:"\u251B",bottomLeft:"\u2517",vertical:"\u2503",horizontal:"\u2501"},cD={topLeft:"\u2553",topRight:"\u2556",bottomRight:"\u255C",bottomLeft:"\u2559",vertical:"\u2551",horizontal:"\u2500"},uD={topLeft:"\u2552",topRight:"\u2555",bottomRight:"\u255B",bottomLeft:"\u2558",vertical:"\u2502",horizontal:"\u2550"},dD={topLeft:"+",topRight:"+",bottomRight:"+",bottomLeft:"+",vertical:"|",horizontal:"-"},fD={single:sD,double:oD,round:aD,bold:lD,singleDouble:cD,doubleSingle:uD,classic:dD},Yf;function hD(){if(Yf)return gs.exports;Yf=1;let t=fD;return gs.exports=t,gs.exports.default=t,gs.exports}var ys={exports:{}},Jf;function pD(){if(Jf)return ys.exports;Jf=1;let t=/[\p{Lu}]/u,e=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,i=/[_.\- ]+/,s=new RegExp("^"+i.source),a=new RegExp(i.source+n.source,"gu"),l=new RegExp("\\d+"+n.source,"gu"),c=(d,p,m)=>{let g=!1,y=!1,b=!1;for(let D=0;D<d.length;D++){let v=d[D];g&&t.test(v)?(d=d.slice(0,D)+"-"+d.slice(D),g=!1,b=y,y=!0,D++):y&&b&&e.test(v)?(d=d.slice(0,D-1)+"-"+d.slice(D-1),b=y,y=!1,g=!0):(g=p(v)===v&&m(v)!==v,b=y,y=m(v)===v&&p(v)!==v)}return d},u=(d,p)=>(r.lastIndex=0,d.replace(r,m=>p(m))),h=(d,p)=>(a.lastIndex=0,l.lastIndex=0,d.replace(a,(m,g)=>p(g)).replace(l,m=>p(m))),f=(d,p)=>{if(!(typeof d=="string"||Array.isArray(d)))throw new TypeError("Expected the input to be `string | string[]`");if(p={pascalCase:!1,preserveConsecutiveUppercase:!1,...p},Array.isArray(d)?d=d.map(b=>b.trim()).filter(b=>b.length).join("-"):d=d.trim(),d.length===0)return"";let m=p.locale===!1?b=>b.toLowerCase():b=>b.toLocaleLowerCase(p.locale),g=p.locale===!1?b=>b.toUpperCase():b=>b.toLocaleUpperCase(p.locale);return d.length===1?p.pascalCase?g(d):m(d):(d!==m(d)&&(d=c(d,m,g)),d=d.replace(s,""),p.preserveConsecutiveUppercase?d=u(d,m):d=m(d),p.pascalCase&&(d=g(d.charAt(0))+d.slice(1)),h(d,g))};return ys.exports=f,ys.exports.default=f,ys.exports}var Ea,Qf;function mD(){if(Qf)return Ea;Qf=1;let t=Ys();function e(i,s){if(!i)return i;s=s||{};let a=s.align||"center";if(a==="left")return i;let l=s.split||`
147
+ `,c=s.pad||" ",u=a!=="right"?r:n,h=!1;Array.isArray(i)||(h=!0,i=String(i).split(l));let f,d=0;return i=i.map(function(p){return p=String(p),f=t(p),d=Math.max(f,d),{str:p,width:f}}).map(function(p){return new Array(u(d,p.width)+1).join(c)+p.str}),h?i.join(l):i}e.left=function(s){return e(s,{align:"left"})},e.center=function(s){return e(s,{align:"center"})},e.right=function(s){return e(s,{align:"right"})},Ea=e;function r(i,s){return Math.floor((i-s)/2)}function n(i,s){return i-s}return Ea}var Ss={exports:{}},_a,Xf;function gD(){return Xf||(Xf=1,_a={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),_a}var xa,eh;function Mh(){if(eh)return xa;eh=1;let t=gD(),e={};for(let i of Object.keys(t))e[t[i]]=i;let r={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};xa=r;for(let i of Object.keys(r)){if(!("channels"in r[i]))throw new Error("missing channels property: "+i);if(!("labels"in r[i]))throw new Error("missing channel labels property: "+i);if(r[i].labels.length!==r[i].channels)throw new Error("channel and label counts mismatch: "+i);let{channels:s,labels:a}=r[i];delete r[i].channels,delete r[i].labels,Object.defineProperty(r[i],"channels",{value:s}),Object.defineProperty(r[i],"labels",{value:a})}r.rgb.hsl=function(i){let s=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.min(s,a,l),u=Math.max(s,a,l),h=u-c,f,d;u===c?f=0:s===u?f=(a-l)/h:a===u?f=2+(l-s)/h:l===u&&(f=4+(s-a)/h),f=Math.min(f*60,360),f<0&&(f+=360);let p=(c+u)/2;return u===c?d=0:p<=.5?d=h/(u+c):d=h/(2-u-c),[f,d*100,p*100]},r.rgb.hsv=function(i){let s,a,l,c,u,h=i[0]/255,f=i[1]/255,d=i[2]/255,p=Math.max(h,f,d),m=p-Math.min(h,f,d),g=function(y){return(p-y)/6/m+1/2};return m===0?(c=0,u=0):(u=m/p,s=g(h),a=g(f),l=g(d),h===p?c=l-a:f===p?c=1/3+s-l:d===p&&(c=2/3+a-s),c<0?c+=1:c>1&&(c-=1)),[c*360,u*100,p*100]},r.rgb.hwb=function(i){let s=i[0],a=i[1],l=i[2],c=r.rgb.hsl(i)[0],u=1/255*Math.min(s,Math.min(a,l));return l=1-1/255*Math.max(s,Math.max(a,l)),[c,u*100,l*100]},r.rgb.cmyk=function(i){let s=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.min(1-s,1-a,1-l),u=(1-s-c)/(1-c)||0,h=(1-a-c)/(1-c)||0,f=(1-l-c)/(1-c)||0;return[u*100,h*100,f*100,c*100]};function n(i,s){return(i[0]-s[0])**2+(i[1]-s[1])**2+(i[2]-s[2])**2}return r.rgb.keyword=function(i){let s=e[i];if(s)return s;let a=1/0,l;for(let c of Object.keys(t)){let u=t[c],h=n(i,u);h<a&&(a=h,l=c)}return l},r.keyword.rgb=function(i){return t[i]},r.rgb.xyz=function(i){let s=i[0]/255,a=i[1]/255,l=i[2]/255;s=s>.04045?((s+.055)/1.055)**2.4:s/12.92,a=a>.04045?((a+.055)/1.055)**2.4:a/12.92,l=l>.04045?((l+.055)/1.055)**2.4:l/12.92;let c=s*.4124+a*.3576+l*.1805,u=s*.2126+a*.7152+l*.0722,h=s*.0193+a*.1192+l*.9505;return[c*100,u*100,h*100]},r.rgb.lab=function(i){let s=r.rgb.xyz(i),a=s[0],l=s[1],c=s[2];a/=95.047,l/=100,c/=108.883,a=a>.008856?a**(1/3):7.787*a+16/116,l=l>.008856?l**(1/3):7.787*l+16/116,c=c>.008856?c**(1/3):7.787*c+16/116;let u=116*l-16,h=500*(a-l),f=200*(l-c);return[u,h,f]},r.hsl.rgb=function(i){let s=i[0]/360,a=i[1]/100,l=i[2]/100,c,u,h;if(a===0)return h=l*255,[h,h,h];l<.5?c=l*(1+a):c=l+a-l*a;let f=2*l-c,d=[0,0,0];for(let p=0;p<3;p++)u=s+1/3*-(p-1),u<0&&u++,u>1&&u--,6*u<1?h=f+(c-f)*6*u:2*u<1?h=c:3*u<2?h=f+(c-f)*(2/3-u)*6:h=f,d[p]=h*255;return d},r.hsl.hsv=function(i){let s=i[0],a=i[1]/100,l=i[2]/100,c=a,u=Math.max(l,.01);l*=2,a*=l<=1?l:2-l,c*=u<=1?u:2-u;let h=(l+a)/2,f=l===0?2*c/(u+c):2*a/(l+a);return[s,f*100,h*100]},r.hsv.rgb=function(i){let s=i[0]/60,a=i[1]/100,l=i[2]/100,c=Math.floor(s)%6,u=s-Math.floor(s),h=255*l*(1-a),f=255*l*(1-a*u),d=255*l*(1-a*(1-u));switch(l*=255,c){case 0:return[l,d,h];case 1:return[f,l,h];case 2:return[h,l,d];case 3:return[h,f,l];case 4:return[d,h,l];case 5:return[l,h,f]}},r.hsv.hsl=function(i){let s=i[0],a=i[1]/100,l=i[2]/100,c=Math.max(l,.01),u,h;h=(2-a)*l;let f=(2-a)*c;return u=a*c,u/=f<=1?f:2-f,u=u||0,h/=2,[s,u*100,h*100]},r.hwb.rgb=function(i){let s=i[0]/360,a=i[1]/100,l=i[2]/100,c=a+l,u;c>1&&(a/=c,l/=c);let h=Math.floor(6*s),f=1-l;u=6*s-h,(h&1)!==0&&(u=1-u);let d=a+u*(f-a),p,m,g;switch(h){default:case 6:case 0:p=f,m=d,g=a;break;case 1:p=d,m=f,g=a;break;case 2:p=a,m=f,g=d;break;case 3:p=a,m=d,g=f;break;case 4:p=d,m=a,g=f;break;case 5:p=f,m=a,g=d;break}return[p*255,m*255,g*255]},r.cmyk.rgb=function(i){let s=i[0]/100,a=i[1]/100,l=i[2]/100,c=i[3]/100,u=1-Math.min(1,s*(1-c)+c),h=1-Math.min(1,a*(1-c)+c),f=1-Math.min(1,l*(1-c)+c);return[u*255,h*255,f*255]},r.xyz.rgb=function(i){let s=i[0]/100,a=i[1]/100,l=i[2]/100,c,u,h;return c=s*3.2406+a*-1.5372+l*-.4986,u=s*-.9689+a*1.8758+l*.0415,h=s*.0557+a*-.204+l*1.057,c=c>.0031308?1.055*c**(1/2.4)-.055:c*12.92,u=u>.0031308?1.055*u**(1/2.4)-.055:u*12.92,h=h>.0031308?1.055*h**(1/2.4)-.055:h*12.92,c=Math.min(Math.max(0,c),1),u=Math.min(Math.max(0,u),1),h=Math.min(Math.max(0,h),1),[c*255,u*255,h*255]},r.xyz.lab=function(i){let s=i[0],a=i[1],l=i[2];s/=95.047,a/=100,l/=108.883,s=s>.008856?s**(1/3):7.787*s+16/116,a=a>.008856?a**(1/3):7.787*a+16/116,l=l>.008856?l**(1/3):7.787*l+16/116;let c=116*a-16,u=500*(s-a),h=200*(a-l);return[c,u,h]},r.lab.xyz=function(i){let s=i[0],a=i[1],l=i[2],c,u,h;u=(s+16)/116,c=a/500+u,h=u-l/200;let f=u**3,d=c**3,p=h**3;return u=f>.008856?f:(u-16/116)/7.787,c=d>.008856?d:(c-16/116)/7.787,h=p>.008856?p:(h-16/116)/7.787,c*=95.047,u*=100,h*=108.883,[c,u,h]},r.lab.lch=function(i){let s=i[0],a=i[1],l=i[2],c;c=Math.atan2(l,a)*360/2/Math.PI,c<0&&(c+=360);let h=Math.sqrt(a*a+l*l);return[s,h,c]},r.lch.lab=function(i){let s=i[0],a=i[1],c=i[2]/360*2*Math.PI,u=a*Math.cos(c),h=a*Math.sin(c);return[s,u,h]},r.rgb.ansi16=function(i,s=null){let[a,l,c]=i,u=s===null?r.rgb.hsv(i)[2]:s;if(u=Math.round(u/50),u===0)return 30;let h=30+(Math.round(c/255)<<2|Math.round(l/255)<<1|Math.round(a/255));return u===2&&(h+=60),h},r.hsv.ansi16=function(i){return r.rgb.ansi16(r.hsv.rgb(i),i[2])},r.rgb.ansi256=function(i){let s=i[0],a=i[1],l=i[2];return s===a&&a===l?s<8?16:s>248?231:Math.round((s-8)/247*24)+232:16+36*Math.round(s/255*5)+6*Math.round(a/255*5)+Math.round(l/255*5)},r.ansi16.rgb=function(i){let s=i%10;if(s===0||s===7)return i>50&&(s+=3.5),s=s/10.5*255,[s,s,s];let a=(~~(i>50)+1)*.5,l=(s&1)*a*255,c=(s>>1&1)*a*255,u=(s>>2&1)*a*255;return[l,c,u]},r.ansi256.rgb=function(i){if(i>=232){let u=(i-232)*10+8;return[u,u,u]}i-=16;let s,a=Math.floor(i/36)/5*255,l=Math.floor((s=i%36)/6)/5*255,c=s%6/5*255;return[a,l,c]},r.rgb.hex=function(i){let a=(((Math.round(i[0])&255)<<16)+((Math.round(i[1])&255)<<8)+(Math.round(i[2])&255)).toString(16).toUpperCase();return"000000".substring(a.length)+a},r.hex.rgb=function(i){let s=i.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!s)return[0,0,0];let a=s[0];s[0].length===3&&(a=a.split("").map(f=>f+f).join(""));let l=parseInt(a,16),c=l>>16&255,u=l>>8&255,h=l&255;return[c,u,h]},r.rgb.hcg=function(i){let s=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.max(Math.max(s,a),l),u=Math.min(Math.min(s,a),l),h=c-u,f,d;return h<1?f=u/(1-h):f=0,h<=0?d=0:c===s?d=(a-l)/h%6:c===a?d=2+(l-s)/h:d=4+(s-a)/h,d/=6,d%=1,[d*360,h*100,f*100]},r.hsl.hcg=function(i){let s=i[1]/100,a=i[2]/100,l=a<.5?2*s*a:2*s*(1-a),c=0;return l<1&&(c=(a-.5*l)/(1-l)),[i[0],l*100,c*100]},r.hsv.hcg=function(i){let s=i[1]/100,a=i[2]/100,l=s*a,c=0;return l<1&&(c=(a-l)/(1-l)),[i[0],l*100,c*100]},r.hcg.rgb=function(i){let s=i[0]/360,a=i[1]/100,l=i[2]/100;if(a===0)return[l*255,l*255,l*255];let c=[0,0,0],u=s%1*6,h=u%1,f=1-h,d=0;switch(Math.floor(u)){case 0:c[0]=1,c[1]=h,c[2]=0;break;case 1:c[0]=f,c[1]=1,c[2]=0;break;case 2:c[0]=0,c[1]=1,c[2]=h;break;case 3:c[0]=0,c[1]=f,c[2]=1;break;case 4:c[0]=h,c[1]=0,c[2]=1;break;default:c[0]=1,c[1]=0,c[2]=f}return d=(1-a)*l,[(a*c[0]+d)*255,(a*c[1]+d)*255,(a*c[2]+d)*255]},r.hcg.hsv=function(i){let s=i[1]/100,a=i[2]/100,l=s+a*(1-s),c=0;return l>0&&(c=s/l),[i[0],c*100,l*100]},r.hcg.hsl=function(i){let s=i[1]/100,l=i[2]/100*(1-s)+.5*s,c=0;return l>0&&l<.5?c=s/(2*l):l>=.5&&l<1&&(c=s/(2*(1-l))),[i[0],c*100,l*100]},r.hcg.hwb=function(i){let s=i[1]/100,a=i[2]/100,l=s+a*(1-s);return[i[0],(l-s)*100,(1-l)*100]},r.hwb.hcg=function(i){let s=i[1]/100,l=1-i[2]/100,c=l-s,u=0;return c<1&&(u=(l-c)/(1-c)),[i[0],c*100,u*100]},r.apple.rgb=function(i){return[i[0]/65535*255,i[1]/65535*255,i[2]/65535*255]},r.rgb.apple=function(i){return[i[0]/255*65535,i[1]/255*65535,i[2]/255*65535]},r.gray.rgb=function(i){return[i[0]/100*255,i[0]/100*255,i[0]/100*255]},r.gray.hsl=function(i){return[0,0,i[0]]},r.gray.hsv=r.gray.hsl,r.gray.hwb=function(i){return[0,100,i[0]]},r.gray.cmyk=function(i){return[0,0,0,i[0]]},r.gray.lab=function(i){return[i[0],0,0]},r.gray.hex=function(i){let s=Math.round(i[0]/100*255)&255,l=((s<<16)+(s<<8)+s).toString(16).toUpperCase();return"000000".substring(l.length)+l},r.rgb.gray=function(i){return[(i[0]+i[1]+i[2])/3/255*100]},xa}var ka,th;function yD(){if(th)return ka;th=1;let t=Mh();function e(){let s={},a=Object.keys(t);for(let l=a.length,c=0;c<l;c++)s[a[c]]={distance:-1,parent:null};return s}function r(s){let a=e(),l=[s];for(a[s].distance=0;l.length;){let c=l.pop(),u=Object.keys(t[c]);for(let h=u.length,f=0;f<h;f++){let d=u[f],p=a[d];p.distance===-1&&(p.distance=a[c].distance+1,p.parent=c,l.unshift(d))}}return a}function n(s,a){return function(l){return a(s(l))}}function i(s,a){let l=[a[s].parent,s],c=t[a[s].parent][s],u=a[s].parent;for(;a[u].parent;)l.unshift(a[u].parent),c=n(t[a[u].parent][u],c),u=a[u].parent;return c.conversion=l,c}return ka=function(s){let a=r(s),l={},c=Object.keys(a);for(let u=c.length,h=0;h<u;h++){let f=c[h];a[f].parent!==null&&(l[f]=i(f,a))}return l},ka}var Fa,rh;function bD(){if(rh)return Fa;rh=1;let t=Mh(),e=yD(),r={},n=Object.keys(t);function i(a){let l=function(...c){let u=c[0];return u==null?u:(u.length>1&&(c=u),a(c))};return"conversion"in a&&(l.conversion=a.conversion),l}function s(a){let l=function(...c){let u=c[0];if(u==null)return u;u.length>1&&(c=u);let h=a(c);if(typeof h=="object")for(let f=h.length,d=0;d<f;d++)h[d]=Math.round(h[d]);return h};return"conversion"in a&&(l.conversion=a.conversion),l}return n.forEach(a=>{r[a]={},Object.defineProperty(r[a],"channels",{value:t[a].channels}),Object.defineProperty(r[a],"labels",{value:t[a].labels});let l=e(a);Object.keys(l).forEach(u=>{let h=l[u];r[a][u]=s(h),r[a][u].raw=i(h)})}),Fa=r,Fa}Ss.exports;var nh;function vD(){return nh||(nh=1,(function(t){let e=(h,f)=>(...d)=>`\x1B[${h(...d)+f}m`,r=(h,f)=>(...d)=>{let p=h(...d);return`\x1B[${38+f};5;${p}m`},n=(h,f)=>(...d)=>{let p=h(...d);return`\x1B[${38+f};2;${p[0]};${p[1]};${p[2]}m`},i=h=>h,s=(h,f,d)=>[h,f,d],a=(h,f,d)=>{Object.defineProperty(h,f,{get:()=>{let p=d();return Object.defineProperty(h,f,{value:p,enumerable:!0,configurable:!0}),p},enumerable:!0,configurable:!0})},l,c=(h,f,d,p)=>{l===void 0&&(l=bD());let m=p?10:0,g={};for(let[y,b]of Object.entries(l)){let D=y==="ansi16"?"ansi":y;y===f?g[D]=h(d,m):typeof b=="object"&&(g[D]=h(b[f],m))}return g};function u(){let h=new Map,f={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};f.color.gray=f.color.blackBright,f.bgColor.bgGray=f.bgColor.bgBlackBright,f.color.grey=f.color.blackBright,f.bgColor.bgGrey=f.bgColor.bgBlackBright;for(let[d,p]of Object.entries(f)){for(let[m,g]of Object.entries(p))f[m]={open:`\x1B[${g[0]}m`,close:`\x1B[${g[1]}m`},p[m]=f[m],h.set(g[0],g[1]);Object.defineProperty(f,d,{value:p,enumerable:!1})}return Object.defineProperty(f,"codes",{value:h,enumerable:!1}),f.color.close="\x1B[39m",f.bgColor.close="\x1B[49m",a(f.color,"ansi",()=>c(e,"ansi16",i,!1)),a(f.color,"ansi256",()=>c(r,"ansi256",i,!1)),a(f.color,"ansi16m",()=>c(n,"rgb",s,!1)),a(f.bgColor,"ansi",()=>c(e,"ansi16",i,!0)),a(f.bgColor,"ansi256",()=>c(r,"ansi256",i,!0)),a(f.bgColor,"ansi16m",()=>c(n,"rgb",s,!0)),f}Object.defineProperty(t,"exports",{enumerable:!0,get:u})})(Ss)),Ss.exports}var Pa,ih;function DD(){if(ih)return Pa;ih=1;let t=Ys(),e=Rh(),r=vD(),n=new Set(["\x1B","\x9B"]),i=39,s="\x07",a="[",l="]",c="m",u=`${l}8;;`,h=y=>`${n.values().next().value}${a}${y}${c}`,f=y=>`${n.values().next().value}${u}${y}${s}`,d=y=>y.split(" ").map(b=>t(b)),p=(y,b,D)=>{let v=[...b],S=!1,C=!1,x=t(e(y[y.length-1]));for(let[_,B]of v.entries()){let w=t(B);if(x+w<=D?y[y.length-1]+=B:(y.push(B),x=0),n.has(B)&&(S=!0,C=v.slice(_+1).join("").startsWith(u)),S){C?B===s&&(S=!1,C=!1):B===c&&(S=!1);continue}x+=w,x===D&&_<v.length-1&&(y.push(""),x=0)}!x&&y[y.length-1].length>0&&y.length>1&&(y[y.length-2]+=y.pop())},m=y=>{let b=y.split(" "),D=b.length;for(;D>0&&!(t(b[D-1])>0);)D--;return D===b.length?y:b.slice(0,D).join(" ")+b.slice(D).join("")},g=(y,b,D={})=>{if(D.trim!==!1&&y.trim()==="")return"";let v="",S,C,x=d(y),_=[""];for(let[w,E]of y.split(" ").entries()){D.trim!==!1&&(_[_.length-1]=_[_.length-1].trimStart());let P=t(_[_.length-1]);if(w!==0&&(P>=b&&(D.wordWrap===!1||D.trim===!1)&&(_.push(""),P=0),(P>0||D.trim===!1)&&(_[_.length-1]+=" ",P++)),D.hard&&x[w]>b){let q=b-P,W=1+Math.floor((x[w]-q-1)/b);Math.floor((x[w]-1)/b)<W&&_.push(""),p(_,E,b);continue}if(P+x[w]>b&&P>0&&x[w]>0){if(D.wordWrap===!1&&P<b){p(_,E,b);continue}_.push("")}if(P+x[w]>b&&D.wordWrap===!1){p(_,E,b);continue}_[_.length-1]+=E}D.trim!==!1&&(_=_.map(m));let B=[..._.join(`
148
148
  `)];for(let[w,E]of B.entries()){if(v+=E,n.has(E)){let{groups:q}=new RegExp(`(?:\\${a}(?<code>\\d+)m|\\${u}(?<uri>.*)${s})`).exec(B.slice(w).join(""))||{groups:{}};if(q.code!==void 0){let W=Number.parseFloat(q.code);S=W===i?void 0:W}else q.uri!==void 0&&(C=q.uri.length===0?void 0:q.uri)}let P=r.codes.get(Number(S));B[w+1]===`
149
149
  `?(C&&(v+=f("")),S&&P&&(v+=h(P))):E===`
150
- `&&(S&&P&&(v+=h(S)),C&&(v+=f(C)))}return v};return Fa=(y,b,D)=>String(y).normalize().replace(/\r\n/g,`
150
+ `&&(S&&P&&(v+=h(S)),C&&(v+=f(C)))}return v};return Pa=(y,b,D)=>String(y).normalize().replace(/\r\n/g,`
151
151
  `).split(`
152
152
  `).map(v=>g(v,b,D)).join(`
153
- `),Fa}var ih;function DD(){if(ih)return fs.exports;ih=1;let t=Ys(),e=I.default,r=nD(),n=fD(),i=hD(),s=pD(),a=vD(),l=`
153
+ `),Pa}var sh;function wD(){if(sh)return fs.exports;sh=1;let t=Ys(),e=I.default,r=iD(),n=hD(),i=pD(),s=mD(),a=DD(),l=`
154
154
  `,c=" ",u=()=>{let{env:D,stdout:v,stderr:S}=process;return v&&v.columns?v.columns:S&&S.columns?S.columns:D.COLUMNS?Number.parseInt(D.COLUMNS,10):80},h=D=>typeof D=="number"?{top:D,right:D*3,bottom:D,left:D*3}:{top:0,right:0,bottom:0,left:0,...D},f=D=>{let v=["topLeft","topRight","bottomRight","bottomLeft","vertical","horizontal"],S;if(typeof D=="string"){if(S=n[D],!S)throw new TypeError(`Invalid border style: ${D}`)}else{for(let C of v)if(!D[C]||typeof D[C]!="string")throw new TypeError(`Invalid border style: ${C}`);S=D}return S},d=(D,v,S)=>{let C="",x=t(D);switch(S){case"left":C=D+v.slice(x);break;case"right":C=v.slice(x)+D;break;default:v=v.slice(x),v.length%2===1?(v=v.slice(Math.floor(v.length/2)),C=v.slice(1)+D+v):(v=v.slice(v.length/2),C=v+D+v);break}return C},p=(D,v,S,C)=>{D=s(D,{align:C});let x=D.split(l),_=r(D),B=S-v.left-v.right;if(_>B){let P=[];for(let q of x){let W=a(q,B,{hard:!0}),pe=s(W,{align:C}).split(`
155
- `),me=Math.max(...pe.map(ve=>t(ve)));for(let ve of pe){let J;switch(C){case"center":J=c.repeat((B-me)/2)+ve;break;case"right":J=c.repeat(B-me)+ve;break;default:J=ve;break}P.push(J)}}x=P}C==="center"&&_<B?x=x.map(P=>c.repeat((B-_)/2)+P):C==="right"&&_<B&&(x=x.map(P=>c.repeat(B-_)+P));let w=c.repeat(v.left),E=c.repeat(v.right);return x=x.map(P=>w+P+E),x=x.map(P=>{if(S-t(P)>0)switch(C){case"center":return P+c.repeat(S-t(P));case"right":return P+c.repeat(S-t(P));default:return P+c.repeat(S-t(P))}return P}),v.top>0&&(x=new Array(v.top).fill(c.repeat(S)).concat(x)),v.bottom>0&&(x=x.concat(new Array(v.bottom).fill(c.repeat(S)))),x.join(l)},m=D=>D.match(/^#(?:[0-f]{3}){1,2}$/i),g=D=>typeof D=="string"&&(e[D]||m(D)),y=D=>m(D)?e.hex(D):e[D],b=D=>m(D)?e.bgHex(D):e[i(["bg",D])];return fs.exports=(D,v)=>{v={padding:0,borderStyle:"single",dimBorder:!1,textAlignment:"left",float:"left",titleAlignment:"left",...v},v.align&&(v.textAlignment=v.align);let S=2;if(v.borderColor&&!g(v.borderColor))throw new Error(`${v.borderColor} is not a valid borderColor`);if(v.backgroundColor&&!g(v.backgroundColor))throw new Error(`${v.backgroundColor} is not a valid backgroundColor`);let C=f(v.borderStyle),x=h(v.padding),_=h(v.margin),B=ge=>{let N=v.borderColor?y(v.borderColor)(ge):ge;return v.dimBorder?e.dim(N):N},w=ge=>v.backgroundColor?b(v.backgroundColor)(ge):ge,E=u()-1,P=r(a(D,E-S,{hard:!0,trim:!1}))+x.left+x.right,q=v.title&&v.title.slice(0,E-4-_.left-_.right);if(q&&(q=` ${q} `,t(q)>P&&(P=t(q))),_.left&&_.right&&P+S+_.left+_.right>E){let N=(E-P-S)/(_.left+_.right);_.left=Math.max(0,Math.floor(_.left*N)),_.right=Math.max(0,Math.floor(_.right*N))}P=Math.min(P,E-S-_.left-_.right),D=p(D,x,P,v.textAlignment);let W=c.repeat(_.left);if(v.float==="center"){let ge=Math.max((E-P-S)/2,0);W=c.repeat(ge)}else if(v.float==="right"){let ge=Math.max(E-P-_.right-S,0);W=c.repeat(ge)}let V=C.horizontal.repeat(P),pe=B(l.repeat(_.top)+W+C.topLeft+(q?d(q,V,v.titleAlignment):V)+C.topRight),me=B(W+C.bottomLeft+V+C.bottomRight+l.repeat(_.bottom)),ve=B(C.vertical),J=l,kt=D.split(l).map(ge=>W+ve+w(ge)+ve).join(J);return pe+J+kt+J+me},fs.exports._borderStyles=n,fs.exports}var wD=DD(),SD=Xv(wD);function Ir(t,e,r){return Ee(I.default.redBright(t)+`
155
+ `),me=Math.max(...pe.map(ve=>t(ve)));for(let ve of pe){let J;switch(C){case"center":J=c.repeat((B-me)/2)+ve;break;case"right":J=c.repeat(B-me)+ve;break;default:J=ve;break}P.push(J)}}x=P}C==="center"&&_<B?x=x.map(P=>c.repeat((B-_)/2)+P):C==="right"&&_<B&&(x=x.map(P=>c.repeat(B-_)+P));let w=c.repeat(v.left),E=c.repeat(v.right);return x=x.map(P=>w+P+E),x=x.map(P=>{if(S-t(P)>0)switch(C){case"center":return P+c.repeat(S-t(P));case"right":return P+c.repeat(S-t(P));default:return P+c.repeat(S-t(P))}return P}),v.top>0&&(x=new Array(v.top).fill(c.repeat(S)).concat(x)),v.bottom>0&&(x=x.concat(new Array(v.bottom).fill(c.repeat(S)))),x.join(l)},m=D=>D.match(/^#(?:[0-f]{3}){1,2}$/i),g=D=>typeof D=="string"&&(e[D]||m(D)),y=D=>m(D)?e.hex(D):e[D],b=D=>m(D)?e.bgHex(D):e[i(["bg",D])];return fs.exports=(D,v)=>{v={padding:0,borderStyle:"single",dimBorder:!1,textAlignment:"left",float:"left",titleAlignment:"left",...v},v.align&&(v.textAlignment=v.align);let S=2;if(v.borderColor&&!g(v.borderColor))throw new Error(`${v.borderColor} is not a valid borderColor`);if(v.backgroundColor&&!g(v.backgroundColor))throw new Error(`${v.backgroundColor} is not a valid backgroundColor`);let C=f(v.borderStyle),x=h(v.padding),_=h(v.margin),B=ge=>{let N=v.borderColor?y(v.borderColor)(ge):ge;return v.dimBorder?e.dim(N):N},w=ge=>v.backgroundColor?b(v.backgroundColor)(ge):ge,E=u()-1,P=r(a(D,E-S,{hard:!0,trim:!1}))+x.left+x.right,q=v.title&&v.title.slice(0,E-4-_.left-_.right);if(q&&(q=` ${q} `,t(q)>P&&(P=t(q))),_.left&&_.right&&P+S+_.left+_.right>E){let N=(E-P-S)/(_.left+_.right);_.left=Math.max(0,Math.floor(_.left*N)),_.right=Math.max(0,Math.floor(_.right*N))}P=Math.min(P,E-S-_.left-_.right),D=p(D,x,P,v.textAlignment);let W=c.repeat(_.left);if(v.float==="center"){let ge=Math.max((E-P-S)/2,0);W=c.repeat(ge)}else if(v.float==="right"){let ge=Math.max(E-P-_.right-S,0);W=c.repeat(ge)}let V=C.horizontal.repeat(P),pe=B(l.repeat(_.top)+W+C.topLeft+(q?d(q,V,v.titleAlignment):V)+C.topRight),me=B(W+C.bottomLeft+V+C.bottomRight+l.repeat(_.bottom)),ve=B(C.vertical),J=l,kt=D.split(l).map(ge=>W+ve+w(ge)+ve).join(J);return pe+J+kt+J+me},fs.exports._borderStyles=n,fs.exports}var SD=wD(),CD=eD(SD);function Ir(t,e,r){return Ee(I.default.redBright(t)+`
156
156
 
157
- `+e,r)}function Ee(t,e){if(Yn.default.browser||Yn.default.env.LMS_NO_FANCY_ERRORS||(0,st.terminalSize)().columns<80){let r=new Error(t);return e===void 0?va(r,""):va(r,e),r}else{e!==void 0&&(t+=`
157
+ `+e,r)}function Ee(t,e){if(Yn.default.browser||Yn.default.env.LMS_NO_FANCY_ERRORS||(0,at.terminalSize)().columns<80){let r=new Error(t);return e===void 0?Da(r,""):Da(r,e),r}else{e!==void 0&&(t+=`
158
158
 
159
159
 
160
160
  `+I.default.bgWhite.black(" </> STACK TRACE ")+`
161
161
 
162
162
  `+I.default.gray(e));let r=new Error(`
163
- `+SD(t,{padding:1,margin:1,borderColor:"redBright",title:"Error"}));return Object.defineProperty(r,"lmstudioRawError",{value:t,enumerable:!1}),va(r,""),r}}var sh=new WeakMap;function j(t,...e){if(e.length+1!==t.length)throw new Error("text called with the wrong number of arguments.");let r=sh.get(t);r===void 0&&(r=BD(t),sh.set(t,r));for(let n=0;n<e.length;n++)if(typeof e[n]=="object")if(typeof e[n].stack=="string")r[n*2+1]=e[n].stack;else try{r[n*2+1]=JSON.stringify(e[n])}catch{r[n*2+1]="[Object failed to stringify]"}else r[n*2+1]=String(e[n]);return r.join("")}function CD(t){return t.replace(/^\n+/,"")}function ED(t){return t.replace(/[\n ]+$/,"")}function _D(t){return t.replace(/^ +/,"")}function xD(t){return t.replace(/ +$/,"")}function kD(t){let e=[],r=[];for(let n of t){let i=-1,s;for(;(s=n.indexOf(`
164
- `,i+1))!==-1;)r.push(n.substring(i+1,s)),e.push(r),r=[],i=s;r.push(n.substring(i+1))}return e.push(r),e}function FD(t){let e=0;for(let r of t)if(r===" ")e++;else return e;return 1/0}function PD(t){let e=t[0],r=FD(e);return r===1/0?t.length===1?1/0:e.length:r}function TD(t){let e=1/0;for(let r of t)e=Math.min(e,PD(r));return e}function AD(t,e){return t.length<e?"":t.slice(e)}function OD(t,e){for(let r of t)r[0]=AD(r[0],e)}function ID(t){if(t.length!==1)return!1;for(let e of t[0])if(e!==" ")return!1;return!0}function RD(t){let e=t.map(ID),r=[],n=[];for(let i=0;i<t.length;i++){if(e[i]){n.length!==0&&(r.push(n),n=[]);continue}if(n.length!==0){let s=xD(n[n.length-1]),a=_D(t[i][0]);n[n.length-1]=s+" "+a,n.push(...t[i].slice(1))}else n.push(...t[i])}return n.length!==0&&r.push(n),r}function MD(t){let e=[];if(t.length===0)return[""];e.push(...t[0]);for(let r=1;r<t.length;r++)e[e.length-1]+=`
163
+ `+CD(t,{padding:1,margin:1,borderColor:"redBright",title:"Error"}));return Object.defineProperty(r,"lmstudioRawError",{value:t,enumerable:!1}),Da(r,""),r}}var oh=new WeakMap;function j(t,...e){if(e.length+1!==t.length)throw new Error("text called with the wrong number of arguments.");let r=oh.get(t);r===void 0&&(r=LD(t),oh.set(t,r));for(let n=0;n<e.length;n++)if(typeof e[n]=="object")if(typeof e[n].stack=="string")r[n*2+1]=e[n].stack;else try{r[n*2+1]=JSON.stringify(e[n])}catch{r[n*2+1]="[Object failed to stringify]"}else r[n*2+1]=String(e[n]);return r.join("")}function ED(t){return t.replace(/^\n+/,"")}function _D(t){return t.replace(/[\n ]+$/,"")}function xD(t){return t.replace(/^ +/,"")}function kD(t){return t.replace(/ +$/,"")}function FD(t){let e=[],r=[];for(let n of t){let i=-1,s;for(;(s=n.indexOf(`
164
+ `,i+1))!==-1;)r.push(n.substring(i+1,s)),e.push(r),r=[],i=s;r.push(n.substring(i+1))}return e.push(r),e}function PD(t){let e=0;for(let r of t)if(r===" ")e++;else return e;return 1/0}function TD(t){let e=t[0],r=PD(e);return r===1/0?t.length===1?1/0:e.length:r}function AD(t){let e=1/0;for(let r of t)e=Math.min(e,TD(r));return e}function OD(t,e){return t.length<e?"":t.slice(e)}function ID(t,e){for(let r of t)r[0]=OD(r[0],e)}function RD(t){if(t.length!==1)return!1;for(let e of t[0])if(e!==" ")return!1;return!0}function MD(t){let e=t.map(RD),r=[],n=[];for(let i=0;i<t.length;i++){if(e[i]){n.length!==0&&(r.push(n),n=[]);continue}if(n.length!==0){let s=kD(n[n.length-1]),a=xD(t[i][0]);n[n.length-1]=s+" "+a,n.push(...t[i].slice(1))}else n.push(...t[i])}return n.length!==0&&r.push(n),r}function jD(t){let e=[];if(t.length===0)return[""];e.push(...t[0]);for(let r=1;r<t.length;r++)e[e.length-1]+=`
165
165
 
166
- `+t[r][0],e.push(...t[r].slice(1));return e}function jD(t){let e=[];for(let r=0;r<t.length;r++)e.push(t[r]),r<t.length-1&&e.push("");return e}function BD(t){let e=[...t];e[0]=CD(e[0]),e[e.length-1]=ED(e[e.length-1]);let r=kD(e),n=TD(r);OD(r,n);let i=RD(r);return jD(MD(i))}var As=class{constructor(e,r){this.data=e,this.mutable=r}_internalGetData(){return this.data}_internalToMutable(){return this.mutable?this:this.asMutableCopy()}asMutableCopy(){return this.create(this.cloneData(this.data),!0)}asImmutableCopy(){return this.mutable?this.create(this.cloneData(this.data),!1):this}guardMutable(){if(!this.mutable)throw new Error(j`
166
+ `+t[r][0],e.push(...t[r].slice(1));return e}function BD(t){let e=[];for(let r=0;r<t.length;r++)e.push(t[r]),r<t.length-1&&e.push("");return e}function LD(t){let e=[...t];e[0]=ED(e[0]),e[e.length-1]=_D(e[e.length-1]);let r=FD(e),n=AD(r);ID(r,n);let i=MD(r);return BD(jD(i))}var As=class{constructor(e,r){this.data=e,this.mutable=r}_internalGetData(){return this.data}_internalToMutable(){return this.mutable?this:this.asMutableCopy()}asMutableCopy(){return this.create(this.cloneData(this.data),!0)}asImmutableCopy(){return this.mutable?this.create(this.cloneData(this.data),!1):this}guardMutable(){if(!this.mutable)throw new Error(j`
167
167
  Cannot modify immutable ${this.getClassName()} instance. Use asMutableCopy() to get a
168
168
  mutable copy.
169
- `)}};var Ua=class t extends Ut{static{this.NOT_AVAILABLE=Ge.NOT_AVAILABLE}applyOptimisticUpdates(e){for(let r of this.queuedUpdates)[e]=r.updater(e);return e}updateOptimisticValue(e){let r=this.innerSignal.get();wt(r)&&this.setOuterSignal(this.applyOptimisticUpdates(r),e)}constructor(e,r,n,i){super(),this.writeUpstream=n,this.isWriteLoopRunning=!1,this.isSubscriptionHandledByWriteLoop=!1,this.queuedUpdates=[],this.currentEnsureAvailablePromise=null,[this.writeErrorEvent,this.emitWriteErrorEvent]=Jn.create(),[this.outerSignal,this.setOuterSignal]=ri.create(e,i),this.innerSignal=Ge.create(e,r,i),this.innerSignal.passiveSubscribeFull((s,a,l)=>{this.isSubscriptionHandledByWriteLoop||this.updateOptimisticValue(l)})}static create(e,r,n,i=(s,a)=>s===a){let s=new t(e,r,n,i),a=Wl(s.update.bind(s));return[s,a,(c,u)=>s.emitWriteErrorEvent({tags:c,error:u})]}static createWithoutInitialValue(e,r,n=(i,s)=>i===s){let i=(s,a)=>s===t.NOT_AVAILABLE||a===t.NOT_AVAILABLE?s===a:n(s,a);return t.create(t.NOT_AVAILABLE,e,r,i)}async update(e,r){let{promise:n,reject:i,resolve:s}=re();return this.queuedUpdates.push({updater:e,tags:r??[],resolve:s,reject:i}),this.updateOptimisticValue(),this.ensureWriteLoop(),n}ensureWriteLoop(){this.isWriteLoopRunning||this.writeLoop()}async writeLoop(){let e=this.innerSignal.subscribe(()=>{});for(this.isWriteLoopRunning=!0,this.isStale()&&await this.innerSignal.pull();this.queuedUpdates.length>0;){let r=this.queuedUpdates.length,n=c=>{let u=[];for(let h=0;h<r;h++){let[f,d]=this.queuedUpdates[h].updater(c);c=f,u.push(...d)}return[c,u]},i=()=>{for(let c=0;c<r;c++)this.queuedUpdates[c].resolve()},s=c=>{for(let u=0;u<r;u++)this.queuedUpdates[u].reject(c)},a=this.queuedUpdates.flatMap(c=>c.tags),l=Date.now()+"-"+Math.random();await new Promise(c=>{this.isSubscriptionHandledByWriteLoop=!0;let u=[],h=()=>{this.isSubscriptionHandledByWriteLoop=!1,u.forEach(d=>d()),c()};u.push(this.innerSignal.subscribeFull((d,p,m)=>{this.isSubscriptionHandledByWriteLoop&&(m?.includes(l)?(h(),i(),this.queuedUpdates.splice(0,r),this.updateOptimisticValue(m.filter(g=>g!==l))):this.updateOptimisticValue(m))})),u.push(this.writeErrorEvent.subscribe(({tags:d,error:p})=>{this.isSubscriptionHandledByWriteLoop&&d.includes(l)&&(h(),s(p),this.queuedUpdates.splice(0,r))})),this.writeUpstream(...n(this.innerSignal.get()),[l,...a])||(h(),i(),this.queuedUpdates.splice(0,r),this.updateOptimisticValue(a.filter(d=>d!==l)))})}this.isWriteLoopRunning=!1,e()}isStale(){return this.innerSignal.isStale()}get(){return this.outerSignal.get()}getPessimistic(){return this.innerSignal.get()}async pull({optimistic:e=!0}={}){return e?this.applyOptimisticUpdates(await this.innerSignal.pull()):this.innerSignal.pull()}async ensureAvailable(){return this.currentEnsureAvailablePromise===null&&(this.currentEnsureAvailablePromise=(async()=>(await this.innerSignal.pull(),this))()),this.currentEnsureAvailablePromise}subscribe(e){let r=this.outerSignal.subscribe(e),n=this.innerSignal.subscribe(()=>{});return()=>{r(),n()}}subscribeFull(e){let r=this.outerSignal.subscribeFull(e),n=this.innerSignal.subscribeFull(()=>{});return()=>{r(),n()}}};function LD(t){t.includes(":")||(t=`local:${t}`);let e=t.indexOf(":"),r=t.slice(0,e),n=t.slice(e+1);switch(r){case"local":{if(n.includes("/")||n.includes("\\")||n.length===0)throw new Error(`Invalid local file name: ${n}.`);return{type:"local",fileName:n}}case"base64":return{type:"base64",base64Data:n};default:throw new Error(`Unknown file identifier namespace: ${r}.`)}}function ND(t){return new Promise((e,r)=>{if(t.aborted){r(t.reason);return}t.addEventListener("abort",()=>{r(t.reason)},{once:!0})})}function $D(t,e){return Promise.race([t,ND(e)])}var UD=["HSA_OVERRIDE_GFX_VERSION"],qD=o.enum(UD),zD=o.record(qD,o.string()),VD=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,ni=o.string().regex(VD),WD=/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/,ii=o.string().regex(WD),GD=/^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])$/u,oh=o.string().regex(GD,{message:"Invalid file name"}),ZD=/^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])(?:\/[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ]))*$/u;o.string().regex(ZD,{message:"Invalid relative path"});var KD=o.object({type:o.literal("huggingface"),user:oh,repo:oh}),Mh=o.discriminatedUnion("type",[KD]),HD=o.enum(["baseModel","draftModel","custom"]),jh=o.object({purpose:HD}),YD=o.object({type:o.literal("model"),...jh.shape,modelKeys:o.array(o.string().min(1)),sources:o.array(Mh)}),JD=o.object({type:o.literal("artifact"),...jh.shape,owner:ni,name:ii}),QD=o.discriminatedUnion("type",[YD,JD]),Gl=o.object({owner:ni,name:ii.min(1,"Name is required").max(100,"Name too long"),revision:o.number().int().optional(),dependencies:o.array(QD).optional(),tags:o.array(o.string()).optional()}),XD=/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:[-.][a-z0-9]+)*$/,ew=o.string().regex(XD,{message:"Invalid artifact identifier format. Expected 'owner/name'."}),tw=o.object({type:o.literal("model"),...Gl.shape}),rw=o.enum(["ecmascript","node","mcpBridge"]),Zl=o.object({type:o.literal("plugin"),runner:rw,...Gl.shape}),nw=o.object({type:o.literal("preset"),...Gl.shape});o.discriminatedUnion("type",[Zl,nw,tw]);var iw=o.enum(["plugin","preset","model"]),Bh=o.object({title:o.string(),description:o.string().optional(),noAutoDismiss:o.boolean().optional()}),Lh=o.enum(["image","text/plain","application/pdf","application/word","text/other","unknown"]),Pe=o.any().transform((t,e)=>{try{return JSON.parse(JSON.stringify(t))}catch(r){return e.addIssue({code:o.ZodIssueCode.custom,message:"Not JSON serializable: "+r.message}),t}}),Cs=o.object({type:o.literal("text"),text:o.string()}),Es=o.object({type:o.literal("file"),name:o.string(),identifier:o.string(),sizeBytes:o.number().int(),fileType:Lh}),sw=o.object({id:o.string().optional(),type:o.literal("function"),arguments:o.record(Pe).optional(),name:o.string()}),si=o.discriminatedUnion("type",[sw]),Nh=o.object({type:o.literal("toolCallRequest"),toolCallRequest:si});o.object({content:o.string(),toolCallId:o.string().optional()});var $h=o.object({type:o.literal("toolCallResult"),content:o.string(),toolCallId:o.string().optional()});o.discriminatedUnion("type",[Cs,Es,Nh,$h]);o.enum(["assistant","user","system","tool"]);var kr=o.discriminatedUnion("role",[o.object({role:o.literal("assistant"),content:o.array(o.discriminatedUnion("type",[Cs,Es,Nh]))}),o.object({role:o.literal("user"),content:o.array(o.discriminatedUnion("type",[Cs,Es]))}),o.object({role:o.literal("system"),content:o.array(o.discriminatedUnion("type",[Cs,Es]))}),o.object({role:o.literal("tool"),content:o.array($h)})]),Fr=o.object({messages:o.array(kr)}),ow=o.object({fileName:o.string(),absoluteFilePath:o.string().optional(),pageNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional(),lineNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional()}),aw=o.enum(["red","green","blue","yellow","orange","purple","default"]),lw=aw,cw=o.discriminatedUnion("type",[o.object({type:o.literal("llm.prediction.input"),modelPath:o.string(),modelIdentifier:o.string(),input:o.string()})]),uw=o.object({timestamp:o.number(),data:cw}),Uh=o.union([o.number().min(0).max(1),o.literal("max"),o.literal("off")]),dw=o.enum(["evenly","favorMainGpu"]),qh=o.object({ratio:Uh.optional(),mainGpu:o.number().int().optional(),splitStrategy:dw.optional(),disabledGpus:o.array(o.number().int()).optional()}),qa=["f32","f16","q8_0","q4_0","q4_1","iq4_nl","q5_0","q5_1"],fw=o.enum(qa),hw=o.union([o.literal(8),o.literal(6),o.literal(4),o.literal(3),o.literal(2)]),pw=o.union([o.literal(32),o.literal(64),o.literal(128)]),mw=o.object({enabled:o.boolean(),bits:hw,groupSize:pw,quantizedStart:o.number().int().nonnegative()}),gw=o.object({gpu:qh.optional(),gpuStrictVramCap:o.boolean().optional(),offloadKVCacheToGpu:o.boolean().optional(),contextLength:o.number().int().min(1).optional(),ropeFrequencyBase:o.number().optional(),ropeFrequencyScale:o.number().optional(),evalBatchSize:o.number().int().min(1).optional(),flashAttention:o.boolean().optional(),keepModelInMemory:o.boolean().optional(),seed:o.number().int().optional(),useFp16ForKVCache:o.boolean().optional(),tryMmap:o.boolean().optional(),numExperts:o.number().int().optional(),llamaKCacheQuantizationType:o.enum(qa).or(o.literal(!1)).optional(),llamaVCacheQuantizationType:o.enum(qa).or(o.literal(!1)).optional()}),yw=o.object({gpu:qh.optional(),contextLength:o.number().int().min(1).optional(),ropeFrequencyBase:o.number().optional(),ropeFrequencyScale:o.number().optional(),keepModelInMemory:o.boolean().optional(),tryMmap:o.boolean().optional()}),Js=o.enum(["gguf","safetensors","onnx","ggml","mlx_placeholder","torch_safetensors"]),bw=o.object({name:o.string(),bits:o.number().int()}),Kl=o.object({modelKey:o.string(),format:Js,displayName:o.string(),path:o.string(),sizeBytes:o.number().int(),paramsString:o.string().optional(),architecture:o.string().optional(),quantization:bw.optional()}),zh=Kl.extend({identifier:o.string(),instanceReference:o.string()}),Vh=o.object({maxContextLength:o.number().int()}),vw=o.object({contextLength:o.number().int()}),Wh=o.object({type:o.literal("embedding")}).extend(Kl.shape).extend(Vh.shape),Gh=o.object({type:o.literal("embedding")}).extend(zh.shape).extend(Vh.shape).extend(vw.shape),oi=o.enum(["llm","embedding","imageGen","transcription","tts"]),pn=o.string().min(1).max(1024).refine(t=>t!=="__proto__",{message:'For security reasons, "__proto__" is not allowed'}).refine(t=>/\p{C}/u.test(t)===!1,{message:"Control characters are not allowed"}),Hl=o.object({domain:oi.optional(),identifier:pn.optional(),path:pn.optional(),vision:o.boolean().optional()}),nt=o.discriminatedUnion("type",[o.object({type:o.literal("query"),query:Hl}),o.object({type:o.literal("instanceReference"),instanceReference:o.string()})]),Dw=[o.object({code:o.literal("generic.specificModelUnloaded")}),o.object({code:o.literal("generic.noModelMatchingQuery"),query:Hl,loadedModelsSample:o.array(o.string()),totalLoadedModels:o.number().int()}),o.object({code:o.literal("generic.pathNotFound"),path:o.string(),availablePathsSample:o.array(o.string()),totalModels:o.number().int()}),o.object({code:o.literal("generic.identifierNotFound"),identifier:o.string(),loadedModelsSample:o.array(o.string()),totalLoadedModels:o.number().int()}),o.object({code:o.literal("generic.domainMismatch"),path:o.string(),actualDomain:oi,expectedDomain:oi}),o.object({code:o.literal("generic.engineDoesNotSupportFeature"),feature:o.string(),engineName:o.string(),engineType:o.string(),installedVersion:o.string(),supportedVersion:o.string().nullable()}),o.object({code:o.literal("generic.presetNotFound"),specifiedFuzzyPresetIdentifier:o.string(),availablePresetsSample:o.array(o.object({identifier:o.string(),name:o.string()})),totalAvailablePresets:o.number().int()})],ww=[],Sw=o.discriminatedUnion("code",[...ww,...Dw]);function Dr(t){return o.any().transform(e=>t.safeParse(e).success?e:void 0)}var Oe=o.object({title:Dr(o.string()).default("Unknown error"),cause:Dr(o.string()).optional(),suggestion:Dr(o.string()).optional(),errorData:Dr(o.record(o.string(),o.unknown())).optional(),displayData:Dr(Sw).optional(),stack:Dr(o.string()).optional(),rootTitle:Dr(o.string()).optional()});function Sr(t){if(typeof t=="object"){let e=t.title??t.lmstudioRawError??t.message??"Unknown error";return Oe.parse({title:e,cause:t.cause,suggestion:t.suggestion,errorData:t.errorData,displayData:t.displayData,stack:t.stack,rootTitle:e})}else{let e=String(t);return{title:e,rootTitle:e}}}function Zh(t,e){let r=t;r.title=e.title,e.cause!==void 0&&(r.cause=e.cause),e.suggestion!==void 0&&(r.suggestion=e.suggestion),e.errorData!==void 0&&(r.errorData=e.errorData)}function Os(t,e="Rehydrated error",r){let n=new Error(t.rootTitle);return Zh(n,t),t.displayData!==void 0&&(n.displayData=t.displayData),r!==void 0?t.stack!==void 0?n.stack=`Error: ${e}
169
+ `)}};var qa=class t extends Ut{static{this.NOT_AVAILABLE=Ze.NOT_AVAILABLE}applyOptimisticUpdates(e){for(let r of this.queuedUpdates)[e]=r.updater(e);return e}updateOptimisticValue(e){let r=this.innerSignal.get();St(r)&&this.setOuterSignal(this.applyOptimisticUpdates(r),e)}constructor(e,r,n,i){super(),this.writeUpstream=n,this.isWriteLoopRunning=!1,this.isSubscriptionHandledByWriteLoop=!1,this.queuedUpdates=[],this.currentEnsureAvailablePromise=null,[this.writeErrorEvent,this.emitWriteErrorEvent]=Jn.create(),[this.outerSignal,this.setOuterSignal]=ri.create(e,i),this.innerSignal=Ze.create(e,r,i),this.innerSignal.passiveSubscribeFull((s,a,l)=>{this.isSubscriptionHandledByWriteLoop||this.updateOptimisticValue(l)})}static create(e,r,n,i=(s,a)=>s===a){let s=new t(e,r,n,i),a=Gl(s.update.bind(s));return[s,a,(c,u)=>s.emitWriteErrorEvent({tags:c,error:u})]}static createWithoutInitialValue(e,r,n=(i,s)=>i===s){let i=(s,a)=>s===t.NOT_AVAILABLE||a===t.NOT_AVAILABLE?s===a:n(s,a);return t.create(t.NOT_AVAILABLE,e,r,i)}async update(e,r){let{promise:n,reject:i,resolve:s}=re();return this.queuedUpdates.push({updater:e,tags:r??[],resolve:s,reject:i}),this.updateOptimisticValue(),this.ensureWriteLoop(),n}ensureWriteLoop(){this.isWriteLoopRunning||this.writeLoop()}async writeLoop(){let e=this.innerSignal.subscribe(()=>{});for(this.isWriteLoopRunning=!0,this.isStale()&&await this.innerSignal.pull();this.queuedUpdates.length>0;){let r=this.queuedUpdates.length,n=c=>{let u=[];for(let h=0;h<r;h++){let[f,d]=this.queuedUpdates[h].updater(c);c=f,u.push(...d)}return[c,u]},i=()=>{for(let c=0;c<r;c++)this.queuedUpdates[c].resolve()},s=c=>{for(let u=0;u<r;u++)this.queuedUpdates[u].reject(c)},a=this.queuedUpdates.flatMap(c=>c.tags),l=Date.now()+"-"+Math.random();await new Promise(c=>{this.isSubscriptionHandledByWriteLoop=!0;let u=[],h=()=>{this.isSubscriptionHandledByWriteLoop=!1,u.forEach(d=>d()),c()};u.push(this.innerSignal.subscribeFull((d,p,m)=>{this.isSubscriptionHandledByWriteLoop&&(m?.includes(l)?(h(),i(),this.queuedUpdates.splice(0,r),this.updateOptimisticValue(m.filter(g=>g!==l))):this.updateOptimisticValue(m))})),u.push(this.writeErrorEvent.subscribe(({tags:d,error:p})=>{this.isSubscriptionHandledByWriteLoop&&d.includes(l)&&(h(),s(p),this.queuedUpdates.splice(0,r))})),this.writeUpstream(...n(this.innerSignal.get()),[l,...a])||(h(),i(),this.queuedUpdates.splice(0,r),this.updateOptimisticValue(a.filter(d=>d!==l)))})}this.isWriteLoopRunning=!1,e()}isStale(){return this.innerSignal.isStale()}get(){return this.outerSignal.get()}getPessimistic(){return this.innerSignal.get()}async pull({optimistic:e=!0}={}){return e?this.applyOptimisticUpdates(await this.innerSignal.pull()):this.innerSignal.pull()}async ensureAvailable(){return this.currentEnsureAvailablePromise===null&&(this.currentEnsureAvailablePromise=(async()=>(await this.innerSignal.pull(),this))()),this.currentEnsureAvailablePromise}subscribe(e){let r=this.outerSignal.subscribe(e),n=this.innerSignal.subscribe(()=>{});return()=>{r(),n()}}subscribeFull(e){let r=this.outerSignal.subscribeFull(e),n=this.innerSignal.subscribeFull(()=>{});return()=>{r(),n()}}};function ND(t){t.includes(":")||(t=`local:${t}`);let e=t.indexOf(":"),r=t.slice(0,e),n=t.slice(e+1);switch(r){case"local":{if(n.includes("/")||n.includes("\\")||n.length===0)throw new Error(`Invalid local file name: ${n}.`);return{type:"local",fileName:n}}case"base64":return{type:"base64",base64Data:n};default:throw new Error(`Unknown file identifier namespace: ${r}.`)}}function $D(t){return new Promise((e,r)=>{if(t.aborted){r(t.reason);return}t.addEventListener("abort",()=>{r(t.reason)},{once:!0})})}function UD(t,e){return Promise.race([t,$D(e)])}var qD=["HSA_OVERRIDE_GFX_VERSION"],zD=o.enum(qD),VD=o.record(zD,o.string()),WD=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,ni=o.string().regex(WD),GD=/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/,ii=o.string().regex(GD),ZD=/^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])$/u,ah=o.string().regex(ZD,{message:"Invalid file name"}),KD=/^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])(?:\/[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ]))*$/u;o.string().regex(KD,{message:"Invalid relative path"});var HD=o.object({type:o.literal("huggingface"),user:ah,repo:ah}),jh=o.discriminatedUnion("type",[HD]),YD=o.enum(["baseModel","draftModel","custom"]),Bh=o.object({purpose:YD}),JD=o.object({type:o.literal("model"),...Bh.shape,modelKeys:o.array(o.string().min(1)),sources:o.array(jh)}),QD=o.object({type:o.literal("artifact"),...Bh.shape,owner:ni,name:ii}),XD=o.discriminatedUnion("type",[JD,QD]),Zl=o.object({owner:ni,name:ii.min(1,"Name is required").max(100,"Name too long"),revision:o.number().int().optional(),dependencies:o.array(XD).optional(),tags:o.array(o.string()).optional()}),ew=/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:[-.][a-z0-9]+)*$/,tw=o.string().regex(ew,{message:"Invalid artifact identifier format. Expected 'owner/name'."}),rw=o.object({type:o.literal("model"),...Zl.shape}),nw=o.enum(["ecmascript","node","mcpBridge"]),Kl=o.object({type:o.literal("plugin"),runner:nw,...Zl.shape}),iw=o.object({type:o.literal("preset"),...Zl.shape});o.discriminatedUnion("type",[Kl,iw,rw]);var sw=o.enum(["plugin","preset","model"]),Lh=o.object({title:o.string(),description:o.string().optional(),noAutoDismiss:o.boolean().optional()}),Nh=o.enum(["image","text/plain","application/pdf","application/word","text/other","unknown"]),Pe=o.any().transform((t,e)=>{try{return JSON.parse(JSON.stringify(t))}catch(r){return e.addIssue({code:o.ZodIssueCode.custom,message:"Not JSON serializable: "+r.message}),t}}),Cs=o.object({type:o.literal("text"),text:o.string()}),Es=o.object({type:o.literal("file"),name:o.string(),identifier:o.string(),sizeBytes:o.number().int(),fileType:Nh}),ow=o.object({id:o.string().optional(),type:o.literal("function"),arguments:o.record(Pe).optional(),name:o.string()}),si=o.discriminatedUnion("type",[ow]),$h=o.object({type:o.literal("toolCallRequest"),toolCallRequest:si});o.object({content:o.string(),toolCallId:o.string().optional()});var Uh=o.object({type:o.literal("toolCallResult"),content:o.string(),toolCallId:o.string().optional()});o.discriminatedUnion("type",[Cs,Es,$h,Uh]);o.enum(["assistant","user","system","tool"]);var kr=o.discriminatedUnion("role",[o.object({role:o.literal("assistant"),content:o.array(o.discriminatedUnion("type",[Cs,Es,$h]))}),o.object({role:o.literal("user"),content:o.array(o.discriminatedUnion("type",[Cs,Es]))}),o.object({role:o.literal("system"),content:o.array(o.discriminatedUnion("type",[Cs,Es]))}),o.object({role:o.literal("tool"),content:o.array(Uh)})]),Fr=o.object({messages:o.array(kr)}),aw=o.object({fileName:o.string(),absoluteFilePath:o.string().optional(),pageNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional(),lineNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional()}),lw=o.enum(["red","green","blue","yellow","orange","purple","default"]),cw=lw,uw=o.discriminatedUnion("type",[o.object({type:o.literal("llm.prediction.input"),modelPath:o.string(),modelIdentifier:o.string(),input:o.string()})]),dw=o.object({timestamp:o.number(),data:uw}),qh=o.union([o.number().min(0).max(1),o.literal("max"),o.literal("off")]),fw=o.enum(["evenly","favorMainGpu"]),zh=o.object({ratio:qh.optional(),mainGpu:o.number().int().optional(),splitStrategy:fw.optional(),disabledGpus:o.array(o.number().int()).optional()}),za=["f32","f16","q8_0","q4_0","q4_1","iq4_nl","q5_0","q5_1"],hw=o.enum(za),pw=o.union([o.literal(8),o.literal(6),o.literal(4),o.literal(3),o.literal(2)]),mw=o.union([o.literal(32),o.literal(64),o.literal(128)]),gw=o.object({enabled:o.boolean(),bits:pw,groupSize:mw,quantizedStart:o.number().int().nonnegative()}),yw=o.object({gpu:zh.optional(),gpuStrictVramCap:o.boolean().optional(),offloadKVCacheToGpu:o.boolean().optional(),contextLength:o.number().int().min(1).optional(),ropeFrequencyBase:o.number().optional(),ropeFrequencyScale:o.number().optional(),evalBatchSize:o.number().int().min(1).optional(),flashAttention:o.boolean().optional(),keepModelInMemory:o.boolean().optional(),seed:o.number().int().optional(),useFp16ForKVCache:o.boolean().optional(),tryMmap:o.boolean().optional(),numExperts:o.number().int().optional(),llamaKCacheQuantizationType:o.enum(za).or(o.literal(!1)).optional(),llamaVCacheQuantizationType:o.enum(za).or(o.literal(!1)).optional()}),bw=o.object({gpu:zh.optional(),contextLength:o.number().int().min(1).optional(),ropeFrequencyBase:o.number().optional(),ropeFrequencyScale:o.number().optional(),keepModelInMemory:o.boolean().optional(),tryMmap:o.boolean().optional()}),Js=o.enum(["gguf","safetensors","onnx","ggml","mlx_placeholder","torch_safetensors"]),vw=o.object({name:o.string(),bits:o.number().int()}),Hl=o.object({modelKey:o.string(),format:Js,displayName:o.string(),path:o.string(),sizeBytes:o.number().int(),paramsString:o.string().optional(),architecture:o.string().optional(),quantization:vw.optional()}),Vh=Hl.extend({identifier:o.string(),instanceReference:o.string()}),Wh=o.object({maxContextLength:o.number().int()}),Dw=o.object({contextLength:o.number().int()}),Gh=o.object({type:o.literal("embedding")}).extend(Hl.shape).extend(Wh.shape),Zh=o.object({type:o.literal("embedding")}).extend(Vh.shape).extend(Wh.shape).extend(Dw.shape),oi=o.enum(["llm","embedding","imageGen","transcription","tts"]),pn=o.string().min(1).max(1024).refine(t=>t!=="__proto__",{message:'For security reasons, "__proto__" is not allowed'}).refine(t=>/\p{C}/u.test(t)===!1,{message:"Control characters are not allowed"}),Yl=o.object({domain:oi.optional(),identifier:pn.optional(),path:pn.optional(),vision:o.boolean().optional()}),st=o.discriminatedUnion("type",[o.object({type:o.literal("query"),query:Yl}),o.object({type:o.literal("instanceReference"),instanceReference:o.string()})]),ww=[o.object({code:o.literal("generic.specificModelUnloaded")}),o.object({code:o.literal("generic.noModelMatchingQuery"),query:Yl,loadedModelsSample:o.array(o.string()),totalLoadedModels:o.number().int()}),o.object({code:o.literal("generic.pathNotFound"),path:o.string(),availablePathsSample:o.array(o.string()),totalModels:o.number().int()}),o.object({code:o.literal("generic.identifierNotFound"),identifier:o.string(),loadedModelsSample:o.array(o.string()),totalLoadedModels:o.number().int()}),o.object({code:o.literal("generic.domainMismatch"),path:o.string(),actualDomain:oi,expectedDomain:oi}),o.object({code:o.literal("generic.engineDoesNotSupportFeature"),feature:o.string(),engineName:o.string(),engineType:o.string(),installedVersion:o.string(),supportedVersion:o.string().nullable()}),o.object({code:o.literal("generic.presetNotFound"),specifiedFuzzyPresetIdentifier:o.string(),availablePresetsSample:o.array(o.object({identifier:o.string(),name:o.string()})),totalAvailablePresets:o.number().int()})],Sw=[],Cw=o.discriminatedUnion("code",[...Sw,...ww]);function Dr(t){return o.any().transform(e=>t.safeParse(e).success?e:void 0)}var Ie=o.object({title:Dr(o.string()).default("Unknown error"),cause:Dr(o.string()).optional(),suggestion:Dr(o.string()).optional(),errorData:Dr(o.record(o.string(),o.unknown())).optional(),displayData:Dr(Cw).optional(),stack:Dr(o.string()).optional(),rootTitle:Dr(o.string()).optional()});function Sr(t){if(typeof t=="object"){let e=t.title??t.lmstudioRawError??t.message??"Unknown error";return Ie.parse({title:e,cause:t.cause,suggestion:t.suggestion,errorData:t.errorData,displayData:t.displayData,stack:t.stack,rootTitle:e})}else{let e=String(t);return{title:e,rootTitle:e}}}function Kh(t,e){let r=t;r.title=e.title,e.cause!==void 0&&(r.cause=e.cause),e.suggestion!==void 0&&(r.suggestion=e.suggestion),e.errorData!==void 0&&(r.errorData=e.errorData)}function Os(t,e="Rehydrated error",r){let n=new Error(t.rootTitle);return Kh(n,t),t.displayData!==void 0&&(n.displayData=t.displayData),r!==void 0?t.stack!==void 0?n.stack=`Error: ${e}
170
170
  ${r}
171
171
  - Caused By: ${t.stack}`:n.stack=`Error: ${e}
172
172
  ${r}`:t.stack!==void 0?n.stack=`Error: ${e}
173
173
  ${n.stack.substring(t.stack.indexOf(`
174
174
  `)+1)}
175
- - Caused By: `+t.stack:n.message+=` - caused by error without stack (${t.title})`,n}var za=o.object({library:o.string(),version:o.string()}),Kh=o.object({parserId:za.optional()});o.enum(["local","base64"]);o.discriminatedUnion("type",[o.object({type:o.literal("local"),fileName:o.string()}),o.object({type:o.literal("base64"),base64Data:o.string()})]);var Cw=["evenly","priorityOrder","custom"],Ew=o.enum(Cw),_w={strategy:"evenly",disabledGpus:[],priority:[],customRatio:[]},xw=o.object({strategy:Ew,disabledGpus:o.array(o.number().int().min(0)),priority:o.array(o.number().int().min(0)),customRatio:o.array(o.number().min(0))});function Hh(t){return{strategy:t?.splitStrategy=="favorMainGpu"?"priorityOrder":t?.splitStrategy??"evenly",disabledGpus:t?.disabledGpus??[],priority:t?.mainGpu?[t.mainGpu]:[],customRatio:[]}}var Yh=o.object({key:o.string(),value:o.any()}),te=o.object({fields:o.array(Yh)}),kw=o.enum(["currentlyEditing","currentlyLoaded","apiOverride","conversationSpecific","conversationGlobal","preset","serverSession","httpServerRequestOverride","completeModeFormatting","instance","userModelDefault","virtualModel","modelDefault","hardware"]),Fw=o.object({layerName:kw,config:te}),Is=o.object({layers:o.array(Fw)}),Pw=o.object({key:o.string(),condition:o.discriminatedUnion("type",[o.object({type:o.literal("equals"),value:o.any()}),o.object({type:o.literal("notEquals"),value:o.any()})])}),Jh=o.discriminatedUnion("type",[o.object({type:o.literal("default")}),o.object({type:o.literal("customLabel"),label:o.string(),color:o.optional(lw)}),o.object({type:o.literal("thinking"),ended:o.boolean().optional(),title:o.string().optional()})]),Tw=o.discriminatedUnion("type",[o.object({type:o.literal("object"),properties:o.record(Pe),required:o.array(o.string()).optional(),additionalProperties:o.boolean().optional(),$defs:o.record(Pe).optional()})]),Er=o.discriminatedUnion("type",[o.object({type:o.literal("function"),function:o.object({name:o.string(),description:o.string().optional(),parameters:Tw.optional()})})]);o.array(Er);var Qh=o.discriminatedUnion("type",[o.object({type:o.literal("none")}),o.object({type:o.literal("toolArray"),tools:o.array(Er).optional(),force:o.boolean().optional()})]),Xh=o.object({omitBosToken:o.boolean().optional(),omitEosToken:o.boolean().optional(),toolDefinitions:o.array(Er).optional()}),Aw=o.discriminatedUnion("type",[o.object({type:o.literal("jsonFile"),absPath:o.string()}),o.object({type:o.literal("yamlFile"),absPath:o.string()})]);o.array(o.object({role:o.enum(["user","assistant","system"]),content:o.string()}));o.array(o.union([o.object({system:o.string()}),o.object({user:o.string()}),o.object({assistant:o.string()})]));var ep=o.object({vision:o.boolean(),trainedForToolUse:o.boolean(),maxContextLength:o.number().int()}),Ow=o.object({contextLength:o.number().int()}),tp=o.object({type:o.literal("llm")}).extend(Kl.shape).extend(ep.shape),Va=o.object({type:o.literal("llm")}).extend(zh.shape).extend(ep.shape).extend(Ow.shape),rp=o.enum(["passThrough","removeSpecial","snakeCase","camelCase"]),Rr=o.custom(t=>typeof t?.parse=="function","Expected a zod schema"),Iw=o.object({beforeSystem:o.string(),afterSystem:o.string(),beforeUser:o.string(),afterUser:o.string(),beforeAssistant:o.string(),afterAssistant:o.string()}),Rw=o.object({template:o.string()}),Mw=o.enum(["manual","jinja"]),np=o.object({type:Mw,manualPromptTemplate:Iw.optional(),jinjaPromptTemplate:Rw.optional(),stopStrings:o.array(o.string())}),jw=o.enum(["none","json","gbnf"]),Yl=o.object({type:jw,jsonSchema:Pe.optional(),gbnfGrammar:o.string().optional()}),ip=o.enum(["stopAtLimit","truncateMiddle","rollingWindow"]),sp=o.object({enabled:o.boolean(),startString:o.string(),endString:o.string()}),Jl=o.object({maxTokens:o.number().int().min(-1).optional().or(o.literal(!1)),temperature:o.number().min(0).optional(),stopStrings:o.array(o.string()).optional(),toolCallStopStrings:o.array(o.string()).optional(),contextOverflowPolicy:ip.optional(),structured:o.union([Rr,Yl]).optional(),rawTools:Qh.optional(),toolNaming:rp.optional(),topKSampling:o.number().optional(),repeatPenalty:o.number().optional().or(o.literal(!1)),minPSampling:o.number().optional().or(o.literal(!1)),topPSampling:o.number().optional().or(o.literal(!1)),cpuThreads:o.number().int().optional(),promptTemplate:np.optional(),draftModel:o.string().optional(),speculativeDecodingNumDraftTokensExact:o.number().int().min(1).optional(),speculativeDecodingMinDraftLengthToConsider:o.number().int().min(0).optional(),speculativeDecodingMinContinueDraftingProbability:o.number().optional(),reasoningParsing:sp.optional(),raw:te.optional()});o.object({...Jl.shape,structured:Yl.optional()});var Bw=o.object({version:o.union([o.literal(0),o.literal(1),o.literal(2)]),learningRate:o.number(),targetEntropy:o.number()}),Lw=o.union([o.number(),o.literal("-inf")]),Nw=o.array(o.tuple([o.number(),Lw])),op=o.enum(["none","reasoning","reasoningStartTag","reasoningEndTag"]),ap=o.object({content:o.string(),tokensCount:o.number().int(),containsDrafted:o.boolean(),reasoningType:op,isStructural:o.boolean()}),lp=o.object({tokenCount:o.number().int().optional(),containsDrafted:o.boolean().optional(),reasoningType:op.optional(),isStructural:o.boolean().optional()}),$w=o.enum(["userStopped","modelUnloaded","failed","eosFound","stopStringFound","toolCalls","maxPredictedTokensReached","contextLengthReached"]),cp=o.object({stopReason:$w,tokensPerSecond:o.number().optional(),numGpuLayers:o.number().optional(),timeToFirstTokenSec:o.number().optional(),totalTimeSec:o.number().optional(),promptTokensCount:o.number().int().optional(),predictedTokensCount:o.number().int().optional(),totalTokensCount:o.number().int().optional(),usedDraftModelKey:o.string().optional(),totalDraftTokensCount:o.number().int().optional(),acceptedDraftTokensCount:o.number().int().optional(),rejectedDraftTokensCount:o.number().int().optional(),ignoredDraftTokensCount:o.number().int().optional()}),Uw=o.object({indexedModelIdentifier:o.string(),identifier:o.string(),loadModelConfig:te,predictionConfig:te,stats:cp}),qw=o.discriminatedUnion("type",[o.object({type:o.literal("beforeId"),id:o.string()}),o.object({type:o.literal("afterId"),id:o.string()})]),zw=o.enum(["waiting","loading","done","error","canceled"]),up=o.object({status:zw,text:o.string()}),Ql=o.object({type:o.literal("status.create"),id:o.string(),state:up,location:qw.optional(),indentation:o.number().int().optional()}),Xl=o.object({type:o.literal("status.update"),id:o.string(),state:up}),ec=o.object({type:o.literal("status.remove"),id:o.string()}),tc=o.object({type:o.literal("citationBlock.create"),id:o.string(),citedText:o.string(),fileName:o.string(),fileIdentifier:o.string(),pageNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional(),lineNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional()}),rc=o.object({type:o.literal("debugInfoBlock.create"),id:o.string(),debugInfo:o.string()}),dp=o.object({type:o.literal("contentBlock.create"),id:o.string(),includeInContext:o.boolean(),roleOverride:o.enum(["user","assistant","system","tool"]).optional(),style:Jh.optional(),prefix:o.string().optional(),suffix:o.string().optional()}),fp=o.object({type:o.literal("contentBlock.appendText"),id:o.string(),text:o.string(),tokensCount:o.number().int().optional(),fromDraftModel:o.boolean().optional(),isStructural:o.boolean().optional()}),hp=o.object({type:o.literal("contentBlock.appendToolResult"),id:o.string(),callId:o.number().int(),toolCallRequestId:o.string().optional(),content:o.string()}),pp=o.object({type:o.literal("contentBlock.appendToolRequest"),id:o.string(),callId:o.number().int(),toolCallRequestId:o.string().optional(),name:o.string(),parameters:o.record(o.unknown()),pluginIdentifier:o.string().optional()}),mp=o.object({type:o.literal("contentBlock.replaceToolRequest"),id:o.string(),callId:o.number().int(),toolCallRequestId:o.string().optional(),name:o.string(),parameters:o.record(o.unknown()),pluginIdentifier:o.string().optional()}),gp=o.object({type:o.literal("contentBlock.replaceText"),id:o.string(),text:o.string()}),Vw=o.object({type:o.literal("contentBlock.setPrefix"),id:o.string(),prefix:o.string()}),Ww=o.object({type:o.literal("contentBlock.setSuffix"),id:o.string(),suffix:o.string()}),yp=o.object({type:o.literal("contentBlock.attachGenInfo"),id:o.string(),genInfo:Uw}),bp=o.object({type:o.literal("contentBlock.setStyle"),id:o.string(),style:Jh}),Gw=o.discriminatedUnion("type",[o.object({type:o.literal("generatingToolCall"),name:o.string().optional(),pluginIdentifier:o.string().optional(),argumentsString:o.string().optional()}),o.object({type:o.literal("toolCallGenerationFailed"),error:o.string(),rawContent:o.string().optional()}),o.object({type:o.literal("toolCallQueued")}),o.object({type:o.literal("confirmingToolCall")}),o.object({type:o.literal("toolCallDenied"),denyReason:o.string().optional()}),o.object({type:o.literal("callingTool")}),o.object({type:o.literal("toolCallFailed"),error:o.string()}),o.object({type:o.literal("toolCallSucceeded"),timeMs:o.number().int()})]),vp=o.object({status:Gw,customStatus:o.string(),customWarnings:o.array(o.string())}),Dp=o.object({type:o.literal("toolStatus.create"),id:o.string(),callId:o.number().int(),state:vp}),wp=o.object({type:o.literal("toolStatus.update"),id:o.string(),state:vp}),Sp=o.object({type:o.literal("toolStatus.argumentFragment"),id:o.string(),content:o.string()}),Cp=o.object({type:o.literal("setSenderName"),name:o.string()}),Zw=o.discriminatedUnion("type",[Ql,Xl,ec,tc,rc,dp,fp,pp,mp,hp,gp,Vw,Ww,yp,bp,Dp,wp,Sp,Cp]);o.discriminatedUnion("type",[Ql,Xl,ec,tc,rc,dp,fp,gp,pp,mp,hp,yp,bp,Dp,wp,Sp,Cp]);var Kw=o.object({type:o.literal("confirmToolCall"),callId:o.number().int(),pluginIdentifier:o.string().optional(),name:o.string(),parameters:o.record(o.any())}),Hw=o.object({type:o.literal("textInput"),prompt:o.string()}),Yw=o.discriminatedUnion("type",[Kw,Hw]),Jw=o.object({type:o.literal("confirmToolCall"),result:o.discriminatedUnion("type",[o.object({type:o.literal("allow"),toolArgsOverride:o.record(o.any()).optional()}),o.object({type:o.literal("deny"),denyReason:o.string().optional()})])}),Qw=o.object({type:o.literal("textInput"),result:o.string()}),Xw=o.discriminatedUnion("type",[Jw,Qw]);o.object({modelTag:o.string().optional(),ignoreUserConfig:o.boolean().optional()});o.discriminatedUnion("type",[Ql,Xl,ec,tc,rc]);var e1=o.discriminatedUnion("type",[o.object({type:o.literal("model"),identifier:o.string()}),o.object({type:o.literal("generator"),pluginIdentifier:o.string()})]),t1=o.discriminatedUnion("type",[tp,Wh]),r1=o.discriminatedUnion("type",[Va,Gh]),ah=o.discriminatedUnion("type",[o.object({type:o.literal("direct"),config:te,workingDirectoryPath:o.string().optional()}),o.object({type:o.literal("predictionProcess"),pci:o.string(),token:o.string()})]),lh=o.object({identifier:o.string(),isDev:o.boolean(),isTrusted:o.boolean(),hasPromptPreprocessor:o.boolean(),hasPredictionLoopHandler:o.boolean(),hasToolsProvider:o.boolean(),hasGenerator:o.boolean()}),ch=o.object({displayName:o.string(),sizeBytes:o.number(),quantName:o.string().optional(),compatibilityType:Js}),uh=o.enum(["pending","fetching","satisfied","completed"]),n1=o.discriminatedUnion("type",[o.object({type:o.literal("artifact"),owner:ni,name:ii,state:uh,artifactType:iw.optional(),sizeBytes:o.number().int().optional(),dependencyNodes:o.array(o.number().int())}),o.object({type:o.literal("model"),state:uh,resolvedSources:o.number().int().optional(),totalSources:o.number().int().optional(),alreadyOwned:ch.optional(),selected:ch.optional()})]),dh=o.object({nodes:o.array(n1),downloadSizeBytes:o.number().int()}),i1=o.object({relativePath:o.string(),sizeBytes:o.number().int()}),s1=o.object({files:o.array(i1),usedIgnoreFile:o.string().nullable()}),Pa=o.object({downloadedBytes:o.number().int(),totalBytes:o.number().int(),speedBytesPerSecond:o.number()}),o1=o.enum(["fullGPUOffload","partialGPUOffload","fitWithoutGPU","willNotFit"]),a1=o.object({quantization:o.string().optional(),name:o.string(),sizeBytes:o.number().int(),fitEstimation:o1,recommended:o.boolean().optional(),downloadIdentifier:o.string(),indexedModelIdentifier:o.string()}),Ep=o.discriminatedUnion("type",[o.object({type:o.literal("catalog"),identifier:o.string()}),o.object({type:o.literal("hf"),identifier:o.string()})]),l1=o.object({name:o.string(),identifier:Ep,exact:o.boolean().optional(),staffPick:o.boolean().optional()}),_p=o.object({searchTerm:o.string().optional(),limit:o.number().int().positive().max(25).optional(),compatibilityTypes:o.array(Js).optional()}),c1=o.object({content:o.string(),score:o.number(),sourceIndex:o.number().int(),pageNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional(),lineNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional()}),u1=o.object({entries:o.array(c1)});o.object({content:o.string(),score:o.number(),citation:ow});var xp=o.discriminatedUnion("type",[o.object({type:o.literal("recursive-v1"),chunkSize:o.number().int(),chunkOverlap:o.number().int()})]),Ta=o.enum(["loading","chunking","embedding"]),d1=o.enum(["unknown","integratedGpu","dedicatedGpu"]),f1=o.object({name:o.string(),deviceId:o.number().int(),totalMemoryBytes:o.number().int(),type:d1});o.object({key:o.string(),name:o.string(),accelerators:o.array(f1)});var h1=o.object({shortKey:o.string(),fullKey:o.string(),typeKey:o.string(),typeParams:Pe,defaultValue:Pe}),fh=o.object({fields:o.array(h1),extensionPrefixes:o.array(o.string()).optional()});o.object({fullKey:o.string(),error:Pe});var bs=o.union([o.literal(!0),o.literal(!1),o.literal("mixed")]),p1=o.object({domain:oi.optional(),architectures:o.array(o.string()).optional(),compatibilityTypes:o.array(Js).optional(),paramsStrings:o.array(o.string()).optional(),minMemoryUsageBytes:o.number().optional(),contextLengths:o.array(o.number()).optional(),trainedForToolUse:bs.optional(),vision:bs.optional(),reasoning:bs.optional(),fim:bs.optional()}),m1=o.object({key:o.string(),sources:o.array(Mh)}),nc=o.object({type:o.literal("setJinjaVariable"),variable:o.string()}),g1=o.object({type:o.literal("prependSystemPrompt"),content:o.string()}),y1=o.object({type:o.literal("appendSystemPrompt"),content:o.string()}),ic=o.object({key:o.string(),displayName:o.string(),description:o.string()}),b1=ic.extend({type:o.literal("boolean"),defaultValue:o.boolean(),effects:o.array(o.discriminatedUnion("type",[nc,g1,y1]))}),v1=ic.extend({type:o.literal("string"),defaultValue:o.string(),effects:o.array(o.discriminatedUnion("type",[nc]))}),D1=ic.extend({type:o.literal("select"),options:o.array(o.object({label:o.string(),value:o.string()})),defaultValue:o.string(),effects:o.array(o.discriminatedUnion("type",[nc]))}),w1=o.discriminatedUnion("type",[b1,v1,D1]),S1=o.object({type:o.literal("equals"),key:o.string(),value:Pe}),C1=o.discriminatedUnion("type",[S1]),E1=o.object({message:o.string(),conditions:o.array(C1),fields:o.array(Yh).optional()});o.object({model:o.string().regex(/^[^/]+\/[^/]+$/),base:o.union([o.string(),o.array(m1)]),tags:o.array(o.string().max(100)).optional(),config:o.object({load:te.optional(),operation:te.optional()}).optional(),metadataOverrides:p1.optional(),customFields:o.array(w1).optional(),suggestions:o.array(E1).optional()});var _1=o.enum(["debug","info","warn","error"]);function L(t,e,r,n){if(r!==void 0)try{let i=r(...n);typeof i=="object"&&typeof i.catch=="function"&&i.catch(s=>{t.error(`Error in the ${e} callback (triggered asynchronously):`,s)})}catch(i){t.error(`Error in the ${e} callback:`,i)}}function x1(t){return t?.isSimpleLogger===!0}var k1=I.default.greenBright("I"),F1=I.default.yellowBright("W"),P1=I.default.redBright("E"),T1=I.default.blueBright("D"),Y=class t{constructor(e="",r=console,{useLogLevelPrefixes:n,infoPrefix:i,warnPrefix:s,errorPrefix:a,debugPrefix:l}={}){this.isSimpleLogger=!0,this.infoPrefix=[],this.warnPrefix=[],this.errorPrefix=[],this.debugPrefix=[],x1(r)?(n=n??r.opts.useLogLevelPrefixes,i=i===void 0?r.opts.infoPrefix:i,s=s===void 0?r.opts.warnPrefix:s,a=a===void 0?r.opts.errorPrefix:a,l=l===void 0?r.opts.debugPrefix:l,e===""?(this.innerPrefix=r.innerPrefix,this.fullPrefix=r.fullPrefix):(r.fullPrefix===""?this.innerPrefix=e:this.innerPrefix=`${r.innerPrefix}][${e}`,this.fullPrefix=I.default.whiteBright(`[${this.innerPrefix}]`)),this.parentLogger=r.parentLogger):(n=n??!1,i=i===void 0?k1:i,s=s===void 0?F1:s,a=a===void 0?P1:a,l=l===void 0?T1:l,e===""?(this.innerPrefix="",this.fullPrefix=""):(this.innerPrefix=e,this.fullPrefix=I.default.whiteBright(`[${this.innerPrefix}]`)),this.parentLogger=r),n&&(i!==null&&this.infoPrefix.push(i),s!==null&&this.warnPrefix.push(s),a!==null&&this.errorPrefix.push(a),l!==null&&this.debugPrefix.push(l)),this.fullPrefix!==""&&(this.infoPrefix.push(this.fullPrefix),this.warnPrefix.push(this.fullPrefix),this.errorPrefix.push(this.fullPrefix),this.debugPrefix.push(this.fullPrefix)),this.opts={useLogLevelPrefixes:n,infoPrefix:i,warnPrefix:s,errorPrefix:a,debugPrefix:l}}subclass(e){return new t(`${this.innerPrefix}:${e}`,this.parentLogger)}info(...e){this.parentLogger.info(...this.infoPrefix,...e)}infoText(e,...r){this.info(j(e,...r))}infoWithoutPrefix(...e){this.parentLogger.info(...e)}error(...e){this.parentLogger.error(...this.errorPrefix,...e)}errorText(e,...r){this.error(j(e,...r))}errorWithoutPrefix(...e){this.parentLogger.error(...e)}warn(...e){this.parentLogger.warn(...this.warnPrefix,...e)}warnText(e,...r){this.warn(j(e,...r))}warnWithoutPrefix(...e){this.parentLogger.warn(...e)}debug(...e){this.parentLogger.debug(...this.debugPrefix,...e)}debugText(e,...r){this.debug(j(e,...r))}debugWithoutPrefix(...e){this.parentLogger.debug(...e)}throw(e){throw new Error(`${this.fullPrefix} ${e}`)}logAtLevel(e,...r){switch(e){case"debug":this.debug(...r);break;case"info":this.info(...r);break;case"warn":this.warn(...r);break;case"error":this.error(...r);break}}static fromMultiple(e,r){return new t("",{debug:(...n)=>{for(let i of e)i.debug(...n)},info:(...n)=>{for(let i of e)i.info(...n)},warn:(...n)=>{for(let i of e)i.warn(...n)},error:(...n)=>{for(let i of e)i.error(...n)}},{...r,useLogLevelPrefixes:!1})}},hh,ph=Symbol("finished"),Rs=class{finished(e){if(this.status!=="pending")throw new Error("`finished` called while not pending");e===void 0?(this.status="resolved",this.nextFragmentPromiseBundle?.resolve(ph),this.resolveFinal(this.collect(this.buffer))):(this.status="rejected",this.nextFragmentPromiseBundle?.reject(e),this.rejectFinal(e))}push(e){if(this.status!=="pending")throw new Error("`push` called while not pending");this.buffer.push(e),this.nextFragmentPromiseBundle?.resolve(e),this.nextFragmentPromiseBundle=null}constructor(){this.status="pending",this.buffer=[],this.nextFragmentPromiseBundle=null,this.hasIterator=!1,this[hh]="StreamablePromise";let{promise:e,resolve:r,reject:n}=re();this.promiseFinal=e,this.resolveFinal=r,this.rejectFinal=n}then(e,r){return this.promiseFinal.then(e,r)}catch(e){return this.promiseFinal.catch(e)}finally(e){return this.promiseFinal.finally(e)}obtainNextFragmentPromiseBundle(){return this.nextFragmentPromiseBundle===null&&(this.nextFragmentPromiseBundle=re()),this.nextFragmentPromiseBundle}async*[(hh=Symbol.toStringTag,Symbol.asyncIterator)](){this.hasIterator||(this.promiseFinal.catch(()=>{}),this.hasIterator=!0);let e=0;for(;e<this.buffer.length||this.status==="pending";)if(e<this.buffer.length)yield this.buffer[e],e++;else{let n=await this.obtainNextFragmentPromiseBundle().promise;if(n===ph)break;yield n,e++}await this.promiseFinal,await Promise.resolve()}},it=class t{constructor({attachStack:e}={}){this.attachStack=e??!0}static prettyPrintZod(e,r){return r.errors.map(n=>{if(n.path.length===0)return`- ${I.default.redBright(e)}: ${n.message}`;let i=I.default.red(`.${n.path.join(".")}`);return`- ${I.default.redBright(e)}${i}: ${n.message}`}).join(`
175
+ - Caused By: `+t.stack:n.message+=` - caused by error without stack (${t.title})`,n}var Va=o.object({library:o.string(),version:o.string()}),Hh=o.object({parserId:Va.optional()});o.enum(["local","base64"]);o.discriminatedUnion("type",[o.object({type:o.literal("local"),fileName:o.string()}),o.object({type:o.literal("base64"),base64Data:o.string()})]);var Ew=["evenly","priorityOrder","custom"],_w=o.enum(Ew),xw={strategy:"evenly",disabledGpus:[],priority:[],customRatio:[]},kw=o.object({strategy:_w,disabledGpus:o.array(o.number().int().min(0)),priority:o.array(o.number().int().min(0)),customRatio:o.array(o.number().min(0))});function Yh(t){return{strategy:t?.splitStrategy=="favorMainGpu"?"priorityOrder":t?.splitStrategy??"evenly",disabledGpus:t?.disabledGpus??[],priority:t?.mainGpu?[t.mainGpu]:[],customRatio:[]}}var Jh=o.object({key:o.string(),value:o.any()}),te=o.object({fields:o.array(Jh)}),Fw=o.enum(["currentlyEditing","currentlyLoaded","apiOverride","conversationSpecific","conversationGlobal","preset","serverSession","httpServerRequestOverride","completeModeFormatting","instance","userModelDefault","virtualModel","modelDefault","hardware"]),Pw=o.object({layerName:Fw,config:te}),Is=o.object({layers:o.array(Pw)}),Tw=o.object({key:o.string(),condition:o.discriminatedUnion("type",[o.object({type:o.literal("equals"),value:o.any()}),o.object({type:o.literal("notEquals"),value:o.any()})])}),Qh=o.discriminatedUnion("type",[o.object({type:o.literal("default")}),o.object({type:o.literal("customLabel"),label:o.string(),color:o.optional(cw)}),o.object({type:o.literal("thinking"),ended:o.boolean().optional(),title:o.string().optional()})]),Aw=o.discriminatedUnion("type",[o.object({type:o.literal("object"),properties:o.record(Pe),required:o.array(o.string()).optional(),additionalProperties:o.boolean().optional(),$defs:o.record(Pe).optional()})]),Er=o.discriminatedUnion("type",[o.object({type:o.literal("function"),function:o.object({name:o.string(),description:o.string().optional(),parameters:Aw.optional()})})]);o.array(Er);var Xh=o.discriminatedUnion("type",[o.object({type:o.literal("none")}),o.object({type:o.literal("toolArray"),tools:o.array(Er).optional(),force:o.boolean().optional()})]),ep=o.object({omitBosToken:o.boolean().optional(),omitEosToken:o.boolean().optional(),toolDefinitions:o.array(Er).optional()}),Ow=o.discriminatedUnion("type",[o.object({type:o.literal("jsonFile"),absPath:o.string()}),o.object({type:o.literal("yamlFile"),absPath:o.string()})]);o.array(o.object({role:o.enum(["user","assistant","system"]),content:o.string()}));o.array(o.union([o.object({system:o.string()}),o.object({user:o.string()}),o.object({assistant:o.string()})]));var tp=o.object({vision:o.boolean(),trainedForToolUse:o.boolean(),maxContextLength:o.number().int()}),Iw=o.object({contextLength:o.number().int()}),rp=o.object({type:o.literal("llm")}).extend(Hl.shape).extend(tp.shape),Wa=o.object({type:o.literal("llm")}).extend(Vh.shape).extend(tp.shape).extend(Iw.shape),np=o.enum(["passThrough","removeSpecial","snakeCase","camelCase"]),Rr=o.custom(t=>typeof t?.parse=="function","Expected a zod schema"),Rw=o.object({beforeSystem:o.string(),afterSystem:o.string(),beforeUser:o.string(),afterUser:o.string(),beforeAssistant:o.string(),afterAssistant:o.string()}),Mw=o.object({template:o.string()}),jw=o.enum(["manual","jinja"]),ip=o.object({type:jw,manualPromptTemplate:Rw.optional(),jinjaPromptTemplate:Mw.optional(),stopStrings:o.array(o.string())}),Bw=o.enum(["none","json","gbnf"]),Jl=o.object({type:Bw,jsonSchema:Pe.optional(),gbnfGrammar:o.string().optional()}),sp=o.enum(["stopAtLimit","truncateMiddle","rollingWindow"]),op=o.object({enabled:o.boolean(),startString:o.string(),endString:o.string()}),Ql=o.object({maxTokens:o.number().int().min(-1).optional().or(o.literal(!1)),temperature:o.number().min(0).optional(),stopStrings:o.array(o.string()).optional(),toolCallStopStrings:o.array(o.string()).optional(),contextOverflowPolicy:sp.optional(),structured:o.union([Rr,Jl]).optional(),rawTools:Xh.optional(),toolNaming:np.optional(),topKSampling:o.number().optional(),repeatPenalty:o.number().optional().or(o.literal(!1)),minPSampling:o.number().optional().or(o.literal(!1)),topPSampling:o.number().optional().or(o.literal(!1)),cpuThreads:o.number().int().optional(),promptTemplate:ip.optional(),draftModel:o.string().optional(),speculativeDecodingNumDraftTokensExact:o.number().int().min(1).optional(),speculativeDecodingMinDraftLengthToConsider:o.number().int().min(0).optional(),speculativeDecodingMinContinueDraftingProbability:o.number().optional(),reasoningParsing:op.optional(),raw:te.optional()});o.object({...Ql.shape,structured:Jl.optional()});var Lw=o.object({version:o.union([o.literal(0),o.literal(1),o.literal(2)]),learningRate:o.number(),targetEntropy:o.number()}),Nw=o.union([o.number(),o.literal("-inf")]),$w=o.array(o.tuple([o.number(),Nw])),ap=o.enum(["none","reasoning","reasoningStartTag","reasoningEndTag"]),lp=o.object({content:o.string(),tokensCount:o.number().int(),containsDrafted:o.boolean(),reasoningType:ap,isStructural:o.boolean()}),cp=o.object({tokenCount:o.number().int().optional(),containsDrafted:o.boolean().optional(),reasoningType:ap.optional(),isStructural:o.boolean().optional()}),Uw=o.enum(["userStopped","modelUnloaded","failed","eosFound","stopStringFound","toolCalls","maxPredictedTokensReached","contextLengthReached"]),up=o.object({stopReason:Uw,tokensPerSecond:o.number().optional(),numGpuLayers:o.number().optional(),timeToFirstTokenSec:o.number().optional(),totalTimeSec:o.number().optional(),promptTokensCount:o.number().int().optional(),predictedTokensCount:o.number().int().optional(),totalTokensCount:o.number().int().optional(),usedDraftModelKey:o.string().optional(),totalDraftTokensCount:o.number().int().optional(),acceptedDraftTokensCount:o.number().int().optional(),rejectedDraftTokensCount:o.number().int().optional(),ignoredDraftTokensCount:o.number().int().optional()}),qw=o.object({indexedModelIdentifier:o.string(),identifier:o.string(),loadModelConfig:te,predictionConfig:te,stats:up}),zw=o.discriminatedUnion("type",[o.object({type:o.literal("beforeId"),id:o.string()}),o.object({type:o.literal("afterId"),id:o.string()})]),Vw=o.enum(["waiting","loading","done","error","canceled"]),dp=o.object({status:Vw,text:o.string()}),Xl=o.object({type:o.literal("status.create"),id:o.string(),state:dp,location:zw.optional(),indentation:o.number().int().optional()}),ec=o.object({type:o.literal("status.update"),id:o.string(),state:dp}),tc=o.object({type:o.literal("status.remove"),id:o.string()}),rc=o.object({type:o.literal("citationBlock.create"),id:o.string(),citedText:o.string(),fileName:o.string(),fileIdentifier:o.string(),pageNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional(),lineNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional()}),nc=o.object({type:o.literal("debugInfoBlock.create"),id:o.string(),debugInfo:o.string()}),fp=o.object({type:o.literal("contentBlock.create"),id:o.string(),includeInContext:o.boolean(),roleOverride:o.enum(["user","assistant","system","tool"]).optional(),style:Qh.optional(),prefix:o.string().optional(),suffix:o.string().optional()}),hp=o.object({type:o.literal("contentBlock.appendText"),id:o.string(),text:o.string(),tokensCount:o.number().int().optional(),fromDraftModel:o.boolean().optional(),isStructural:o.boolean().optional()}),pp=o.object({type:o.literal("contentBlock.appendToolResult"),id:o.string(),callId:o.number().int(),toolCallRequestId:o.string().optional(),content:o.string()}),mp=o.object({type:o.literal("contentBlock.appendToolRequest"),id:o.string(),callId:o.number().int(),toolCallRequestId:o.string().optional(),name:o.string(),parameters:o.record(o.unknown()),pluginIdentifier:o.string().optional()}),gp=o.object({type:o.literal("contentBlock.replaceToolRequest"),id:o.string(),callId:o.number().int(),toolCallRequestId:o.string().optional(),name:o.string(),parameters:o.record(o.unknown()),pluginIdentifier:o.string().optional()}),yp=o.object({type:o.literal("contentBlock.replaceText"),id:o.string(),text:o.string()}),Ww=o.object({type:o.literal("contentBlock.setPrefix"),id:o.string(),prefix:o.string()}),Gw=o.object({type:o.literal("contentBlock.setSuffix"),id:o.string(),suffix:o.string()}),bp=o.object({type:o.literal("contentBlock.attachGenInfo"),id:o.string(),genInfo:qw}),vp=o.object({type:o.literal("contentBlock.setStyle"),id:o.string(),style:Qh}),Zw=o.discriminatedUnion("type",[o.object({type:o.literal("generatingToolCall"),name:o.string().optional(),pluginIdentifier:o.string().optional(),argumentsString:o.string().optional()}),o.object({type:o.literal("toolCallGenerationFailed"),error:o.string(),rawContent:o.string().optional()}),o.object({type:o.literal("toolCallQueued")}),o.object({type:o.literal("confirmingToolCall")}),o.object({type:o.literal("toolCallDenied"),denyReason:o.string().optional()}),o.object({type:o.literal("callingTool")}),o.object({type:o.literal("toolCallFailed"),error:o.string()}),o.object({type:o.literal("toolCallSucceeded"),timeMs:o.number().int()})]),Dp=o.object({status:Zw,customStatus:o.string(),customWarnings:o.array(o.string())}),wp=o.object({type:o.literal("toolStatus.create"),id:o.string(),callId:o.number().int(),state:Dp}),Sp=o.object({type:o.literal("toolStatus.update"),id:o.string(),state:Dp}),Cp=o.object({type:o.literal("toolStatus.argumentFragment"),id:o.string(),content:o.string()}),Ep=o.object({type:o.literal("setSenderName"),name:o.string()}),Kw=o.discriminatedUnion("type",[Xl,ec,tc,rc,nc,fp,hp,mp,gp,pp,yp,Ww,Gw,bp,vp,wp,Sp,Cp,Ep]);o.discriminatedUnion("type",[Xl,ec,tc,rc,nc,fp,hp,yp,mp,gp,pp,bp,vp,wp,Sp,Cp,Ep]);var Hw=o.object({type:o.literal("confirmToolCall"),callId:o.number().int(),pluginIdentifier:o.string().optional(),name:o.string(),parameters:o.record(o.any())}),Yw=o.object({type:o.literal("textInput"),prompt:o.string()}),Jw=o.discriminatedUnion("type",[Hw,Yw]),Qw=o.object({type:o.literal("confirmToolCall"),result:o.discriminatedUnion("type",[o.object({type:o.literal("allow"),toolArgsOverride:o.record(o.any()).optional()}),o.object({type:o.literal("deny"),denyReason:o.string().optional()})])}),Xw=o.object({type:o.literal("textInput"),result:o.string()}),e1=o.discriminatedUnion("type",[Qw,Xw]);o.object({modelTag:o.string().optional(),ignoreUserConfig:o.boolean().optional()});o.discriminatedUnion("type",[Xl,ec,tc,rc,nc]);var t1=o.discriminatedUnion("type",[o.object({type:o.literal("model"),identifier:o.string()}),o.object({type:o.literal("generator"),pluginIdentifier:o.string()})]),r1=o.discriminatedUnion("type",[rp,Gh]),n1=o.discriminatedUnion("type",[Wa,Zh]),lh=o.discriminatedUnion("type",[o.object({type:o.literal("direct"),config:te,workingDirectoryPath:o.string().optional()}),o.object({type:o.literal("predictionProcess"),pci:o.string(),token:o.string()})]),ch=o.object({identifier:o.string(),isDev:o.boolean(),isTrusted:o.boolean(),hasPromptPreprocessor:o.boolean(),hasPredictionLoopHandler:o.boolean(),hasToolsProvider:o.boolean(),hasGenerator:o.boolean()}),uh=o.object({displayName:o.string(),sizeBytes:o.number(),quantName:o.string().optional(),compatibilityType:Js}),dh=o.enum(["pending","fetching","satisfied","completed"]),i1=o.discriminatedUnion("type",[o.object({type:o.literal("artifact"),owner:ni,name:ii,state:dh,artifactType:sw.optional(),sizeBytes:o.number().int().optional(),dependencyNodes:o.array(o.number().int())}),o.object({type:o.literal("model"),state:dh,resolvedSources:o.number().int().optional(),totalSources:o.number().int().optional(),alreadyOwned:uh.optional(),selected:uh.optional()})]),fh=o.object({nodes:o.array(i1),downloadSizeBytes:o.number().int()}),s1=o.object({relativePath:o.string(),sizeBytes:o.number().int()}),o1=o.object({files:o.array(s1),usedIgnoreFile:o.string().nullable()}),Ta=o.object({downloadedBytes:o.number().int(),totalBytes:o.number().int(),speedBytesPerSecond:o.number()}),a1=o.enum(["fullGPUOffload","partialGPUOffload","fitWithoutGPU","willNotFit"]),l1=o.object({quantization:o.string().optional(),name:o.string(),sizeBytes:o.number().int(),fitEstimation:a1,recommended:o.boolean().optional(),downloadIdentifier:o.string(),indexedModelIdentifier:o.string()}),_p=o.discriminatedUnion("type",[o.object({type:o.literal("catalog"),identifier:o.string()}),o.object({type:o.literal("hf"),identifier:o.string()})]),c1=o.object({name:o.string(),identifier:_p,exact:o.boolean().optional(),staffPick:o.boolean().optional()}),xp=o.object({searchTerm:o.string().optional(),limit:o.number().int().positive().max(25).optional(),compatibilityTypes:o.array(Js).optional()}),u1=o.object({content:o.string(),score:o.number(),sourceIndex:o.number().int(),pageNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional(),lineNumber:o.union([o.number().int(),o.tuple([o.number().int(),o.number().int()])]).optional()}),d1=o.object({entries:o.array(u1)});o.object({content:o.string(),score:o.number(),citation:aw});var kp=o.discriminatedUnion("type",[o.object({type:o.literal("recursive-v1"),chunkSize:o.number().int(),chunkOverlap:o.number().int()})]),Aa=o.enum(["loading","chunking","embedding"]),f1=o.enum(["unknown","integratedGpu","dedicatedGpu"]),h1=o.object({name:o.string(),deviceId:o.number().int(),totalMemoryBytes:o.number().int(),type:f1});o.object({key:o.string(),name:o.string(),accelerators:o.array(h1)});var p1=o.object({shortKey:o.string(),fullKey:o.string(),typeKey:o.string(),typeParams:Pe,defaultValue:Pe}),hh=o.object({fields:o.array(p1),extensionPrefixes:o.array(o.string()).optional()});o.object({fullKey:o.string(),error:Pe});var bs=o.union([o.literal(!0),o.literal(!1),o.literal("mixed")]),m1=o.object({domain:oi.optional(),architectures:o.array(o.string()).optional(),compatibilityTypes:o.array(Js).optional(),paramsStrings:o.array(o.string()).optional(),minMemoryUsageBytes:o.number().optional(),contextLengths:o.array(o.number()).optional(),trainedForToolUse:bs.optional(),vision:bs.optional(),reasoning:bs.optional(),fim:bs.optional()}),g1=o.object({key:o.string(),sources:o.array(jh)}),ic=o.object({type:o.literal("setJinjaVariable"),variable:o.string()}),y1=o.object({type:o.literal("prependSystemPrompt"),content:o.string()}),b1=o.object({type:o.literal("appendSystemPrompt"),content:o.string()}),sc=o.object({key:o.string(),displayName:o.string(),description:o.string()}),v1=sc.extend({type:o.literal("boolean"),defaultValue:o.boolean(),effects:o.array(o.discriminatedUnion("type",[ic,y1,b1]))}),D1=sc.extend({type:o.literal("string"),defaultValue:o.string(),effects:o.array(o.discriminatedUnion("type",[ic]))}),w1=sc.extend({type:o.literal("select"),options:o.array(o.object({label:o.string(),value:o.string()})),defaultValue:o.string(),effects:o.array(o.discriminatedUnion("type",[ic]))}),S1=o.discriminatedUnion("type",[v1,D1,w1]),C1=o.object({type:o.literal("equals"),key:o.string(),value:Pe}),E1=o.discriminatedUnion("type",[C1]),_1=o.object({message:o.string(),conditions:o.array(E1),fields:o.array(Jh).optional()});o.object({model:o.string().regex(/^[^/]+\/[^/]+$/),base:o.union([o.string(),o.array(g1)]),tags:o.array(o.string().max(100)).optional(),config:o.object({load:te.optional(),operation:te.optional()}).optional(),metadataOverrides:m1.optional(),customFields:o.array(S1).optional(),suggestions:o.array(_1).optional()});var x1=o.enum(["debug","info","warn","error"]);function L(t,e,r,n){if(r!==void 0)try{let i=r(...n);typeof i=="object"&&typeof i.catch=="function"&&i.catch(s=>{t.error(`Error in the ${e} callback (triggered asynchronously):`,s)})}catch(i){t.error(`Error in the ${e} callback:`,i)}}function k1(t){return t?.isSimpleLogger===!0}var F1=I.default.greenBright("I"),P1=I.default.yellowBright("W"),T1=I.default.redBright("E"),A1=I.default.blueBright("D"),Y=class t{constructor(e="",r=console,{useLogLevelPrefixes:n,infoPrefix:i,warnPrefix:s,errorPrefix:a,debugPrefix:l}={}){this.isSimpleLogger=!0,this.infoPrefix=[],this.warnPrefix=[],this.errorPrefix=[],this.debugPrefix=[],k1(r)?(n=n??r.opts.useLogLevelPrefixes,i=i===void 0?r.opts.infoPrefix:i,s=s===void 0?r.opts.warnPrefix:s,a=a===void 0?r.opts.errorPrefix:a,l=l===void 0?r.opts.debugPrefix:l,e===""?(this.innerPrefix=r.innerPrefix,this.fullPrefix=r.fullPrefix):(r.fullPrefix===""?this.innerPrefix=e:this.innerPrefix=`${r.innerPrefix}][${e}`,this.fullPrefix=I.default.whiteBright(`[${this.innerPrefix}]`)),this.parentLogger=r.parentLogger):(n=n??!1,i=i===void 0?F1:i,s=s===void 0?P1:s,a=a===void 0?T1:a,l=l===void 0?A1:l,e===""?(this.innerPrefix="",this.fullPrefix=""):(this.innerPrefix=e,this.fullPrefix=I.default.whiteBright(`[${this.innerPrefix}]`)),this.parentLogger=r),n&&(i!==null&&this.infoPrefix.push(i),s!==null&&this.warnPrefix.push(s),a!==null&&this.errorPrefix.push(a),l!==null&&this.debugPrefix.push(l)),this.fullPrefix!==""&&(this.infoPrefix.push(this.fullPrefix),this.warnPrefix.push(this.fullPrefix),this.errorPrefix.push(this.fullPrefix),this.debugPrefix.push(this.fullPrefix)),this.opts={useLogLevelPrefixes:n,infoPrefix:i,warnPrefix:s,errorPrefix:a,debugPrefix:l}}subclass(e){return new t(`${this.innerPrefix}:${e}`,this.parentLogger)}info(...e){this.parentLogger.info(...this.infoPrefix,...e)}infoText(e,...r){this.info(j(e,...r))}infoWithoutPrefix(...e){this.parentLogger.info(...e)}error(...e){this.parentLogger.error(...this.errorPrefix,...e)}errorText(e,...r){this.error(j(e,...r))}errorWithoutPrefix(...e){this.parentLogger.error(...e)}warn(...e){this.parentLogger.warn(...this.warnPrefix,...e)}warnText(e,...r){this.warn(j(e,...r))}warnWithoutPrefix(...e){this.parentLogger.warn(...e)}debug(...e){this.parentLogger.debug(...this.debugPrefix,...e)}debugText(e,...r){this.debug(j(e,...r))}debugWithoutPrefix(...e){this.parentLogger.debug(...e)}throw(e){throw new Error(`${this.fullPrefix} ${e}`)}logAtLevel(e,...r){switch(e){case"debug":this.debug(...r);break;case"info":this.info(...r);break;case"warn":this.warn(...r);break;case"error":this.error(...r);break}}static fromMultiple(e,r){return new t("",{debug:(...n)=>{for(let i of e)i.debug(...n)},info:(...n)=>{for(let i of e)i.info(...n)},warn:(...n)=>{for(let i of e)i.warn(...n)},error:(...n)=>{for(let i of e)i.error(...n)}},{...r,useLogLevelPrefixes:!1})}},ph,mh=Symbol("finished"),Rs=class{finished(e){if(this.status!=="pending")throw new Error("`finished` called while not pending");e===void 0?(this.status="resolved",this.nextFragmentPromiseBundle?.resolve(mh),this.resolveFinal(this.collect(this.buffer))):(this.status="rejected",this.nextFragmentPromiseBundle?.reject(e),this.rejectFinal(e))}push(e){if(this.status!=="pending")throw new Error("`push` called while not pending");this.buffer.push(e),this.nextFragmentPromiseBundle?.resolve(e),this.nextFragmentPromiseBundle=null}constructor(){this.status="pending",this.buffer=[],this.nextFragmentPromiseBundle=null,this.hasIterator=!1,this[ph]="StreamablePromise";let{promise:e,resolve:r,reject:n}=re();this.promiseFinal=e,this.resolveFinal=r,this.rejectFinal=n}then(e,r){return this.promiseFinal.then(e,r)}catch(e){return this.promiseFinal.catch(e)}finally(e){return this.promiseFinal.finally(e)}obtainNextFragmentPromiseBundle(){return this.nextFragmentPromiseBundle===null&&(this.nextFragmentPromiseBundle=re()),this.nextFragmentPromiseBundle}async*[(ph=Symbol.toStringTag,Symbol.asyncIterator)](){this.hasIterator||(this.promiseFinal.catch(()=>{}),this.hasIterator=!0);let e=0;for(;e<this.buffer.length||this.status==="pending";)if(e<this.buffer.length)yield this.buffer[e],e++;else{let n=await this.obtainNextFragmentPromiseBundle().promise;if(n===mh)break;yield n,e++}await this.promiseFinal,await Promise.resolve()}},ot=class t{constructor({attachStack:e}={}){this.attachStack=e??!0}static prettyPrintZod(e,r){return r.errors.map(n=>{if(n.path.length===0)return`- ${I.default.redBright(e)}: ${n.message}`;let i=I.default.red(`.${n.path.join(".")}`);return`- ${I.default.redBright(e)}${i}: ${n.message}`}).join(`
176
176
  `)}validateOrThrow(e,r,n,i,s){let a=n.safeParse(i);if(a.success)return a.data;throw Ee(`${e}
177
177
 
178
178
  ${t.prettyPrintZod(r,a.error)}`,this.attachStack?s:void 0)}validateMultipleOrThrow(e,r,n,i,s){let a=n.map((c,u)=>c.safeParse(i[u])),l=a.map((c,u)=>({result:c,index:u,rootObjectName:r[u]})).filter(({result:c})=>!c.success).map(({result:c,rootObjectName:u,index:h})=>({error:c.error,rootObjectName:u,index:h}));if(l.length===0)return a.map(c=>c.data);{let c=new Set(l.map(({index:h})=>h)),u=e(c);throw Ee(`${u}
@@ -186,7 +186,7 @@ ${l.map(({error:h,rootObjectName:f})=>t.prettyPrintZod(f,h)).join(`
186
186
  ${e}(${I.default.redBright(r)})
187
187
  `);return this.validateOrThrow(`Invalid parameter(s) when constructing ${a}`,r,n,i,s)}validateConstructorParamsOrThrow(e,r,n,i,s){return this.validateMultipleOrThrow(a=>{let l=r.map((u,h)=>a.has(h)?I.default.redBright(u):u);return`Invalid parameter(s) when constructing ${I.default.yellowBright(j`
188
188
  ${e}(${l.join(", ")})
189
- `)}:`},r,n,i,s)}},kp=new it,Ce=class{constructor(e,r,n,i,s){this.filesNamespace=e,this.identifier=r,this.type=n,this.sizeBytes=i,this.name=s,this.parsedIdentifier=LD(r)}async getFilePath(){switch(this.parsedIdentifier.type){case"local":return(await this.filesNamespace.getLocalFileAbsolutePath(this.parsedIdentifier.fileName)).path;case"base64":throw new Error("Not implemented. Please open an issue on GitHub if you encountered this error.");default:{let e=this.parsedIdentifier;throw new Error(`Unexpected file identifier type: ${JSON.stringify(e)}`)}}}isImage(){return this.type==="image"}},sc=o.object({role:o.enum(["user","assistant","system"]).optional(),content:o.string().optional(),images:o.array(o.instanceof(Ce)).optional()}),A1=o.array(sc);function O1(t){return!Array.isArray(t.content)}function I1(t){return!("messages"in t)}function Wa(t){let{role:e,content:r,images:n}=t,i=[];if(n===void 0||n.length===0)r===void 0&&i.push({type:"text",text:""});else for(let s of n)i.push({type:"file",identifier:s.identifier,name:s.name,fileType:s.type,sizeBytes:s.sizeBytes});return r!==void 0&&i.push({type:"text",text:r}),{role:e??"user",content:i}}var Et=class t extends As{getClassName(){return"Chat"}create(e,r){return new t(e,r)}cloneData(e){return Fr.parse(e)}constructor(e,r){super(e,r)}static empty(){return new t({messages:[]},!0)}static from(e){let r=A(1);if(kp.validateMethodParamOrThrow("Chat","from","initializer",gn,e,r),e instanceof t)return e.asMutableCopy();if(typeof e=="string"){let n=t.empty();return n.append("user",e),n}return Array.isArray(e)?new t({messages:e.map(Wa)},!0):I1(e)?new t({messages:[Wa(e)]},!0):new t(e,!1).asMutableCopy()}static createRaw(e,r){return new t(e,r)}getRaw(){return this.data}append(...e){if(this.guardMutable(),e.length===1){let[r]=e,n=he.from(r),i=n._internalToMutable();this.data.messages.push(i._internalGetData())}else{let[r,n,i={}]=e;if(r==="user"||r==="system"||r==="assistant"){let s=[{type:"text",text:n}];if(i.images!==void 0)for(let a of i.images)s.push({type:"file",name:a.name,identifier:a.identifier,sizeBytes:a.sizeBytes,fileType:a.type});this.data.messages.push({role:r,content:s})}else throw new Error(j`
189
+ `)}:`},r,n,i,s)}},Fp=new ot,Ce=class{constructor(e,r,n,i,s){this.filesNamespace=e,this.identifier=r,this.type=n,this.sizeBytes=i,this.name=s,this.parsedIdentifier=ND(r)}async getFilePath(){switch(this.parsedIdentifier.type){case"local":return(await this.filesNamespace.getLocalFileAbsolutePath(this.parsedIdentifier.fileName)).path;case"base64":throw new Error("Not implemented. Please open an issue on GitHub if you encountered this error.");default:{let e=this.parsedIdentifier;throw new Error(`Unexpected file identifier type: ${JSON.stringify(e)}`)}}}isImage(){return this.type==="image"}},oc=o.object({role:o.enum(["user","assistant","system"]).optional(),content:o.string().optional(),images:o.array(o.instanceof(Ce)).optional()}),O1=o.array(oc);function I1(t){return!Array.isArray(t.content)}function R1(t){return!("messages"in t)}function Ga(t){let{role:e,content:r,images:n}=t,i=[];if(n===void 0||n.length===0)r===void 0&&i.push({type:"text",text:""});else for(let s of n)i.push({type:"file",identifier:s.identifier,name:s.name,fileType:s.type,sizeBytes:s.sizeBytes});return r!==void 0&&i.push({type:"text",text:r}),{role:e??"user",content:i}}var _t=class t extends As{getClassName(){return"Chat"}create(e,r){return new t(e,r)}cloneData(e){return Fr.parse(e)}constructor(e,r){super(e,r)}static empty(){return new t({messages:[]},!0)}static from(e){let r=A(1);if(Fp.validateMethodParamOrThrow("Chat","from","initializer",gn,e,r),e instanceof t)return e.asMutableCopy();if(typeof e=="string"){let n=t.empty();return n.append("user",e),n}return Array.isArray(e)?new t({messages:e.map(Ga)},!0):R1(e)?new t({messages:[Ga(e)]},!0):new t(e,!1).asMutableCopy()}static createRaw(e,r){return new t(e,r)}getRaw(){return this.data}append(...e){if(this.guardMutable(),e.length===1){let[r]=e,n=he.from(r),i=n._internalToMutable();this.data.messages.push(i._internalGetData())}else{let[r,n,i={}]=e;if(r==="user"||r==="system"||r==="assistant"){let s=[{type:"text",text:n}];if(i.images!==void 0)for(let a of i.images)s.push({type:"file",name:a.name,identifier:a.identifier,sizeBytes:a.sizeBytes,fileType:a.type});this.data.messages.push({role:r,content:s})}else throw new Error(j`
190
190
  Unsupported role for append() API with [role, content] parameters: ${r}.
191
191
  Supported roles are 'user', 'system', and 'assistant'.
192
192
  `)}}withAppended(...e){let r=this.asMutableCopy();return r.append(...e),r}getLength(){return this.data.messages.length}get length(){return this.getLength()}pop(){if(this.guardMutable(),this.data.messages.length===0)throw new Error("Tried to pop from an empty history.");let e=this.data.messages.pop();return he.createRaw(e,!0)}getAllFiles(e){return this.data.messages.flatMap(r=>r.content.filter(n=>n.type==="file")).map(r=>new Ce(e.files,r.identifier,r.fileType,r.sizeBytes,r.name))}*files(e){for(let r of this.data.messages)for(let n of r.content)n.type==="file"&&(yield new Ce(e.files,n.identifier,n.fileType,n.sizeBytes,n.name))}hasFiles(){return this.data.messages.some(e=>e.content.some(r=>r.type==="file"))}at(e){let r=e;if(e<0&&(r=this.data.messages.length+e),r<0||r>=this.data.messages.length)throw new Error(j`
@@ -199,11 +199,11 @@ ${l.map(({error:h,rootObjectName:f})=>t.prettyPrintZod(f,h)).join(`
199
199
  `).map(n=>" "+n).join(`
200
200
  `)).join(`
201
201
  `)+`
202
- }`}},gn=o.union([o.instanceof(Et),Fr,o.string(),A1,sc]),he=class t extends As{getClassName(){return"ChatMessage"}create(e,r){return new t(e,r)}cloneData(e){return kr.parse(e)}constructor(e,r){super(e,r)}static create(e,r){return new t(kr.parse({role:e,content:[{type:"text",text:r}]}),!0)}static from(e){let r=A(1);return kp.validateMethodParamOrThrow("ChatMessage","from","initializer",R1,e,r),e instanceof t?e.asMutableCopy():typeof e=="string"?new t(kr.parse({role:"user",content:[{type:"text",text:e}]}),!0):O1(e)?new t(Wa(e),!0):new t(e,!0)}static createRaw(e,r){return new t(e,r)}getRaw(){return this.data}getRole(){return this.data.role}setRole(e){this.guardMutable(),this.data.role=e}getFileParts(){return this.data.content.filter(e=>e.type==="file")}getText(){return this.data.content.filter(e=>e.type==="text").map(e=>e.text).join(" ")}getToolCallResults(){return this.data.content.filter(e=>e.type==="toolCallResult").map(e=>({content:e.content,toolCallId:e.toolCallId}))}getToolCallRequests(){return this.data.content.filter(e=>e.type==="toolCallRequest").map(e=>e.toolCallRequest)}getFiles(e){return this.getFileParts().map(r=>new Ce(e.files,r.identifier,r.fileType,r.sizeBytes,r.name))}*files(e){for(let r of this.getFileParts())yield new Ce(e.files,r.identifier,r.fileType,r.sizeBytes,r.name)}consumeFiles(e,r){this.guardMutable();let n=[],i=new Set;for(let[s,a]of this.data.content.entries()){if(a.type!=="file")continue;let l=new Ce(e.files,a.identifier,a.fileType,a.sizeBytes,a.name);r(l)&&(n.push(l),i.add(s))}return this.data.content=this.data.content.filter((s,a)=>!i.has(a)),n}async consumeFilesAsync(e,r){this.guardMutable();let n=[],i=new Set;for(let[s,a]of this.data.content.entries()){if(a.type!=="file")continue;let l=new Ce(e.files,a.identifier,a.fileType,a.sizeBytes,a.name);await r(l)&&(n.push(l),i.add(s))}return this.data.content=this.data.content.filter((s,a)=>!i.has(a)),n}hasFiles(){return this.data.content.some(e=>e.type==="file")}appendText(e){switch(this.guardMutable(),this.data.role){case"assistant":case"user":case"system":this.data.content.push({type:"text",text:e});break;case"tool":throw new Error(`Cannot append text to a message with role "${this.data.role}"`);default:{let r=this.data;throw new Error(`Unhandled role in switch statement: ${r.role}`)}}}appendFile(e){switch(this.guardMutable(),this.data.role){case"assistant":case"user":case"system":this.data.content.push({type:"file",name:e.name,identifier:e.identifier,sizeBytes:e.sizeBytes,fileType:e.type});break;case"tool":throw new Error(`Cannot append text to a message with role "${this.data.role}"`);default:{let r=this.data;throw new Error(`Unhandled role in switch statement: ${r.role}`)}}}replaceText(e){switch(this.guardMutable(),this.data.role){case"assistant":case"user":case"system":this.data.content=[{type:"text",text:e},...this.data.content.filter(r=>r.type!=="text")];break;case"tool":throw new Error(`Cannot replace text in a message with role "${this.data.role}"`);default:{let r=this.data;throw new Error(`Unhandled role in switch statement: ${r.role}`)}}}isSystemPrompt(){return this.data.role==="system"}isUserMessage(){return this.data.role==="user"}isAssistantMessage(){return this.data.role==="assistant"}toString(){let e=this.data.content.map(r=>{switch(r.type){case"text":return r.text;case"file":return`<file ${r.name}>`;case"toolCallRequest":return r.toolCallRequest.name+`(${JSON.stringify(r.toolCallRequest.arguments)})`;case"toolCallResult":return r.content;default:{let n=r;throw new Error(`Unknown part type: ${n.type}`)}}}).join(" ");return e.includes(`
202
+ }`}},gn=o.union([o.instanceof(_t),Fr,o.string(),O1,oc]),he=class t extends As{getClassName(){return"ChatMessage"}create(e,r){return new t(e,r)}cloneData(e){return kr.parse(e)}constructor(e,r){super(e,r)}static create(e,r){return new t(kr.parse({role:e,content:[{type:"text",text:r}]}),!0)}static from(e){let r=A(1);return Fp.validateMethodParamOrThrow("ChatMessage","from","initializer",M1,e,r),e instanceof t?e.asMutableCopy():typeof e=="string"?new t(kr.parse({role:"user",content:[{type:"text",text:e}]}),!0):I1(e)?new t(Ga(e),!0):new t(e,!0)}static createRaw(e,r){return new t(e,r)}getRaw(){return this.data}getRole(){return this.data.role}setRole(e){this.guardMutable(),this.data.role=e}getFileParts(){return this.data.content.filter(e=>e.type==="file")}getText(){return this.data.content.filter(e=>e.type==="text").map(e=>e.text).join(" ")}getToolCallResults(){return this.data.content.filter(e=>e.type==="toolCallResult").map(e=>({content:e.content,toolCallId:e.toolCallId}))}getToolCallRequests(){return this.data.content.filter(e=>e.type==="toolCallRequest").map(e=>e.toolCallRequest)}getFiles(e){return this.getFileParts().map(r=>new Ce(e.files,r.identifier,r.fileType,r.sizeBytes,r.name))}*files(e){for(let r of this.getFileParts())yield new Ce(e.files,r.identifier,r.fileType,r.sizeBytes,r.name)}consumeFiles(e,r){this.guardMutable();let n=[],i=new Set;for(let[s,a]of this.data.content.entries()){if(a.type!=="file")continue;let l=new Ce(e.files,a.identifier,a.fileType,a.sizeBytes,a.name);r(l)&&(n.push(l),i.add(s))}return this.data.content=this.data.content.filter((s,a)=>!i.has(a)),n}async consumeFilesAsync(e,r){this.guardMutable();let n=[],i=new Set;for(let[s,a]of this.data.content.entries()){if(a.type!=="file")continue;let l=new Ce(e.files,a.identifier,a.fileType,a.sizeBytes,a.name);await r(l)&&(n.push(l),i.add(s))}return this.data.content=this.data.content.filter((s,a)=>!i.has(a)),n}hasFiles(){return this.data.content.some(e=>e.type==="file")}appendText(e){switch(this.guardMutable(),this.data.role){case"assistant":case"user":case"system":this.data.content.push({type:"text",text:e});break;case"tool":throw new Error(`Cannot append text to a message with role "${this.data.role}"`);default:{let r=this.data;throw new Error(`Unhandled role in switch statement: ${r.role}`)}}}appendFile(e){switch(this.guardMutable(),this.data.role){case"assistant":case"user":case"system":this.data.content.push({type:"file",name:e.name,identifier:e.identifier,sizeBytes:e.sizeBytes,fileType:e.type});break;case"tool":throw new Error(`Cannot append text to a message with role "${this.data.role}"`);default:{let r=this.data;throw new Error(`Unhandled role in switch statement: ${r.role}`)}}}replaceText(e){switch(this.guardMutable(),this.data.role){case"assistant":case"user":case"system":this.data.content=[{type:"text",text:e},...this.data.content.filter(r=>r.type!=="text")];break;case"tool":throw new Error(`Cannot replace text in a message with role "${this.data.role}"`);default:{let r=this.data;throw new Error(`Unhandled role in switch statement: ${r.role}`)}}}isSystemPrompt(){return this.data.role==="system"}isUserMessage(){return this.data.role==="user"}isAssistantMessage(){return this.data.role==="assistant"}toString(){let e=this.data.content.map(r=>{switch(r.type){case"text":return r.text;case"file":return`<file ${r.name}>`;case"toolCallRequest":return r.toolCallRequest.name+`(${JSON.stringify(r.toolCallRequest.arguments)})`;case"toolCallResult":return r.content;default:{let n=r;throw new Error(`Unknown part type: ${n.type}`)}}}).join(" ");return e.includes(`
203
203
  `)?this.data.role+`:
204
204
  `+e.split(`
205
205
  `).map(r=>" "+r).join(`
206
- `):this.data.role+": "+e}},R1=o.union([o.instanceof(he),sc,o.string(),kr]),Ga=class{constructor(e){this.baseSchema=e,this.valueTypes=new Map}valueType(e,r){if(this.valueTypes.has(e))throw new Error(`ValueType with key ${e} already exists`);return this.valueTypes.set(e,{paramType:o.object({...this.baseSchema,...r.paramType}),schemaMaker:r.schemaMaker,effectiveEquals:r.effectiveEquals,stringify:r.stringify}),this}build(){return new Za(new Map(this.valueTypes))}},Za=class{constructor(e){this.valueTypes=e}getSchema(e,r){let n=this.valueTypes.get(e);if(n===void 0)throw new Error(`Cannot find value type ${e}`);return n.schemaMaker(n.paramType.parse(r))}parseParamTypes(e,r){return this.valueTypes.get(e).paramType.parse(r)}effectiveEquals(e,r,n,i){return this.valueTypes.get(e).effectiveEquals(n,i,r)}stringify(e,r,n,i){return this.valueTypes.get(e).stringify(i,r,n)}},Ms=class t{constructor(e){this.valueTypeLibrary=e,this.fields=new Map,this.extensionPrefixes=[]}field(e,r,n,i){let a=this.valueTypeLibrary.getSchema(r,n).safeParse(i);if(!a.success)throw new Error(`Invalid default value for field ${e}: ${a.error.message}`);if(i=a.data,this.fields.has(e))throw new Error(`Cannot add field with key ${e}. Key already exists in the schematics.`);return this.fields.set(e,{valueTypeKey:r,valueTypeParams:n,schema:this.valueTypeLibrary.getSchema(r,n),fullKey:e,defaultValue:i}),this}extension(e){return this.extensionPrefixes.push(`${e}.`),this}scope(e,r){let n=r(new t(this.valueTypeLibrary));for(let[i,{valueTypeKey:s,valueTypeParams:a,schema:l,defaultValue:c}]of n.fields.entries()){let u=`${e}.${i}`;if(this.fields.has(u))throw new Error(`Cannot add field with key ${u}. Key already exists in the schematics.`);this.fields.set(u,{valueTypeKey:s,valueTypeParams:a,schema:l,fullKey:u,defaultValue:c})}return this.extensionPrefixes.push(...n.extensionPrefixes.map(i=>`${e}.${i}`)),this}build(){return new ai(this.valueTypeLibrary,this.fields,this.extensionPrefixes)}},js=Symbol("createParsedKVConfig"),ai=class t{constructor(e,r,n){this.valueTypeLibrary=e,this.fields=r,this.extensionPrefixes=n,this.fullKepMap=void 0,this.lenientZodSchema=void 0}getFieldsMap(){return new Map([...this.fields.values()].map(e=>[e.fullKey,e]))}obtainField(e){let r=this.fields.get(e);if(r===void 0){let n=[...this.fields.keys()],i=n.slice(0,10).map(s=>`- ${s}`).join(`
206
+ `):this.data.role+": "+e}},M1=o.union([o.instanceof(he),oc,o.string(),kr]),Za=class{constructor(e){this.baseSchema=e,this.valueTypes=new Map}valueType(e,r){if(this.valueTypes.has(e))throw new Error(`ValueType with key ${e} already exists`);return this.valueTypes.set(e,{paramType:o.object({...this.baseSchema,...r.paramType}),schemaMaker:r.schemaMaker,effectiveEquals:r.effectiveEquals,stringify:r.stringify}),this}build(){return new Ka(new Map(this.valueTypes))}},Ka=class{constructor(e){this.valueTypes=e}getSchema(e,r){let n=this.valueTypes.get(e);if(n===void 0)throw new Error(`Cannot find value type ${e}`);return n.schemaMaker(n.paramType.parse(r))}parseParamTypes(e,r){return this.valueTypes.get(e).paramType.parse(r)}effectiveEquals(e,r,n,i){return this.valueTypes.get(e).effectiveEquals(n,i,r)}stringify(e,r,n,i){return this.valueTypes.get(e).stringify(i,r,n)}},Ms=class t{constructor(e){this.valueTypeLibrary=e,this.fields=new Map,this.extensionPrefixes=[]}field(e,r,n,i){let a=this.valueTypeLibrary.getSchema(r,n).safeParse(i);if(!a.success)throw new Error(`Invalid default value for field ${e}: ${a.error.message}`);if(i=a.data,this.fields.has(e))throw new Error(`Cannot add field with key ${e}. Key already exists in the schematics.`);return this.fields.set(e,{valueTypeKey:r,valueTypeParams:n,schema:this.valueTypeLibrary.getSchema(r,n),fullKey:e,defaultValue:i}),this}extension(e){return this.extensionPrefixes.push(`${e}.`),this}scope(e,r){let n=r(new t(this.valueTypeLibrary));for(let[i,{valueTypeKey:s,valueTypeParams:a,schema:l,defaultValue:c}]of n.fields.entries()){let u=`${e}.${i}`;if(this.fields.has(u))throw new Error(`Cannot add field with key ${u}. Key already exists in the schematics.`);this.fields.set(u,{valueTypeKey:s,valueTypeParams:a,schema:l,fullKey:u,defaultValue:c})}return this.extensionPrefixes.push(...n.extensionPrefixes.map(i=>`${e}.${i}`)),this}build(){return new ai(this.valueTypeLibrary,this.fields,this.extensionPrefixes)}},js=Symbol("createParsedKVConfig"),ai=class t{constructor(e,r,n){this.valueTypeLibrary=e,this.fields=r,this.extensionPrefixes=n,this.fullKepMap=void 0,this.lenientZodSchema=void 0}getFieldsMap(){return new Map([...this.fields.values()].map(e=>[e.fullKey,e]))}obtainField(e){let r=this.fields.get(e);if(r===void 0){let n=[...this.fields.keys()],i=n.slice(0,10).map(s=>`- ${s}`).join(`
207
207
  `);throw n.length>10&&(i+=`
208
208
  ... and ${n.length-10} more`),new Error(`Cannot access key ${e}. Key does not exist in the schematics. Available keys:
209
209
 
@@ -211,25 +211,25 @@ ${l.map(({error:h,rootObjectName:f})=>t.prettyPrintZod(f,h)).join(`
211
211
  `);throw n.length>10&&(i+=`
212
212
  ... and ${n.length-10} more`),new Error(`Cannot access full key ${e}. Full key does not exist in the schematics. Availablekeys:
213
213
 
214
- `+i)}return r}getSchemaForKey(e){return this.obtainField(e).schema}parseField(e,r){if(r===void 0){if(e.defaultValue===void 0)throw new Error(`Field with key ${e.fullKey} is missing and has no default value`);return e.defaultValue}let n=e.schema.safeParse(r);if(!n.success)throw new Error(`Field with key ${e.fullKey} does not satisfy the schema:`+n.error.message);return n.data}parseFieldWithoutDefault(e,r){if(r===void 0)return;let n=e.schema.safeParse(r);if(!n.success)throw new Error(`Field with key ${e.fullKey} does not satisfy the schema:`+n.error.message);return n.data}access(e,r){let n=this.obtainField(r);return this.parseField(n,e.fields.find(i=>i.key===n.fullKey)?.value)}accessByFullKey(e,r){let n=this.obtainFieldByFullKey(r);return this.parseField(n,e.fields.find(i=>i.key===n.fullKey)?.value)}accessPartial(e,r){let n=this.obtainField(r);return this.parseFieldWithoutDefault(n,e.fields.find(i=>i.key===n.fullKey)?.value)}sliced(...e){let r=e.map(i=>i.endsWith("*")?{type:"prefix",value:i.substring(0,i.length-1)}:{type:"exact",value:i}),n=new Map;for(let[i,s]of this.fields.entries())for(let a of r)(a.type==="exact"&&i===a.value||a.type==="prefix"&&i.startsWith(a.value))&&n.set(i,s);return new t(this.valueTypeLibrary,n,this.extensionPrefixes)}scoped(e){let r=new Map;for(let[n,i]of this.fields.entries())n.startsWith(`${e}.`)&&r.set(n.substring(e.length+1),i);return new t(this.valueTypeLibrary,r,this.extensionPrefixes)}union(e){let r=new Map;for(let[n,i]of this.fields.entries())r.set(n,i);for(let[n,i]of e.fields.entries()){if(r.has(n))throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: "+n);r.set(n,i)}return new t(this.valueTypeLibrary,r,[...this.extensionPrefixes,...e.extensionPrefixes])}flattenBaseKey(){let e=new Map;for(let r of this.fields.values())e.set(r.fullKey,r);return new t(this.valueTypeLibrary,e,this.extensionPrefixes)}parseToMap(e){let r=vt(e),n=new Map;for(let[i,s]of this.fields.entries()){let a=r.get(s.fullKey),l=this.parseField(s,a);n.set(i,l)}return n}parseToMapWithFullKey(e){let r=vt(e),n=new Map;for(let i of this.fields.values()){let s=r.get(i.fullKey),a=this.parseField(i,s);n.set(i.fullKey,a)}return n}parseToMapPartial(e){let r=vt(e),n=new Map;for(let[i,s]of this.fields.entries()){let a=r.get(s.fullKey),l=this.parseFieldWithoutDefault(s,a);l!==void 0&&n.set(i,l)}return n}parse(e){return Ha[js](this.parseToMap(e))}parsePartial(e){return Ya[js](this.parseToMapPartial(e))}buildFullConfig(e){return{fields:Array.from(this.fields.entries()).map(([r,n])=>{let i=this.parseField(n,e[r]);return{key:n.fullKey,value:i}})}}buildPartialConfig(e){return{fields:Object.entries(e).filter(([r,n])=>n!==void 0).map(([r,n])=>{let i=this.obtainField(r);return{key:i.fullKey,value:this.parseField(i,n)}})}}createBuildPartialConfigInput(){return{}}configBuilder(){return new Ka(this.fields)}clone(){return new t(this.valueTypeLibrary,new Map(this.fields),this.extensionPrefixes)}withTypeParamOverride(e,r){let n=this.obtainField(e),i=this.clone();return i.fields.set(e,{...n,valueTypeParams:r(n.valueTypeParams),schema:this.valueTypeLibrary.getSchema(n.valueTypeKey,r(n.valueTypeParams))}),i}getFullKeyMap(){return this.fullKepMap!==void 0?this.fullKepMap:(this.fullKepMap=new Map([...this.fields.values()].map(e=>[e.fullKey,e])),this.fullKepMap)}makeLenientZodSchema(){let e=this.getFullKeyMap();return te.transform(r=>{let n=new Set;return{fields:r.fields.filter(i=>{if(this.extensionPrefixes.some(l=>i.key.startsWith(l)))return!0;if(n.has(i.key))return!1;let s=e.get(i.key);return s===void 0||!s.schema.safeParse(i.value).success?!1:(n.add(i.key),!0)})}})}getLenientZodSchema(){return this.lenientZodSchema!==void 0?this.lenientZodSchema:(this.lenientZodSchema=this.makeLenientZodSchema(),this.lenientZodSchema)}getValueType(e){let r=this.fields.get(e);return r===void 0?null:r.valueTypeKey}getValueTypeParam(e){let r=this.fields.get(e);return r===void 0?null:r.valueTypeParams}getValueTypeParamByFullKey(e){let r=this.getFullKeyMap().get(e);if(r===void 0)throw new Error(`Field with key ${e} does not exist in the schematics`);return r.valueTypeParams}hasFullKey(e){return this.getFullKeyMap().get(e)!==void 0}filterConfig(e,r){let n=this.getFullKeyMap();return{fields:e.fields.filter(i=>{let s=n.get(i.key);return s===void 0?!1:r!==void 0?r(s.fullKey,{type:s.valueTypeKey,param:s.valueTypeParams}):!0})}}filterStack(e){return{layers:e.layers.map(r=>({layerName:r.layerName,config:this.filterConfig(r.config)}))}}twoWayFilterConfig(e,r){let n=[],i=[],s=this.getFullKeyMap();for(let a of e.fields){let l=s.get(a.key),c=l!==void 0;l!==void 0&&r!==void 0&&(c=r(l.fullKey,{type:l.valueTypeKey,param:l.valueTypeParams})),c?n.push(a):i.push(a)}return[{fields:n},{fields:i}]}filterFullKeys(e){let r=this.getFullKeyMap();return e.filter(n=>r.has(n))}configEffectiveEquals(e,r){let n=vt(e),i=vt(r);for(let s of this.fields.values()){let a=n.get(s.fullKey),l=i.get(s.fullKey);if(a===void 0){if(l===void 0)continue;return!1}this.valueTypeLibrary.effectiveEquals(s.valueTypeKey,s.valueTypeParams,a,l)}return!0}fieldEffectiveEquals(e,r,n){let i=this.obtainField(e);return this.valueTypeLibrary.effectiveEquals(i.valueTypeKey,i.valueTypeParams,i.schema.parse(r),i.schema.parse(n))}fieldEffectiveEqualsWithFullKey(e,r,n){let s=this.getFullKeyMap().get(e);if(s===void 0)throw new Error(`Field with key ${e} does not exist in the schematics`);return this.valueTypeLibrary.effectiveEquals(s.valueTypeKey,s.valueTypeParams,s.schema.parse(r),s.schema.parse(n))}makeInternalFieldStringifyOpts(e){return{t:e.t??((r,n)=>n),desiredLength:e.desiredLength}}stringifyField(e,r,n={}){let i=this.obtainField(e);return this.valueTypeLibrary.stringify(i.valueTypeKey,i.valueTypeParams,this.makeInternalFieldStringifyOpts(n),r)}tryStringifyFieldWithFullKey(e,r,n){let s=this.getFullKeyMap().get(e);return s===void 0?null:this.valueTypeLibrary.stringify(s.valueTypeKey,s.valueTypeParams,this.makeInternalFieldStringifyOpts(n),r)}apply(e,r){let n=this.filterConfig(r);return Fp([e,n])}unApply(e,r){let n=this.filterConfig(r),i=vt(n),s=new Map(vt(e)),a=this.getFullKeyMap();for(let[l,c]of i.entries()){let u=a.get(l);if(u===void 0)continue;let h=s.get(l);if(h!==void 0){if(!this.valueTypeLibrary.effectiveEquals(u.valueTypeKey,u.valueTypeParams,c,h))continue;s.delete(l)}}return oc(s)}*iterateFieldsOfConfig(e){let r=this.getFullKeyMap();for(let{key:n,value:i}of e.fields)r.get(n)!==void 0&&(yield[n,i])}*fullKeys(){let e=this.getFullKeyMap();for(let r of e.keys())yield r}effectiveCompareConfig(e,r,n={}){let{fieldFilter:i}=n,s=vt(e),a=vt(r),l=[],c=[],u=[];for(let h of this.fields.values()){if(i!==void 0&&!i(h.fullKey,{type:h.valueTypeKey,param:h.valueTypeParams}))continue;let f=s.get(h.fullKey),d=a.get(h.fullKey);if(f===void 0){if(d===void 0)continue;c.push(h.fullKey)}else d===void 0?l.push(h.fullKey):this.valueTypeLibrary.effectiveEquals(h.valueTypeKey,h.valueTypeParams,f,d)||u.push(h.fullKey)}return{onlyInA:l,onlyInB:c,inBothButDifferent:u}}serialize(){return{fields:[...this.fields.entries()].map(([e,r])=>({shortKey:e,fullKey:r.fullKey,typeKey:r.valueTypeKey,typeParams:r.valueTypeParams,defaultValue:r.defaultValue})),extensionPrefixes:this.extensionPrefixes}}hasFieldsWithPrefix(e){for(let r of this.fields.values())if(r.fullKey.startsWith(e))return!0;return!1}static deserialize(e,r){let n=new Map(r.fields.map(i=>{let s=e.parseParamTypes(i.typeKey,i.typeParams),a=e.getSchema(i.typeKey,s);return[i.shortKey,{valueTypeKey:i.typeKey,valueTypeParams:s,schema:a,fullKey:i.fullKey,defaultValue:a.parse(i.defaultValue)}]}));return new t(e,n,r.extensionPrefixes??[])}static tryDeserialize(e,r){let n=new Map,i=[];for(let s of r.fields)try{let a=e.parseParamTypes(s.typeKey,s.typeParams),l=e.getSchema(s.typeKey,a);n.set(s.shortKey,{valueTypeKey:s.typeKey,valueTypeParams:a,schema:l,fullKey:s.fullKey,defaultValue:l.parse(s.defaultValue)})}catch(a){i.push({fullKey:s.fullKey,error:Sr(a)})}return{schematics:new t(e,n,r.extensionPrefixes??[]),errors:i}}},Ka=class{constructor(e){this.fieldDefs=e,this.fields=new Map}with(e,r){let n=this.fieldDefs.get(e);if(n===void 0)throw new Error(`Field with key ${e} does not exist in the schematics.`);return this.fields.set(n.fullKey,r),this}build(){return oc(this.fields)}},Ha=class t{constructor(e){this.configMap=e}static[js](e){return new t(e)}get(e){return this.configMap.get(e)}},Ya=class t{constructor(e){this.configMap=e}static[js](e){return new t(e)}get(e){return this.configMap.get(e)}has(e){return this.configMap.has(e)}};function vt(t){return new Map(t.fields.map(e=>[e.key,e.value]))}function oc(t){return{fields:Array.from(t.entries()).map(([e,r])=>({key:e,value:r}))}}function Fp(t){let e=new Map;for(let r of t)for(let{key:n,value:i}of r.fields)e.set(n,i);return oc(e)}var Pp={fields:[]};function mh(t,e){return{layers:[{layerName:t,config:e}]}}function Aa(t,e,r){return{layers:[...t.layers,{layerName:e,config:r}]}}function tt(t,e){if(t===e)return!0;if(typeof t!="object"||typeof e!="object"||t===null||e===null||Array.isArray(t)!==Array.isArray(e))return!1;if(Array.isArray(t)){if(t.length!==e?.length)return!1;for(let i=0;i<t.length;i++)if(!tt(t[i],e[i]))return!1;return!0}let r=new Set(Object.keys(t)),n=new Set(Object.keys(e));if(r.size!==n.size)return!1;for(let i of r)if(!n.has(i)||!tt(t[i],e[i]))return!1;return!0}function Ja(t,e){return t===void 0||t===""?e??'""':JSON.stringify(t)}function dn(t,e){return Ja(t?.replace(/\\n/g,`
215
- `),e)}var Tp=new Ga({displayName:o.string().optional(),hint:o.string().optional(),modelCentric:o.boolean().optional(),nonConfigurable:o.boolean().optional(),engineDoesNotSupport:o.boolean().optional(),machineDependent:o.boolean().optional(),warning:o.string().optional(),subtitle:o.string().optional(),isExperimental:o.boolean().optional(),dependencies:o.array(Pw).optional()}).valueType("numeric",{paramType:{min:o.number().optional(),max:o.number().optional(),step:o.number().optional(),int:o.boolean().optional(),precision:o.number().int().nonnegative().optional(),slider:o.object({min:o.number(),max:o.number(),step:o.number()}).optional(),shortHand:o.string().optional()},schemaMaker:({min:t,max:e,int:r,precision:n})=>{let i=o.number();if(t!==void 0&&(i=i.min(t)),e!==void 0&&(i=i.max(e)),r){if(n!==void 0)throw new Error("Cannot specify both int and precision.");i=i.int()}return i},effectiveEquals:(t,e)=>t===e,stringify:(t,{int:e,precision:r})=>e?String(Math.round(t)):t.toFixed(r??2)}).valueType("string",{paramType:{minLength:o.number().optional(),maxLength:o.number().optional(),isParagraph:o.boolean().optional(),isProtected:o.boolean().optional(),isToken:o.boolean().optional(),placeholder:o.string().optional()},schemaMaker:({minLength:t,maxLength:e})=>{let r=o.string();return t!==void 0&&(r=r.min(t)),e!==void 0&&(r=r.max(e)),r},effectiveEquals:(t,e)=>t===e,stringify:(t,{isParagraph:e,isProtected:r},{t:n,desiredLength:i})=>{if(r)return"********";if(e)return t===""?n("config:customInputs.string.emptyParagraph","<Empty>"):i===void 0||t.length<=i?t:t.slice(0,Math.floor(i/2))+" ... "+t.slice(-Math.ceil(i/2));{let s=Ja(t);return i===void 0||s.length<=i?s:s.slice(0,Math.floor(i/2))+"..."+s.slice(-Math.ceil(i/2))}}}).valueType("select",{paramType:{options:o.array(o.object({value:o.string().nonempty(),displayName:o.string()}).or(o.string())).refine(t=>{let e=new Set;for(let r of t){let n=typeof r=="string"?r:r.value;if(e.has(n))return!1;e.add(n)}return!0},{message:"Duplicate values in options."})},schemaMaker:({options:t})=>{let e=new Set(t.map(r=>typeof r=="string"?r:r.value));return o.string().refine(r=>e.has(r))},effectiveEquals:(t,e)=>t===e,stringify:t=>t}).valueType("boolean",{paramType:{},schemaMaker:()=>o.boolean(),effectiveEquals:(t,e)=>t===e,stringify:t=>t?"ON":"OFF"}).valueType("stringArray",{paramType:{maxNumItems:o.number().optional(),allowEmptyStrings:o.boolean().optional()},schemaMaker:({maxNumItems:t,allowEmptyStrings:e})=>{let r=o.string();e||(r=r.min(1));let n=o.array(r);return t!==void 0&&(n=n.max(t)),n},effectiveEquals:(t,e)=>t.length===e.length&&t.every((r,n)=>r===e[n]),stringify:(t,e,{t:r,desiredLength:n})=>{let i=t.map(a=>Ja(a));if(i.length===0)return r("config:customInputs.stringArray.empty","<Empty>");if(i.length<=2||n===void 0)return i.join(", ");let s=i[0].length+i[1].length+6;for(let a=1;a<i.length-1;a++)if(s+=i[a].length+2,s>=n)return i.slice(0,a).join(", ")+", ..."+i[i.length-1];return i.join(", ")}});Tp.build();var Ap=Tp.valueType("checkboxNumeric",{paramType:{min:o.number().optional(),max:o.number().optional(),step:o.number().optional(),int:o.boolean().optional(),uncheckedHint:o.string().optional(),precision:o.number().int().nonnegative().optional(),slider:o.object({min:o.number(),max:o.number(),step:o.number()}).optional()},schemaMaker:({min:t,max:e,int:r,precision:n})=>{let i=o.number();if(t!==void 0&&(i=i.min(t)),e!==void 0&&(i=i.max(e)),r){if(n!==void 0)throw new Error("Cannot specify both int and precision.");i=i.int()}return o.object({checked:o.boolean(),value:i})},effectiveEquals:(t,e)=>t.checked!==e.checked?!1:t.checked?t.value===e.value:!0,stringify:(t,{int:e,precision:r},{t:n})=>t.checked?e?String(Math.round(t.value)):t.value.toFixed(r??2):n("config:customInputs.checkboxNumeric.off","OFF")}).valueType("numericArray",{paramType:{min:o.number().optional(),max:o.number().optional(),int:o.boolean().optional()},schemaMaker:({min:t,max:e,int:r})=>{let n=o.number();return t!==void 0&&(n=n.min(t)),e!==void 0&&(n=n.max(e)),r&&(n=n.int()),o.array(n)},effectiveEquals:(t,e)=>t.length===e.length&&t.every((r,n)=>r===e[n]),stringify:(t,{int:e})=>t.map(r=>String(e?Math.round(r):r)).join(", ")}).valueType("contextOverflowPolicy",{paramType:{},schemaMaker:()=>ip,effectiveEquals:(t,e)=>t===e,stringify:(t,e,{t:r})=>{switch(t){case"stopAtLimit":return r("config:customInputs.contextOverflowPolicy.stopAtLimit","Stop At Limit");case"truncateMiddle":return r("config:customInputs.contextOverflowPolicy.truncateMiddle","Truncate Middle");case"rollingWindow":return r("config:customInputs.contextOverflowPolicy.rollingWindow","Rolling Window")}}}).valueType("context",{paramType:{},schemaMaker:()=>o.array(Aw),effectiveEquals:(t,e)=>tt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("contextLength",{paramType:{max:o.number().optional()},schemaMaker:()=>o.number().int().positive(),effectiveEquals:(t,e)=>t===e,stringify:(t,{max:e})=>e===void 0?String(t):`${t}/${e}`}).valueType("modelIdentifier",{paramType:{domain:o.array(oi).optional()},schemaMaker:()=>o.string(),effectiveEquals:(t,e)=>t===e,stringify:t=>t}).valueType("llmPromptTemplate",{paramType:{},schemaMaker:()=>np,effectiveEquals:(t,e)=>{if(t.type!==e.type||t.stopStrings.length!==e.stopStrings.length||!t.stopStrings.every((r,n)=>r===e.stopStrings[n]))return!1;switch(t.type){case"jinja":return t.jinjaPromptTemplate?.template===e.jinjaPromptTemplate?.template;case"manual":return t.manualPromptTemplate?.beforeSystem===e.manualPromptTemplate?.beforeSystem&&t.manualPromptTemplate?.afterSystem===e.manualPromptTemplate?.afterSystem&&t.manualPromptTemplate?.beforeUser===e.manualPromptTemplate?.beforeUser&&t.manualPromptTemplate?.afterUser===e.manualPromptTemplate?.afterUser&&t.manualPromptTemplate?.beforeAssistant===e.manualPromptTemplate?.beforeAssistant&&t.manualPromptTemplate?.afterAssistant===e.manualPromptTemplate?.afterAssistant;default:{let r=t.type;throw new Error("Unknown template type: "+r)}}},stringify:(t,e,{t:r,desiredLength:n})=>{switch(t.type){case"jinja":{let i=`${r("config:customInputs.llmPromptTemplate.type","Type")}: ${r("config:customInputs.llmPromptTemplate.types.jinja/label","Jinja")}
214
+ `+i)}return r}getSchemaForKey(e){return this.obtainField(e).schema}parseField(e,r){if(r===void 0){if(e.defaultValue===void 0)throw new Error(`Field with key ${e.fullKey} is missing and has no default value`);return e.defaultValue}let n=e.schema.safeParse(r);if(!n.success)throw new Error(`Field with key ${e.fullKey} does not satisfy the schema:`+n.error.message);return n.data}parseFieldWithoutDefault(e,r){if(r===void 0)return;let n=e.schema.safeParse(r);if(!n.success)throw new Error(`Field with key ${e.fullKey} does not satisfy the schema:`+n.error.message);return n.data}access(e,r){let n=this.obtainField(r);return this.parseField(n,e.fields.find(i=>i.key===n.fullKey)?.value)}accessByFullKey(e,r){let n=this.obtainFieldByFullKey(r);return this.parseField(n,e.fields.find(i=>i.key===n.fullKey)?.value)}accessPartial(e,r){let n=this.obtainField(r);return this.parseFieldWithoutDefault(n,e.fields.find(i=>i.key===n.fullKey)?.value)}sliced(...e){let r=e.map(i=>i.endsWith("*")?{type:"prefix",value:i.substring(0,i.length-1)}:{type:"exact",value:i}),n=new Map;for(let[i,s]of this.fields.entries())for(let a of r)(a.type==="exact"&&i===a.value||a.type==="prefix"&&i.startsWith(a.value))&&n.set(i,s);return new t(this.valueTypeLibrary,n,this.extensionPrefixes)}scoped(e){let r=new Map;for(let[n,i]of this.fields.entries())n.startsWith(`${e}.`)&&r.set(n.substring(e.length+1),i);return new t(this.valueTypeLibrary,r,this.extensionPrefixes)}union(e){let r=new Map;for(let[n,i]of this.fields.entries())r.set(n,i);for(let[n,i]of e.fields.entries()){if(r.has(n))throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: "+n);r.set(n,i)}return new t(this.valueTypeLibrary,r,[...this.extensionPrefixes,...e.extensionPrefixes])}flattenBaseKey(){let e=new Map;for(let r of this.fields.values())e.set(r.fullKey,r);return new t(this.valueTypeLibrary,e,this.extensionPrefixes)}parseToMap(e){let r=Dt(e),n=new Map;for(let[i,s]of this.fields.entries()){let a=r.get(s.fullKey),l=this.parseField(s,a);n.set(i,l)}return n}parseToMapWithFullKey(e){let r=Dt(e),n=new Map;for(let i of this.fields.values()){let s=r.get(i.fullKey),a=this.parseField(i,s);n.set(i.fullKey,a)}return n}parseToMapPartial(e){let r=Dt(e),n=new Map;for(let[i,s]of this.fields.entries()){let a=r.get(s.fullKey),l=this.parseFieldWithoutDefault(s,a);l!==void 0&&n.set(i,l)}return n}parse(e){return Ya[js](this.parseToMap(e))}parsePartial(e){return Ja[js](this.parseToMapPartial(e))}buildFullConfig(e){return{fields:Array.from(this.fields.entries()).map(([r,n])=>{let i=this.parseField(n,e[r]);return{key:n.fullKey,value:i}})}}buildPartialConfig(e){return{fields:Object.entries(e).filter(([r,n])=>n!==void 0).map(([r,n])=>{let i=this.obtainField(r);return{key:i.fullKey,value:this.parseField(i,n)}})}}createBuildPartialConfigInput(){return{}}configBuilder(){return new Ha(this.fields)}clone(){return new t(this.valueTypeLibrary,new Map(this.fields),this.extensionPrefixes)}withTypeParamOverride(e,r){let n=this.obtainField(e),i=this.clone();return i.fields.set(e,{...n,valueTypeParams:r(n.valueTypeParams),schema:this.valueTypeLibrary.getSchema(n.valueTypeKey,r(n.valueTypeParams))}),i}getFullKeyMap(){return this.fullKepMap!==void 0?this.fullKepMap:(this.fullKepMap=new Map([...this.fields.values()].map(e=>[e.fullKey,e])),this.fullKepMap)}makeLenientZodSchema(){let e=this.getFullKeyMap();return te.transform(r=>{let n=new Set;return{fields:r.fields.filter(i=>{if(this.extensionPrefixes.some(l=>i.key.startsWith(l)))return!0;if(n.has(i.key))return!1;let s=e.get(i.key);return s===void 0||!s.schema.safeParse(i.value).success?!1:(n.add(i.key),!0)})}})}getLenientZodSchema(){return this.lenientZodSchema!==void 0?this.lenientZodSchema:(this.lenientZodSchema=this.makeLenientZodSchema(),this.lenientZodSchema)}getValueType(e){let r=this.fields.get(e);return r===void 0?null:r.valueTypeKey}getValueTypeParam(e){let r=this.fields.get(e);return r===void 0?null:r.valueTypeParams}getValueTypeParamByFullKey(e){let r=this.getFullKeyMap().get(e);if(r===void 0)throw new Error(`Field with key ${e} does not exist in the schematics`);return r.valueTypeParams}hasFullKey(e){return this.getFullKeyMap().get(e)!==void 0}filterConfig(e,r){let n=this.getFullKeyMap();return{fields:e.fields.filter(i=>{let s=n.get(i.key);return s===void 0?!1:r!==void 0?r(s.fullKey,{type:s.valueTypeKey,param:s.valueTypeParams}):!0})}}filterStack(e){return{layers:e.layers.map(r=>({layerName:r.layerName,config:this.filterConfig(r.config)}))}}twoWayFilterConfig(e,r){let n=[],i=[],s=this.getFullKeyMap();for(let a of e.fields){let l=s.get(a.key),c=l!==void 0;l!==void 0&&r!==void 0&&(c=r(l.fullKey,{type:l.valueTypeKey,param:l.valueTypeParams})),c?n.push(a):i.push(a)}return[{fields:n},{fields:i}]}filterFullKeys(e){let r=this.getFullKeyMap();return e.filter(n=>r.has(n))}configEffectiveEquals(e,r){let n=Dt(e),i=Dt(r);for(let s of this.fields.values()){let a=n.get(s.fullKey),l=i.get(s.fullKey);if(a===void 0){if(l===void 0)continue;return!1}this.valueTypeLibrary.effectiveEquals(s.valueTypeKey,s.valueTypeParams,a,l)}return!0}fieldEffectiveEquals(e,r,n){let i=this.obtainField(e);return this.valueTypeLibrary.effectiveEquals(i.valueTypeKey,i.valueTypeParams,i.schema.parse(r),i.schema.parse(n))}fieldEffectiveEqualsWithFullKey(e,r,n){let s=this.getFullKeyMap().get(e);if(s===void 0)throw new Error(`Field with key ${e} does not exist in the schematics`);return this.valueTypeLibrary.effectiveEquals(s.valueTypeKey,s.valueTypeParams,s.schema.parse(r),s.schema.parse(n))}makeInternalFieldStringifyOpts(e){return{t:e.t??((r,n)=>n),desiredLength:e.desiredLength}}stringifyField(e,r,n={}){let i=this.obtainField(e);return this.valueTypeLibrary.stringify(i.valueTypeKey,i.valueTypeParams,this.makeInternalFieldStringifyOpts(n),r)}tryStringifyFieldWithFullKey(e,r,n){let s=this.getFullKeyMap().get(e);return s===void 0?null:this.valueTypeLibrary.stringify(s.valueTypeKey,s.valueTypeParams,this.makeInternalFieldStringifyOpts(n),r)}apply(e,r){let n=this.filterConfig(r);return Pp([e,n])}unApply(e,r){let n=this.filterConfig(r),i=Dt(n),s=new Map(Dt(e)),a=this.getFullKeyMap();for(let[l,c]of i.entries()){let u=a.get(l);if(u===void 0)continue;let h=s.get(l);if(h!==void 0){if(!this.valueTypeLibrary.effectiveEquals(u.valueTypeKey,u.valueTypeParams,c,h))continue;s.delete(l)}}return ac(s)}*iterateFieldsOfConfig(e){let r=this.getFullKeyMap();for(let{key:n,value:i}of e.fields)r.get(n)!==void 0&&(yield[n,i])}*fullKeys(){let e=this.getFullKeyMap();for(let r of e.keys())yield r}effectiveCompareConfig(e,r,n={}){let{fieldFilter:i}=n,s=Dt(e),a=Dt(r),l=[],c=[],u=[];for(let h of this.fields.values()){if(i!==void 0&&!i(h.fullKey,{type:h.valueTypeKey,param:h.valueTypeParams}))continue;let f=s.get(h.fullKey),d=a.get(h.fullKey);if(f===void 0){if(d===void 0)continue;c.push(h.fullKey)}else d===void 0?l.push(h.fullKey):this.valueTypeLibrary.effectiveEquals(h.valueTypeKey,h.valueTypeParams,f,d)||u.push(h.fullKey)}return{onlyInA:l,onlyInB:c,inBothButDifferent:u}}serialize(){return{fields:[...this.fields.entries()].map(([e,r])=>({shortKey:e,fullKey:r.fullKey,typeKey:r.valueTypeKey,typeParams:r.valueTypeParams,defaultValue:r.defaultValue})),extensionPrefixes:this.extensionPrefixes}}hasFieldsWithPrefix(e){for(let r of this.fields.values())if(r.fullKey.startsWith(e))return!0;return!1}static deserialize(e,r){let n=new Map(r.fields.map(i=>{let s=e.parseParamTypes(i.typeKey,i.typeParams),a=e.getSchema(i.typeKey,s);return[i.shortKey,{valueTypeKey:i.typeKey,valueTypeParams:s,schema:a,fullKey:i.fullKey,defaultValue:a.parse(i.defaultValue)}]}));return new t(e,n,r.extensionPrefixes??[])}static tryDeserialize(e,r){let n=new Map,i=[];for(let s of r.fields)try{let a=e.parseParamTypes(s.typeKey,s.typeParams),l=e.getSchema(s.typeKey,a);n.set(s.shortKey,{valueTypeKey:s.typeKey,valueTypeParams:a,schema:l,fullKey:s.fullKey,defaultValue:l.parse(s.defaultValue)})}catch(a){i.push({fullKey:s.fullKey,error:Sr(a)})}return{schematics:new t(e,n,r.extensionPrefixes??[]),errors:i}}},Ha=class{constructor(e){this.fieldDefs=e,this.fields=new Map}with(e,r){let n=this.fieldDefs.get(e);if(n===void 0)throw new Error(`Field with key ${e} does not exist in the schematics.`);return this.fields.set(n.fullKey,r),this}build(){return ac(this.fields)}},Ya=class t{constructor(e){this.configMap=e}static[js](e){return new t(e)}get(e){return this.configMap.get(e)}},Ja=class t{constructor(e){this.configMap=e}static[js](e){return new t(e)}get(e){return this.configMap.get(e)}has(e){return this.configMap.has(e)}};function Dt(t){return new Map(t.fields.map(e=>[e.key,e.value]))}function ac(t){return{fields:Array.from(t.entries()).map(([e,r])=>({key:e,value:r}))}}function Pp(t){let e=new Map;for(let r of t)for(let{key:n,value:i}of r.fields)e.set(n,i);return ac(e)}var Tp={fields:[]};function gh(t,e){return{layers:[{layerName:t,config:e}]}}function Oa(t,e,r){return{layers:[...t.layers,{layerName:e,config:r}]}}function nt(t,e){if(t===e)return!0;if(typeof t!="object"||typeof e!="object"||t===null||e===null||Array.isArray(t)!==Array.isArray(e))return!1;if(Array.isArray(t)){if(t.length!==e?.length)return!1;for(let i=0;i<t.length;i++)if(!nt(t[i],e[i]))return!1;return!0}let r=new Set(Object.keys(t)),n=new Set(Object.keys(e));if(r.size!==n.size)return!1;for(let i of r)if(!n.has(i)||!nt(t[i],e[i]))return!1;return!0}function Qa(t,e){return t===void 0||t===""?e??'""':JSON.stringify(t)}function dn(t,e){return Qa(t?.replace(/\\n/g,`
215
+ `),e)}var Ap=new Za({displayName:o.string().optional(),hint:o.string().optional(),modelCentric:o.boolean().optional(),nonConfigurable:o.boolean().optional(),engineDoesNotSupport:o.boolean().optional(),machineDependent:o.boolean().optional(),warning:o.string().optional(),subtitle:o.string().optional(),isExperimental:o.boolean().optional(),dependencies:o.array(Tw).optional()}).valueType("numeric",{paramType:{min:o.number().optional(),max:o.number().optional(),step:o.number().optional(),int:o.boolean().optional(),precision:o.number().int().nonnegative().optional(),slider:o.object({min:o.number(),max:o.number(),step:o.number()}).optional(),shortHand:o.string().optional()},schemaMaker:({min:t,max:e,int:r,precision:n})=>{let i=o.number();if(t!==void 0&&(i=i.min(t)),e!==void 0&&(i=i.max(e)),r){if(n!==void 0)throw new Error("Cannot specify both int and precision.");i=i.int()}return i},effectiveEquals:(t,e)=>t===e,stringify:(t,{int:e,precision:r})=>e?String(Math.round(t)):t.toFixed(r??2)}).valueType("string",{paramType:{minLength:o.number().optional(),maxLength:o.number().optional(),isParagraph:o.boolean().optional(),isProtected:o.boolean().optional(),isToken:o.boolean().optional(),placeholder:o.string().optional()},schemaMaker:({minLength:t,maxLength:e})=>{let r=o.string();return t!==void 0&&(r=r.min(t)),e!==void 0&&(r=r.max(e)),r},effectiveEquals:(t,e)=>t===e,stringify:(t,{isParagraph:e,isProtected:r},{t:n,desiredLength:i})=>{if(r)return"********";if(e)return t===""?n("config:customInputs.string.emptyParagraph","<Empty>"):i===void 0||t.length<=i?t:t.slice(0,Math.floor(i/2))+" ... "+t.slice(-Math.ceil(i/2));{let s=Qa(t);return i===void 0||s.length<=i?s:s.slice(0,Math.floor(i/2))+"..."+s.slice(-Math.ceil(i/2))}}}).valueType("select",{paramType:{options:o.array(o.object({value:o.string().nonempty(),displayName:o.string()}).or(o.string())).refine(t=>{let e=new Set;for(let r of t){let n=typeof r=="string"?r:r.value;if(e.has(n))return!1;e.add(n)}return!0},{message:"Duplicate values in options."})},schemaMaker:({options:t})=>{let e=new Set(t.map(r=>typeof r=="string"?r:r.value));return o.string().refine(r=>e.has(r))},effectiveEquals:(t,e)=>t===e,stringify:t=>t}).valueType("boolean",{paramType:{},schemaMaker:()=>o.boolean(),effectiveEquals:(t,e)=>t===e,stringify:t=>t?"ON":"OFF"}).valueType("stringArray",{paramType:{maxNumItems:o.number().optional(),allowEmptyStrings:o.boolean().optional()},schemaMaker:({maxNumItems:t,allowEmptyStrings:e})=>{let r=o.string();e||(r=r.min(1));let n=o.array(r);return t!==void 0&&(n=n.max(t)),n},effectiveEquals:(t,e)=>t.length===e.length&&t.every((r,n)=>r===e[n]),stringify:(t,e,{t:r,desiredLength:n})=>{let i=t.map(a=>Qa(a));if(i.length===0)return r("config:customInputs.stringArray.empty","<Empty>");if(i.length<=2||n===void 0)return i.join(", ");let s=i[0].length+i[1].length+6;for(let a=1;a<i.length-1;a++)if(s+=i[a].length+2,s>=n)return i.slice(0,a).join(", ")+", ..."+i[i.length-1];return i.join(", ")}});Ap.build();var Op=Ap.valueType("checkboxNumeric",{paramType:{min:o.number().optional(),max:o.number().optional(),step:o.number().optional(),int:o.boolean().optional(),uncheckedHint:o.string().optional(),precision:o.number().int().nonnegative().optional(),slider:o.object({min:o.number(),max:o.number(),step:o.number()}).optional()},schemaMaker:({min:t,max:e,int:r,precision:n})=>{let i=o.number();if(t!==void 0&&(i=i.min(t)),e!==void 0&&(i=i.max(e)),r){if(n!==void 0)throw new Error("Cannot specify both int and precision.");i=i.int()}return o.object({checked:o.boolean(),value:i})},effectiveEquals:(t,e)=>t.checked!==e.checked?!1:t.checked?t.value===e.value:!0,stringify:(t,{int:e,precision:r},{t:n})=>t.checked?e?String(Math.round(t.value)):t.value.toFixed(r??2):n("config:customInputs.checkboxNumeric.off","OFF")}).valueType("numericArray",{paramType:{min:o.number().optional(),max:o.number().optional(),int:o.boolean().optional()},schemaMaker:({min:t,max:e,int:r})=>{let n=o.number();return t!==void 0&&(n=n.min(t)),e!==void 0&&(n=n.max(e)),r&&(n=n.int()),o.array(n)},effectiveEquals:(t,e)=>t.length===e.length&&t.every((r,n)=>r===e[n]),stringify:(t,{int:e})=>t.map(r=>String(e?Math.round(r):r)).join(", ")}).valueType("contextOverflowPolicy",{paramType:{},schemaMaker:()=>sp,effectiveEquals:(t,e)=>t===e,stringify:(t,e,{t:r})=>{switch(t){case"stopAtLimit":return r("config:customInputs.contextOverflowPolicy.stopAtLimit","Stop At Limit");case"truncateMiddle":return r("config:customInputs.contextOverflowPolicy.truncateMiddle","Truncate Middle");case"rollingWindow":return r("config:customInputs.contextOverflowPolicy.rollingWindow","Rolling Window")}}}).valueType("context",{paramType:{},schemaMaker:()=>o.array(Ow),effectiveEquals:(t,e)=>nt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("contextLength",{paramType:{max:o.number().optional()},schemaMaker:()=>o.number().int().positive(),effectiveEquals:(t,e)=>t===e,stringify:(t,{max:e})=>e===void 0?String(t):`${t}/${e}`}).valueType("modelIdentifier",{paramType:{domain:o.array(oi).optional()},schemaMaker:()=>o.string(),effectiveEquals:(t,e)=>t===e,stringify:t=>t}).valueType("llmPromptTemplate",{paramType:{},schemaMaker:()=>ip,effectiveEquals:(t,e)=>{if(t.type!==e.type||t.stopStrings.length!==e.stopStrings.length||!t.stopStrings.every((r,n)=>r===e.stopStrings[n]))return!1;switch(t.type){case"jinja":return t.jinjaPromptTemplate?.template===e.jinjaPromptTemplate?.template;case"manual":return t.manualPromptTemplate?.beforeSystem===e.manualPromptTemplate?.beforeSystem&&t.manualPromptTemplate?.afterSystem===e.manualPromptTemplate?.afterSystem&&t.manualPromptTemplate?.beforeUser===e.manualPromptTemplate?.beforeUser&&t.manualPromptTemplate?.afterUser===e.manualPromptTemplate?.afterUser&&t.manualPromptTemplate?.beforeAssistant===e.manualPromptTemplate?.beforeAssistant&&t.manualPromptTemplate?.afterAssistant===e.manualPromptTemplate?.afterAssistant;default:{let r=t.type;throw new Error("Unknown template type: "+r)}}},stringify:(t,e,{t:r,desiredLength:n})=>{switch(t.type){case"jinja":{let i=`${r("config:customInputs.llmPromptTemplate.type","Type")}: ${r("config:customInputs.llmPromptTemplate.types.jinja/label","Jinja")}
216
216
  ${r("config:customInputs.llmPromptTemplate.jinja.template/label","Template")}: `;if(n===void 0)return i+t.jinjaPromptTemplate?.template;let s=i.length,a=Math.min(100,n-s),l=t.jinjaPromptTemplate?.template??"";return l.length<=a?i+l:i+l.slice(0,Math.floor(a/2))+"..."+l.slice(-Math.ceil(a/2))}case"manual":return`${r("config:customInputs.llmPromptTemplate.type","Type")}: ${r("config:customInputs.llmPromptTemplate.types.manual/label","Manual")}
217
217
  ${r("config:customInputs.llmPromptTemplate.manual.subfield.beforeSystem/label","Before System")}: ${dn(t.manualPromptTemplate?.beforeSystem)}
218
218
  ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterSystem/label","After System")}: ${dn(t.manualPromptTemplate?.afterSystem)}
219
219
  ${r("config:customInputs.llmPromptTemplate.manual.subfield.beforeUser/label","Before User")}: ${dn(t.manualPromptTemplate?.beforeUser)}
220
220
  ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterUser/label","After User")}: ${dn(t.manualPromptTemplate?.afterUser)}
221
221
  ${r("config:customInputs.llmPromptTemplate.manual.subfield.beforeAssistant/label","Before Assistant")}: ${dn(t.manualPromptTemplate?.beforeAssistant)}
222
- ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label","After Assistant")}: ${dn(t.manualPromptTemplate?.afterAssistant)}`;default:{let i=t.type;throw new Error("Unknown template type: "+i)}}}}).valueType("llmReasoningParsing",{paramType:{},schemaMaker:()=>sp,effectiveEquals:(t,e)=>t.startString===e.startString&&t.endString===e.endString,stringify:t=>JSON.stringify(t,null,2)}).valueType("llamaStructuredOutput",{paramType:{},schemaMaker:()=>Yl,effectiveEquals:(t,e)=>t.type==="json"&&e.type==="json"?tt(t,e):t.type==="none"&&e.type==="none",stringify:t=>JSON.stringify(t,null,2)}).valueType("speculativeDecodingDraftModel",{paramType:{},schemaMaker:()=>o.string(),effectiveEquals:(t,e)=>t===e,stringify:(t,e,{t:r})=>t===""?r("config:customInputs.speculativeDecodingDraftModel.off","OFF"):t}).valueType("toolUse",{paramType:{},schemaMaker:()=>Qh,effectiveEquals:(t,e)=>tt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("toolNaming",{paramType:{},schemaMaker:()=>rp,effectiveEquals:(t,e)=>t===e,stringify:t=>t}).valueType("llamaAccelerationOffloadRatio",{paramType:{numLayers:o.number().optional()},schemaMaker:()=>Uh,effectiveEquals:(t,e)=>(t==="max"?1:t==="off"?0:t)===(e==="max"?1:e==="off"?0:e),stringify:(t,{numLayers:e},{t:r})=>{if(t==="max"||t===1){let n=r("config:customInputs.llamaAccelerationOffloadRatio.max","MAX");return e!==0?`${n} (${e})`:n}return t==="off"||t===0?r("config:customInputs.llamaAccelerationOffloadRatio.off","OFF"):e!==void 0?String(Math.round(e*t)):(t*100).toFixed(0)+"%"}}).valueType("llamaMirostatSampling",{paramType:{},schemaMaker:()=>Bw,effectiveEquals:(t,e)=>tt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("llamaLogitBias",{paramType:{},schemaMaker:()=>Nw,effectiveEquals:(t,e)=>tt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("llamaCacheQuantizationType",{paramType:{},schemaMaker:()=>o.object({checked:o.boolean(),value:fw}),effectiveEquals:(t,e)=>t.checked!==e.checked?!1:t.checked?t.value===e.value:!0,stringify:(t,e,{t:r})=>t.checked?t.value:r("config:customInputs.llamaCacheQuantizationType.off","OFF")}).valueType("mlxKvCacheQuantizationType",{paramType:{},schemaMaker:()=>mw,effectiveEquals:(t,e)=>t.enabled!==e.enabled?!1:t.enabled?t.bits===e.bits&&t.groupSize===e.groupSize&&t.quantizedStart===e.quantizedStart:!0,stringify:t=>JSON.stringify(t,null,2)}).valueType("retrievalChunkingMethod",{paramType:{},schemaMaker:()=>xp,effectiveEquals:(t,e)=>tt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("envVars",{paramType:{},schemaMaker:()=>zD,effectiveEquals:(t,e)=>tt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("gpuSplitConfig",{paramType:{},schemaMaker:()=>xw,effectiveEquals:(t,e)=>tt(t,e),stringify:t=>JSON.stringify(t,null,2)}).build(),qt=new Ms(Ap).extension("ext.virtualModel.customField").field("envVars","envVars",{},{}).scope("llm.prediction",t=>t.field("temperature","numeric",{min:0,step:.01,slider:{min:0,max:1,step:.01},precision:2,shortHand:"temp"},.8).field("contextOverflowPolicy","contextOverflowPolicy",{},"truncateMiddle").field("maxPredictedTokens","checkboxNumeric",{min:1,int:!0},{checked:!1,value:1e3}).field("stopStrings","stringArray",{},[]).field("toolCallStopStrings","stringArray",{},[]).field("structured","llamaStructuredOutput",{},{type:"none"}).scope("speculativeDecoding",e=>e.field("draftModel","speculativeDecodingDraftModel",{modelCentric:!0},"").field("minDraftLengthToConsider","numeric",{modelCentric:!0,min:0,int:!0,slider:{min:0,max:10,step:1}},0).field("numReuseTokens","numeric",{modelCentric:!0,min:1,int:!0},256).field("minContinueDraftingProbability","numeric",{modelCentric:!0,min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},.75).field("maxTokensToDraft","numeric",{modelCentric:!0,min:1,int:!0,slider:{min:10,max:30,step:1}},16).field("numDraftTokensExact","numeric",{modelCentric:!0,min:1,int:!0,slider:{min:1,max:10,step:1}},2)).field("tools","toolUse",{},{type:"none"}).field("toolNaming","toolNaming",{},"removeSpecial").field("promptTemplate","llmPromptTemplate",{modelCentric:!0},{type:"manual",manualPromptTemplate:{beforeSystem:"Instruct: ",afterSystem:`
222
+ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label","After Assistant")}: ${dn(t.manualPromptTemplate?.afterAssistant)}`;default:{let i=t.type;throw new Error("Unknown template type: "+i)}}}}).valueType("llmReasoningParsing",{paramType:{},schemaMaker:()=>op,effectiveEquals:(t,e)=>t.startString===e.startString&&t.endString===e.endString,stringify:t=>JSON.stringify(t,null,2)}).valueType("llamaStructuredOutput",{paramType:{},schemaMaker:()=>Jl,effectiveEquals:(t,e)=>t.type==="json"&&e.type==="json"?nt(t,e):t.type==="none"&&e.type==="none",stringify:t=>JSON.stringify(t,null,2)}).valueType("speculativeDecodingDraftModel",{paramType:{},schemaMaker:()=>o.string(),effectiveEquals:(t,e)=>t===e,stringify:(t,e,{t:r})=>t===""?r("config:customInputs.speculativeDecodingDraftModel.off","OFF"):t}).valueType("toolUse",{paramType:{},schemaMaker:()=>Xh,effectiveEquals:(t,e)=>nt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("toolNaming",{paramType:{},schemaMaker:()=>np,effectiveEquals:(t,e)=>t===e,stringify:t=>t}).valueType("llamaAccelerationOffloadRatio",{paramType:{numLayers:o.number().optional()},schemaMaker:()=>qh,effectiveEquals:(t,e)=>(t==="max"?1:t==="off"?0:t)===(e==="max"?1:e==="off"?0:e),stringify:(t,{numLayers:e},{t:r})=>{if(t==="max"||t===1){let n=r("config:customInputs.llamaAccelerationOffloadRatio.max","MAX");return e!==0?`${n} (${e})`:n}return t==="off"||t===0?r("config:customInputs.llamaAccelerationOffloadRatio.off","OFF"):e!==void 0?String(Math.round(e*t)):(t*100).toFixed(0)+"%"}}).valueType("llamaMirostatSampling",{paramType:{},schemaMaker:()=>Lw,effectiveEquals:(t,e)=>nt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("llamaLogitBias",{paramType:{},schemaMaker:()=>$w,effectiveEquals:(t,e)=>nt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("llamaCacheQuantizationType",{paramType:{},schemaMaker:()=>o.object({checked:o.boolean(),value:hw}),effectiveEquals:(t,e)=>t.checked!==e.checked?!1:t.checked?t.value===e.value:!0,stringify:(t,e,{t:r})=>t.checked?t.value:r("config:customInputs.llamaCacheQuantizationType.off","OFF")}).valueType("mlxKvCacheQuantizationType",{paramType:{},schemaMaker:()=>gw,effectiveEquals:(t,e)=>t.enabled!==e.enabled?!1:t.enabled?t.bits===e.bits&&t.groupSize===e.groupSize&&t.quantizedStart===e.quantizedStart:!0,stringify:t=>JSON.stringify(t,null,2)}).valueType("retrievalChunkingMethod",{paramType:{},schemaMaker:()=>kp,effectiveEquals:(t,e)=>nt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("envVars",{paramType:{},schemaMaker:()=>VD,effectiveEquals:(t,e)=>nt(t,e),stringify:t=>JSON.stringify(t,null,2)}).valueType("gpuSplitConfig",{paramType:{},schemaMaker:()=>kw,effectiveEquals:(t,e)=>nt(t,e),stringify:t=>JSON.stringify(t,null,2)}).build(),qt=new Ms(Op).extension("ext.virtualModel.customField").field("envVars","envVars",{},{}).scope("llm.prediction",t=>t.field("temperature","numeric",{min:0,step:.01,slider:{min:0,max:1,step:.01},precision:2,shortHand:"temp"},.8).field("contextOverflowPolicy","contextOverflowPolicy",{},"truncateMiddle").field("maxPredictedTokens","checkboxNumeric",{min:1,int:!0},{checked:!1,value:1e3}).field("stopStrings","stringArray",{},[]).field("toolCallStopStrings","stringArray",{},[]).field("structured","llamaStructuredOutput",{},{type:"none"}).scope("speculativeDecoding",e=>e.field("draftModel","speculativeDecodingDraftModel",{modelCentric:!0},"").field("minDraftLengthToConsider","numeric",{modelCentric:!0,min:0,int:!0,slider:{min:0,max:10,step:1}},0).field("numReuseTokens","numeric",{modelCentric:!0,min:1,int:!0},256).field("minContinueDraftingProbability","numeric",{modelCentric:!0,min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},.75).field("maxTokensToDraft","numeric",{modelCentric:!0,min:1,int:!0,slider:{min:10,max:30,step:1}},16).field("numDraftTokensExact","numeric",{modelCentric:!0,min:1,int:!0,slider:{min:1,max:10,step:1}},2)).field("tools","toolUse",{},{type:"none"}).field("toolNaming","toolNaming",{},"removeSpecial").field("promptTemplate","llmPromptTemplate",{modelCentric:!0},{type:"manual",manualPromptTemplate:{beforeSystem:"Instruct: ",afterSystem:`
223
223
  `,beforeAssistant:"AI: ",afterAssistant:`
224
224
  `,beforeUser:"Human: ",afterUser:`
225
- `},stopStrings:[]}).field("systemPrompt","string",{isParagraph:!0},"").field("seed","checkboxNumeric",{int:!0,min:-1,uncheckedHint:"config:seedUncheckedHint"},{checked:!1,value:-1}).field("contextPrefill","context",{},[]).field("topKSampling","numeric",{min:-1,max:500,int:!0},40).field("repeatPenalty","checkboxNumeric",{min:-1,step:.01},{checked:!0,value:1.1}).field("minPSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!0,value:.05}).field("topPSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!0,value:.95}).field("logProbs","checkboxNumeric",{min:0,max:100,int:!0},{checked:!1,value:0}).scope("reasoning",e=>e.field("parsing","llmReasoningParsing",{},{enabled:!0,startString:"<think>",endString:"</think>"})).scope("llama",e=>e.field("cpuThreads","numeric",{min:1,int:!0},4).field("frequencyPenalty","checkboxNumeric",{precision:2},{checked:!1,value:0}).field("xtcProbability","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!1,value:.5}).field("xtcThreshold","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:.5,step:.01}},{checked:!1,value:.1}).field("presencePenalty","checkboxNumeric",{precision:2},{checked:!1,value:0}).field("mirostatSampling","llamaMirostatSampling",{},{version:0,learningRate:.1,targetEntropy:5}).field("tailFreeSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!1,value:.95}).field("locallyTypicalSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!1,value:.9}).field("logitBias","llamaLogitBias",{},[]))).scope("llm.load",t=>t.field("contextLength","contextLength",{machineDependent:!0},2048).field("numExperts","numeric",{min:0,int:!0},0).field("seed","checkboxNumeric",{int:!0,min:-1,uncheckedHint:"config:seedUncheckedHint"},{checked:!1,value:-1}).field("offloadKVCacheToGpu","boolean",{},!0).field("numCpuExpertLayersRatio","llamaAccelerationOffloadRatio",{machineDependent:!0,isExperimental:!0},"off").scope("llama",e=>e.scope("acceleration",r=>r.field("offloadRatio","llamaAccelerationOffloadRatio",{machineDependent:!0},"max")).field("cpuThreadPoolSize","numeric",{min:1,machineDependent:!0},4).field("evalBatchSize","numeric",{min:1,int:!0},512).field("flashAttention","boolean",{isExperimental:!0,warning:"config:flashAttentionWarning"},!1).field("ropeFrequencyBase","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyBaseUncheckedHint"},{checked:!1,value:0}).field("ropeFrequencyScale","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyScaleUncheckedHint"},{checked:!1,value:0}).field("keepModelInMemory","boolean",{},!0).field("useFp16ForKVCache","boolean",{},!0).field("tryMmap","boolean",{},!0).field("kCacheQuantizationType","llamaCacheQuantizationType",{isExperimental:!0},{checked:!1,value:"f16"}).field("vCacheQuantizationType","llamaCacheQuantizationType",{isExperimental:!0,warning:"config:llamaKvCacheQuantizationWarning"},{checked:!1,value:"f16"})).scope("mlx",e=>e.field("kvCacheQuantization","mlxKvCacheQuantizationType",{isExperimental:!0},{enabled:!1,bits:8,groupSize:64,quantizedStart:5e3}))).scope("load",t=>t.field("gpuSplitConfig","gpuSplitConfig",{},_w).field("gpuStrictVramCap","boolean",{},!1)).scope("embedding.load",t=>t.field("contextLength","contextLength",{machineDependent:!0},2048).field("seed","checkboxNumeric",{int:!0,min:-1,uncheckedHint:"config:seedUncheckedHint"},{checked:!1,value:-1}).scope("llama",e=>e.scope("acceleration",r=>r.field("offloadRatio","llamaAccelerationOffloadRatio",{machineDependent:!0},"max")).field("evalBatchSize","numeric",{min:1,int:!0},512).field("ropeFrequencyBase","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyBaseUncheckedHint"},{checked:!1,value:0}).field("ropeFrequencyScale","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyScaleUncheckedHint"},{checked:!1,value:0}).field("keepModelInMemory","boolean",{},!0).field("tryMmap","boolean",{},!0))).scope("retrieval",t=>t.field("databaseFile","string",{machineDependent:!0},"").field("chunkingMethod","retrievalChunkingMethod",{},{type:"recursive-v1",chunkSize:512,chunkOverlap:100}).field("limit","numeric",{min:1,int:!0},5).field("embeddingModel","modelIdentifier",{domain:["embedding"]},"")).build(),vn=qt.scoped("llm.prediction"),gi=vn.sliced("temperature","maxPredictedTokens","promptTemplate","systemPrompt","seed","contextPrefill","tools","toolNaming","reasoning.*");gi.union(vn.sliced("llama.*","contextOverflowPolicy","stopStrings","toolCallStopStrings","structured","topKSampling","repeatPenalty","minPSampling","topPSampling","logProbs","speculativeDecoding.draftModel","speculativeDecoding.minContinueDraftingProbability","speculativeDecoding.minDraftLengthToConsider","speculativeDecoding.maxTokensToDraft","speculativeDecoding.numReuseTokens"));gi.union(vn.sliced("mlx.*","contextOverflowPolicy","stopStrings","toolCallStopStrings","structured","repeatPenalty","minPSampling","topPSampling","topKSampling","speculativeDecoding.draftModel","speculativeDecoding.numDraftTokensExact"));gi.union(vn.sliced("transformers.*"));gi.union(vn.sliced("onnx.*","repeatPenalty","topPSampling","topKSampling"));var Dn=qt.scoped("llm.load").union(qt.sliced("envVars")),yi=Dn.sliced("contextLength","seed","envVars"),Op=qt.sliced("llama.load.*","load.*"),M1=yi.union(Dn.sliced("llama.*","load.*","offloadKVCacheToGpu")).union(Op);yi.union(Dn.sliced("mlx.*"));yi.union(Dn.sliced("transformers.*"));yi.union(Dn.sliced("onnx.*"));var j1=Dn.sliced("numExperts","numCpuExpertLayersRatio"),B1=M1.union(j1),Ip=qt.scoped("embedding.load").union(qt.sliced("load.*")),Rp=Ip.sliced("contextLength","seed"),L1=qt.scoped("retrieval"),N1=Rp.union(Ip.sliced("llama.*")).union(Op);new Ms(Ap).build();function wr(t,e){if(t!==void 0)return t===!1?{checked:!1,value:e}:{checked:!0,value:t}}function $1(t){let e=vn.buildPartialConfig({temperature:t.temperature,contextOverflowPolicy:t.contextOverflowPolicy,maxPredictedTokens:wr(t.maxTokens,1),stopStrings:t.stopStrings,toolCallStopStrings:t.toolCallStopStrings,structured:t.structured,tools:t.rawTools,toolNaming:t.toolNaming,topKSampling:t.topKSampling,repeatPenalty:wr(t.repeatPenalty,1.1),minPSampling:wr(t.minPSampling,.05),topPSampling:wr(t.topPSampling,.95),"llama.xtcProbability":wr(t.xtcProbability,0),"llama.xtcThreshold":wr(t.xtcThreshold,0),logProbs:wr(t.logProbs,0),"llama.cpuThreads":t.cpuThreads,promptTemplate:t.promptTemplate,"speculativeDecoding.draftModel":t.draftModel,"speculativeDecoding.numDraftTokensExact":t.speculativeDecodingNumDraftTokensExact,"speculativeDecoding.minDraftLengthToConsider":t.speculativeDecodingMinDraftLengthToConsider,"speculativeDecoding.minContinueDraftingProbability":t.speculativeDecodingMinContinueDraftingProbability,"reasoning.parsing":t.reasoningParsing});return t.raw!==void 0?Fp([t.raw,e]):e}var Xe={},be={},gh;function _r(){if(gh)return be;gh=1;var t=be.ValidationError=function(g,y,b,D,v,S){if(Array.isArray(D)?(this.path=D,this.property=D.reduce(function(x,_){return x+l(_)},"instance")):D!==void 0&&(this.property=D),g&&(this.message=g),b){var C=b.$id||b.id;this.schema=C||b}y!==void 0&&(this.instance=y),this.name=v,this.argument=S,this.stack=this.toString()};t.prototype.toString=function(){return this.property+" "+this.message};var e=be.ValidatorResult=function(g,y,b,D){this.instance=g,this.schema=y,this.options=b,this.path=D.path,this.propertyPath=D.propertyPath,this.errors=[],this.throwError=b&&b.throwError,this.throwFirst=b&&b.throwFirst,this.throwAll=b&&b.throwAll,this.disableFormat=b&&b.disableFormat===!0};e.prototype.addError=function(g){var y;if(typeof g=="string")y=new t(g,this.instance,this.schema,this.path);else{if(!g)throw new Error("Missing error detail");if(!g.message)throw new Error("Missing error message");if(!g.name)throw new Error("Missing validator type");y=new t(g.message,this.instance,this.schema,this.path,g.name,g.argument)}if(this.errors.push(y),this.throwFirst)throw new n(this);if(this.throwError)throw y;return y},e.prototype.importErrors=function(g){typeof g=="string"||g&&g.validatorType?this.addError(g):g&&g.errors&&(this.errors=this.errors.concat(g.errors))};function r(m,g){return g+": "+m.toString()+`
226
- `}e.prototype.toString=function(g){return this.errors.map(r).join("")},Object.defineProperty(e.prototype,"valid",{get:function(){return!this.errors.length}}),be.ValidatorResultError=n;function n(m){typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n),this.instance=m.instance,this.schema=m.schema,this.options=m.options,this.errors=m.errors}n.prototype=new Error,n.prototype.constructor=n,n.prototype.name="Validation Error";var i=be.SchemaError=function m(g,y){this.message=g,this.schema=y,Error.call(this,g),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,m)};i.prototype=Object.create(Error.prototype,{constructor:{value:i,enumerable:!1},name:{value:"SchemaError",enumerable:!1}});var s=be.SchemaContext=function(g,y,b,D,v){this.schema=g,this.options=y,Array.isArray(b)?(this.path=b,this.propertyPath=b.reduce(function(S,C){return S+l(C)},"instance")):this.propertyPath=b,this.base=D,this.schemas=v};s.prototype.resolve=function(g){return p(this.base,g)},s.prototype.makeChild=function(g,y){var b=y===void 0?this.path:this.path.concat([y]),D=g.$id||g.id;let v=p(this.base,D||"");var S=new s(g,this.options,b,v,Object.create(this.schemas));return D&&!S.schemas[v]&&(S.schemas[v]=g),S};var a=be.FORMAT_REGEXPS={"date-time":/^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,date:/^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,time:/^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,duration:/P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i,email:/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,"idn-email":/^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u,"ip-address":/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,ipv6:/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,"uri-reference":/^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/,iri:/^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,"iri-reference":/^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u,uuid:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,"uri-template":/(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu,"json-pointer":/^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu,"relative-json-pointer":/^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu,hostname:/^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,"host-name":/^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,"utc-millisec":function(m){return typeof m=="string"&&parseFloat(m)===parseInt(m,10)&&!isNaN(m)},regex:function(m){var g=!0;try{new RegExp(m)}catch{g=!1}return g},style:/[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/,color:/^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,phone:/^\+(?:[0-9] ?){6,14}[0-9]$/,alpha:/^[a-zA-Z]+$/,alphanumeric:/^[a-zA-Z0-9]+$/};a.regexp=a.regex,a.pattern=a.regex,a.ipv4=a["ip-address"],be.isFormat=function(g,y,b){if(typeof g=="string"&&a[y]!==void 0){if(a[y]instanceof RegExp)return a[y].test(g);if(typeof a[y]=="function")return a[y](g)}else if(b&&b.customFormats&&typeof b.customFormats[y]=="function")return b.customFormats[y](g);return!0};var l=be.makeSuffix=function(g){return g=g.toString(),!g.match(/[.\s\[\]]/)&&!g.match(/^[\d]/)?"."+g:g.match(/^\d+$/)?"["+g+"]":"["+JSON.stringify(g)+"]"};be.deepCompareStrict=function m(g,y){if(typeof g!=typeof y)return!1;if(Array.isArray(g))return!Array.isArray(y)||g.length!==y.length?!1:g.every(function(v,S){return m(g[S],y[S])});if(typeof g=="object"){if(!g||!y)return g===y;var b=Object.keys(g),D=Object.keys(y);return b.length!==D.length?!1:b.every(function(v){return m(g[v],y[v])})}return g===y};function c(m,g,y,b){typeof y=="object"?g[b]=f(m[b],y):m.indexOf(y)===-1&&g.push(y)}function u(m,g,y){g[y]=m[y]}function h(m,g,y,b){typeof g[b]!="object"||!g[b]?y[b]=g[b]:m[b]?y[b]=f(m[b],g[b]):y[b]=g[b]}function f(m,g){var y=Array.isArray(g),b=y&&[]||{};return y?(m=m||[],b=b.concat(m),g.forEach(c.bind(null,m,b))):(m&&typeof m=="object"&&Object.keys(m).forEach(u.bind(null,m,b)),Object.keys(g).forEach(h.bind(null,m,g,b))),b}be.deepMerge=f,be.objectGetPath=function(g,y){for(var b=y.split("/").slice(1),D;typeof(D=b.shift())=="string";){var v=decodeURIComponent(D.replace(/~0/,"~").replace(/~1/g,"/"));if(!(v in g))return;g=g[v]}return g};function d(m){return"/"+encodeURIComponent(m).replace(/~/g,"%7E")}be.encodePath=function(g){return g.map(d).join("")},be.getDecimalPlaces=function(g){var y=0;if(isNaN(g))return y;typeof g!="number"&&(g=Number(g));var b=g.toString().split("e");if(b.length===2){if(b[1][0]!=="-")return y;y=Number(b[1].slice(1))}var D=b[0].split(".");return D.length===2&&(y+=D[1].length),y},be.isSchema=function(g){return typeof g=="object"&&g||typeof g=="boolean"};var p=be.resolveUrl=function(g,y){let b=new URL(y,new URL(g,"resolve://"));if(b.protocol==="resolve:"){let{pathname:D,search:v,hash:S}=b;return D+v+S}return b.toString()};return be}var Oa,yh;function U1(){if(yh)return Oa;yh=1;var t=_r(),e=t.ValidatorResult,r=t.SchemaError,n={};n.ignoreProperties={id:!0,default:!0,description:!0,title:!0,additionalItems:!0,then:!0,else:!0,$schema:!0,$ref:!0,extends:!0};var i=n.validators={};i.type=function(f,d,p,m){if(f===void 0)return null;var g=new e(f,d,p,m),y=Array.isArray(d.type)?d.type:[d.type];if(!y.some(this.testType.bind(this,f,d,p,m))){var b=y.map(function(D){if(D){var v=D.$id||D.id;return v?"<"+v+">":D+""}});g.addError({name:"type",argument:b,message:"is not of a type(s) "+b})}return g};function s(h,f,d,p,m){var g=f.throwError,y=f.throwAll;f.throwError=!1,f.throwAll=!1;var b=this.validateSchema(h,m,f,d);return f.throwError=g,f.throwAll=y,!b.valid&&p instanceof Function&&p(b),b.valid}i.anyOf=function(f,d,p,m){if(f===void 0)return null;var g=new e(f,d,p,m),y=new e(f,d,p,m);if(!Array.isArray(d.anyOf))throw new r("anyOf must be an array");if(!d.anyOf.some(s.bind(this,f,p,m,function(D){y.importErrors(D)}))){var b=d.anyOf.map(function(D,v){var S=D.$id||D.id;return S?"<"+S+">":D.title&&JSON.stringify(D.title)||D.$ref&&"<"+D.$ref+">"||"[subschema "+v+"]"});p.nestedErrors&&g.importErrors(y),g.addError({name:"anyOf",argument:b,message:"is not any of "+b.join(",")})}return g},i.allOf=function(f,d,p,m){if(f===void 0)return null;if(!Array.isArray(d.allOf))throw new r("allOf must be an array");var g=new e(f,d,p,m),y=this;return d.allOf.forEach(function(b,D){var v=y.validateSchema(f,b,p,m);if(!v.valid){var S=b.$id||b.id,C=S||b.title&&JSON.stringify(b.title)||b.$ref&&"<"+b.$ref+">"||"[subschema "+D+"]";g.addError({name:"allOf",argument:{id:C,length:v.errors.length,valid:v},message:"does not match allOf schema "+C+" with "+v.errors.length+" error[s]:"}),g.importErrors(v)}}),g},i.oneOf=function(f,d,p,m){if(f===void 0)return null;if(!Array.isArray(d.oneOf))throw new r("oneOf must be an array");var g=new e(f,d,p,m),y=new e(f,d,p,m),b=d.oneOf.filter(s.bind(this,f,p,m,function(v){y.importErrors(v)})).length,D=d.oneOf.map(function(v,S){var C=v.$id||v.id;return C||v.title&&JSON.stringify(v.title)||v.$ref&&"<"+v.$ref+">"||"[subschema "+S+"]"});return b!==1&&(p.nestedErrors&&g.importErrors(y),g.addError({name:"oneOf",argument:D,message:"is not exactly one from "+D.join(",")})),g},i.if=function(f,d,p,m){if(f===void 0)return null;if(!t.isSchema(d.if))throw new Error('Expected "if" keyword to be a schema');var g=s.call(this,f,p,m,null,d.if),y=new e(f,d,p,m),b;if(g){if(d.then===void 0)return;if(!t.isSchema(d.then))throw new Error('Expected "then" keyword to be a schema');b=this.validateSchema(f,d.then,p,m.makeChild(d.then)),y.importErrors(b)}else{if(d.else===void 0)return;if(!t.isSchema(d.else))throw new Error('Expected "else" keyword to be a schema');b=this.validateSchema(f,d.else,p,m.makeChild(d.else)),y.importErrors(b)}return y};function a(h,f){if(Object.hasOwnProperty.call(h,f))return h[f];if(f in h){for(;h=Object.getPrototypeOf(h);)if(Object.propertyIsEnumerable.call(h,f))return h[f]}}i.propertyNames=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),y=d.propertyNames!==void 0?d.propertyNames:{};if(!t.isSchema(y))throw new r('Expected "propertyNames" to be a schema (object or boolean)');for(var b in f)if(a(f,b)!==void 0){var D=this.validateSchema(b,y,p,m.makeChild(y));g.importErrors(D)}return g}},i.properties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),y=d.properties||{};for(var b in y){var D=y[b];if(D!==void 0){if(D===null)throw new r('Unexpected null, expected schema in "properties"');typeof p.preValidateProperty=="function"&&p.preValidateProperty(f,b,D,p,m);var v=a(f,b),S=this.validateSchema(v,D,p,m.makeChild(D,b));S.instance!==g.instance[b]&&(g.instance[b]=S.instance),g.importErrors(S)}}return g}};function l(h,f,d,p,m,g){if(this.types.object(h)&&!(f.properties&&f.properties[m]!==void 0))if(f.additionalProperties===!1)g.addError({name:"additionalProperties",argument:m,message:"is not allowed to have the additional property "+JSON.stringify(m)});else{var y=f.additionalProperties||{};typeof d.preValidateProperty=="function"&&d.preValidateProperty(h,m,y,d,p);var b=this.validateSchema(h[m],y,d,p.makeChild(y,m));b.instance!==g.instance[m]&&(g.instance[m]=b.instance),g.importErrors(b)}}i.patternProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),y=d.patternProperties||{};for(var b in f){var D=!0;for(var v in y){var S=y[v];if(S!==void 0){if(S===null)throw new r('Unexpected null, expected schema in "patternProperties"');try{var C=new RegExp(v,"u")}catch{C=new RegExp(v)}if(C.test(b)){D=!1,typeof p.preValidateProperty=="function"&&p.preValidateProperty(f,b,S,p,m);var x=this.validateSchema(f[b],S,p,m.makeChild(S,b));x.instance!==g.instance[b]&&(g.instance[b]=x.instance),g.importErrors(x)}}}D&&l.call(this,f,d,p,m,b,g)}return g}},i.additionalProperties=function(f,d,p,m){if(this.types.object(f)){if(d.patternProperties)return null;var g=new e(f,d,p,m);for(var y in f)l.call(this,f,d,p,m,y,g);return g}},i.minProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),y=Object.keys(f);return y.length>=d.minProperties||g.addError({name:"minProperties",argument:d.minProperties,message:"does not meet minimum property length of "+d.minProperties}),g}},i.maxProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),y=Object.keys(f);return y.length<=d.maxProperties||g.addError({name:"maxProperties",argument:d.maxProperties,message:"does not meet maximum property length of "+d.maxProperties}),g}},i.items=function(f,d,p,m){var g=this;if(this.types.array(f)&&d.items!==void 0){var y=new e(f,d,p,m);return f.every(function(b,D){if(Array.isArray(d.items))var v=d.items[D]===void 0?d.additionalItems:d.items[D];else var v=d.items;if(v===void 0)return!0;if(v===!1)return y.addError({name:"items",message:"additionalItems not permitted"}),!1;var S=g.validateSchema(b,v,p,m.makeChild(v,D));return S.instance!==y.instance[D]&&(y.instance[D]=S.instance),y.importErrors(S),!0}),y}},i.contains=function(f,d,p,m){var g=this;if(this.types.array(f)&&d.contains!==void 0){if(!t.isSchema(d.contains))throw new Error('Expected "contains" keyword to be a schema');var y=new e(f,d,p,m),b=f.some(function(D,v){var S=g.validateSchema(D,d.contains,p,m.makeChild(d.contains,v));return S.errors.length===0});return b===!1&&y.addError({name:"contains",argument:d.contains,message:"must contain an item matching given schema"}),y}},i.minimum=function(f,d,p,m){if(this.types.number(f)){var g=new e(f,d,p,m);return d.exclusiveMinimum&&d.exclusiveMinimum===!0?f>d.minimum||g.addError({name:"minimum",argument:d.minimum,message:"must be greater than "+d.minimum}):f>=d.minimum||g.addError({name:"minimum",argument:d.minimum,message:"must be greater than or equal to "+d.minimum}),g}},i.maximum=function(f,d,p,m){if(this.types.number(f)){var g=new e(f,d,p,m);return d.exclusiveMaximum&&d.exclusiveMaximum===!0?f<d.maximum||g.addError({name:"maximum",argument:d.maximum,message:"must be less than "+d.maximum}):f<=d.maximum||g.addError({name:"maximum",argument:d.maximum,message:"must be less than or equal to "+d.maximum}),g}},i.exclusiveMinimum=function(f,d,p,m){if(typeof d.exclusiveMinimum!="boolean"&&this.types.number(f)){var g=new e(f,d,p,m),y=f>d.exclusiveMinimum;return y||g.addError({name:"exclusiveMinimum",argument:d.exclusiveMinimum,message:"must be strictly greater than "+d.exclusiveMinimum}),g}},i.exclusiveMaximum=function(f,d,p,m){if(typeof d.exclusiveMaximum!="boolean"&&this.types.number(f)){var g=new e(f,d,p,m),y=f<d.exclusiveMaximum;return y||g.addError({name:"exclusiveMaximum",argument:d.exclusiveMaximum,message:"must be strictly less than "+d.exclusiveMaximum}),g}};var c=function(f,d,p,m,g,y){if(this.types.number(f)){var b=d[g];if(b==0)throw new r(g+" cannot be zero");var D=new e(f,d,p,m),v=t.getDecimalPlaces(f),S=t.getDecimalPlaces(b),C=Math.max(v,S),x=Math.pow(10,C);return Math.round(f*x)%Math.round(b*x)!==0&&D.addError({name:g,argument:b,message:y+JSON.stringify(b)}),D}};i.multipleOf=function(f,d,p,m){return c.call(this,f,d,p,m,"multipleOf","is not a multiple of (divisible by) ")},i.divisibleBy=function(f,d,p,m){return c.call(this,f,d,p,m,"divisibleBy","is not divisible by (multiple of) ")},i.required=function(f,d,p,m){var g=new e(f,d,p,m);return f===void 0&&d.required===!0?g.addError({name:"required",message:"is required"}):this.types.object(f)&&Array.isArray(d.required)&&d.required.forEach(function(y){a(f,y)===void 0&&g.addError({name:"required",argument:y,message:"requires property "+JSON.stringify(y)})}),g},i.pattern=function(f,d,p,m){if(this.types.string(f)){var g=new e(f,d,p,m),y=d.pattern;try{var b=new RegExp(y,"u")}catch{b=new RegExp(y)}return f.match(b)||g.addError({name:"pattern",argument:d.pattern,message:"does not match pattern "+JSON.stringify(d.pattern.toString())}),g}},i.format=function(f,d,p,m){if(f!==void 0){var g=new e(f,d,p,m);return!g.disableFormat&&!t.isFormat(f,d.format,this)&&g.addError({name:"format",argument:d.format,message:"does not conform to the "+JSON.stringify(d.format)+" format"}),g}},i.minLength=function(f,d,p,m){if(this.types.string(f)){var g=new e(f,d,p,m),y=f.match(/[\uDC00-\uDFFF]/g),b=f.length-(y?y.length:0);return b>=d.minLength||g.addError({name:"minLength",argument:d.minLength,message:"does not meet minimum length of "+d.minLength}),g}},i.maxLength=function(f,d,p,m){if(this.types.string(f)){var g=new e(f,d,p,m),y=f.match(/[\uDC00-\uDFFF]/g),b=f.length-(y?y.length:0);return b<=d.maxLength||g.addError({name:"maxLength",argument:d.maxLength,message:"does not meet maximum length of "+d.maxLength}),g}},i.minItems=function(f,d,p,m){if(this.types.array(f)){var g=new e(f,d,p,m);return f.length>=d.minItems||g.addError({name:"minItems",argument:d.minItems,message:"does not meet minimum length of "+d.minItems}),g}},i.maxItems=function(f,d,p,m){if(this.types.array(f)){var g=new e(f,d,p,m);return f.length<=d.maxItems||g.addError({name:"maxItems",argument:d.maxItems,message:"does not meet maximum length of "+d.maxItems}),g}};function u(h,f,d){var p,m=d.length;for(p=f+1,m;p<m;p++)if(t.deepCompareStrict(h,d[p]))return!1;return!0}return i.uniqueItems=function(f,d,p,m){if(d.uniqueItems===!0&&this.types.array(f)){var g=new e(f,d,p,m);return f.every(u)||g.addError({name:"uniqueItems",message:"contains duplicate item"}),g}},i.dependencies=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m);for(var y in d.dependencies)if(f[y]!==void 0){var b=d.dependencies[y],D=m.makeChild(b,y);if(typeof b=="string"&&(b=[b]),Array.isArray(b))b.forEach(function(S){f[S]===void 0&&g.addError({name:"dependencies",argument:D.propertyPath,message:"property "+S+" not found, required by "+D.propertyPath})});else{var v=this.validateSchema(f,b,p,D);g.instance!==v.instance&&(g.instance=v.instance),v&&v.errors.length&&(g.addError({name:"dependencies",argument:D.propertyPath,message:"does not meet dependency required by "+D.propertyPath}),g.importErrors(v))}}return g}},i.enum=function(f,d,p,m){if(f===void 0)return null;if(!Array.isArray(d.enum))throw new r("enum expects an array",d);var g=new e(f,d,p,m);return d.enum.some(t.deepCompareStrict.bind(null,f))||g.addError({name:"enum",argument:d.enum,message:"is not one of enum values: "+d.enum.map(String).join(",")}),g},i.const=function(f,d,p,m){if(f===void 0)return null;var g=new e(f,d,p,m);return t.deepCompareStrict(d.const,f)||g.addError({name:"const",argument:d.const,message:"does not exactly match expected constant: "+d.const}),g},i.not=i.disallow=function(f,d,p,m){var g=this;if(f===void 0)return null;var y=new e(f,d,p,m),b=d.not||d.disallow;return b?(Array.isArray(b)||(b=[b]),b.forEach(function(D){if(g.testType(f,d,p,m,D)){var v=D&&(D.$id||D.id),S=v||D;y.addError({name:"not",argument:S,message:"is of prohibited type "+S})}}),y):null},Oa=n,Oa}var vs={},bh;function Qa(){if(bh)return vs;bh=1;var t=_r();vs.SchemaScanResult=e;function e(r,n){this.id=r,this.ref=n}return vs.scan=function(n,i){function s(h,f){if(!f||typeof f!="object")return;if(f.$ref){let g=t.resolveUrl(h,f.$ref);u[g]=u[g]?u[g]+1:0;return}var d=f.$id||f.id;let p=t.resolveUrl(h,d);var m=d?p:h;if(m){if(m.indexOf("#")<0&&(m+="#"),c[m]){if(!t.deepCompareStrict(c[m],f))throw new Error("Schema <"+m+"> already exists with different definition");return c[m]}c[m]=f,m[m.length-1]=="#"&&(c[m.substring(0,m.length-1)]=f)}a(m+"/items",Array.isArray(f.items)?f.items:[f.items]),a(m+"/extends",Array.isArray(f.extends)?f.extends:[f.extends]),s(m+"/additionalItems",f.additionalItems),l(m+"/properties",f.properties),s(m+"/additionalProperties",f.additionalProperties),l(m+"/definitions",f.definitions),l(m+"/patternProperties",f.patternProperties),l(m+"/dependencies",f.dependencies),a(m+"/disallow",f.disallow),a(m+"/allOf",f.allOf),a(m+"/anyOf",f.anyOf),a(m+"/oneOf",f.oneOf),s(m+"/not",f.not)}function a(h,f){if(Array.isArray(f))for(var d=0;d<f.length;d++)s(h+"/"+d,f[d])}function l(h,f){if(!(!f||typeof f!="object"))for(var d in f)s(h+"/"+d,f[d])}var c={},u={};return s(n,i),new e(c,u)},vs}var Ia,vh;function q1(){if(vh)return Ia;vh=1;var t=U1(),e=_r(),r=Qa().scan,n=e.ValidatorResult,i=e.ValidatorResultError,s=e.SchemaError,a=e.SchemaContext,l="/",c=function f(){this.customFormats=Object.create(f.prototype.customFormats),this.schemas={},this.unresolvedRefs=[],this.types=Object.create(h),this.attributes=Object.create(t.validators)};c.prototype.customFormats={},c.prototype.schemas=null,c.prototype.types=null,c.prototype.attributes=null,c.prototype.unresolvedRefs=null,c.prototype.addSchema=function(d,p){var m=this;if(!d)return null;var g=r(p||l,d),y=p||d.$id||d.id;for(var b in g.id)this.schemas[b]=g.id[b];for(var b in g.ref)this.unresolvedRefs.push(b);return this.unresolvedRefs=this.unresolvedRefs.filter(function(D){return typeof m.schemas[D]>"u"}),this.schemas[y]},c.prototype.addSubSchemaArray=function(d,p){if(Array.isArray(p))for(var m=0;m<p.length;m++)this.addSubSchema(d,p[m])},c.prototype.addSubSchemaObject=function(d,p){if(!(!p||typeof p!="object"))for(var m in p)this.addSubSchema(d,p[m])},c.prototype.setSchemas=function(d){this.schemas=d},c.prototype.getSchema=function(d){return this.schemas[d]},c.prototype.validate=function(d,p,m,g){if(typeof p!="boolean"&&typeof p!="object"||p===null)throw new s("Expected `schema` to be an object or boolean");m||(m={});var y=p.$id||p.id;let b=e.resolveUrl(m.base,y||"");if(!g){g=new a(p,m,[],b,Object.create(this.schemas)),g.schemas[b]||(g.schemas[b]=p);var D=r(b,p);for(var v in D.id){var S=D.id[v];g.schemas[v]=S}}if(m.required&&d===void 0){var C=new n(d,p,m,g);return C.addError("is required, but is undefined"),C}var C=this.validateSchema(d,p,m,g);if(C){if(m.throwAll&&C.errors.length)throw new i(C)}else throw new Error("Result undefined");return C};function u(f){var d=typeof f=="string"?f:f.$ref;return typeof d=="string"?d:!1}c.prototype.validateSchema=function(d,p,m,g){var y=new n(d,p,m,g);if(typeof p=="boolean")p===!0?p={}:p===!1&&(p={type:[]});else if(!p)throw new Error("schema is undefined");if(p.extends)if(Array.isArray(p.extends)){var b={schema:p,ctx:g};p.extends.forEach(this.schemaTraverser.bind(this,b)),p=b.schema,b.schema=null,b.ctx=null,b=null}else p=e.deepMerge(p,this.superResolve(p.extends,g));var D=u(p);if(D){var v=this.resolve(p,D,g),S=new a(v.subschema,m,g.path,v.switchSchema,g.schemas);return this.validateSchema(d,v.subschema,m,S)}var C=m&&m.skipAttributes||[];for(var x in p)if(!t.ignoreProperties[x]&&C.indexOf(x)<0){var _=null,B=this.attributes[x];if(B)_=B.call(this,d,p,m,g);else if(m.allowUnknownAttributes===!1)throw new s("Unsupported attribute: "+x,p);_&&y.importErrors(_)}if(typeof m.rewrite=="function"){var w=m.rewrite.call(this,d,p,m,g);y.instance=w}return y},c.prototype.schemaTraverser=function(d,p){d.schema=e.deepMerge(d.schema,this.superResolve(p,d.ctx))},c.prototype.superResolve=function(d,p){var m=u(d);return m?this.resolve(d,m,p).subschema:d},c.prototype.resolve=function(d,p,m){if(p=m.resolve(p),m.schemas[p])return{subschema:m.schemas[p],switchSchema:p};let y=new URL(p,"thismessage::/").hash;var b=y&&y.length&&p.substr(0,p.length-y.length);if(!b||!m.schemas[b])throw new s("no such schema <"+p+">",d);var D=e.objectGetPath(m.schemas[b],y.substr(1));if(D===void 0)throw new s("no such schema "+y+" located in <"+b+">",d);return{subschema:D,switchSchema:p}},c.prototype.testType=function(d,p,m,g,y){if(y!==void 0){if(y===null)throw new s('Unexpected null in "type" keyword');if(typeof this.types[y]=="function")return this.types[y].call(this,d);if(y&&typeof y=="object"){var b=this.validateSchema(d,y,m,g);return b===void 0||!(b&&b.errors.length)}return!0}};var h=c.prototype.types={};return h.string=function(d){return typeof d=="string"},h.number=function(d){return typeof d=="number"&&isFinite(d)},h.integer=function(d){return typeof d=="number"&&d%1===0},h.boolean=function(d){return typeof d=="boolean"},h.array=function(d){return Array.isArray(d)},h.null=function(d){return d===null},h.date=function(d){return d instanceof Date},h.any=function(d){return!0},h.object=function(d){return d&&typeof d=="object"&&!Array.isArray(d)&&!(d instanceof Date)},Ia=c,Ia}var Dh;function z1(){if(Dh)return Xe;Dh=1;var t=Xe.Validator=q1();return Xe.ValidatorResult=_r().ValidatorResult,Xe.ValidatorResultError=_r().ValidatorResultError,Xe.ValidationError=_r().ValidationError,Xe.SchemaError=_r().SchemaError,Xe.SchemaScanResult=Qa().SchemaScanResult,Xe.scan=Qa().scan,Xe.validate=function(e,r,n){var i=new t;return i.validate(e,r,n)},Xe}var V1=z1(),Qs=o.object({name:o.string(),description:o.string()}),Xa=class{constructor(e,r,n){this.logger=e,this.signal=r,this.callId=n}status(e){this.logger.info(e)}warn(e){this.logger.warn(e)}},W1=Qs.extend({type:o.literal("function"),parametersSchema:Rr,checkParameters:o.function(),implementation:o.function()}),G1=Qs.extend({type:o.literal("rawFunction"),parametersSchema:Rr,checkParameters:o.function(),implementation:o.function()}),Z1=Qs.extend({type:o.literal("unimplementedRawFunction"),parametersJsonSchema:Rr,checkParameters:o.function(),implementation:o.function()}),K1=Qs.extend({type:o.literal("remoteTool"),pluginIdentifier:o.string(),parametersJsonSchema:Rr,checkParameters:o.function(),implementation:o.function()});o.discriminatedUnion("type",[W1,G1,Z1,K1]);function H1(t,e){return e.map(r=>`${[t,...r.path].join(".")} ${r.message}`).join(`
227
- `)}var el=class extends Error{constructor(e){super(`Tool "${e}" is not implemented.`)}};function Y1({name:t,description:e,pluginIdentifier:r,parametersJsonSchema:n,implementation:i}){return{name:t,description:e,type:"remoteTool",pluginIdentifier:r,parametersJsonSchema:n,checkParameters:s=>{let l=new V1.Validator().validate(s,n);if(l.errors.length>0)throw new Error(j`
225
+ `},stopStrings:[]}).field("systemPrompt","string",{isParagraph:!0},"").field("seed","checkboxNumeric",{int:!0,min:-1,uncheckedHint:"config:seedUncheckedHint"},{checked:!1,value:-1}).field("contextPrefill","context",{},[]).field("topKSampling","numeric",{min:-1,max:500,int:!0},40).field("repeatPenalty","checkboxNumeric",{min:-1,step:.01},{checked:!0,value:1.1}).field("minPSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!0,value:.05}).field("topPSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!0,value:.95}).field("logProbs","checkboxNumeric",{min:0,max:100,int:!0},{checked:!1,value:0}).scope("reasoning",e=>e.field("parsing","llmReasoningParsing",{},{enabled:!0,startString:"<think>",endString:"</think>"})).scope("llama",e=>e.field("cpuThreads","numeric",{min:1,int:!0},4).field("frequencyPenalty","checkboxNumeric",{precision:2},{checked:!1,value:0}).field("xtcProbability","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!1,value:.5}).field("xtcThreshold","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:.5,step:.01}},{checked:!1,value:.1}).field("presencePenalty","checkboxNumeric",{precision:2},{checked:!1,value:0}).field("mirostatSampling","llamaMirostatSampling",{},{version:0,learningRate:.1,targetEntropy:5}).field("tailFreeSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!1,value:.95}).field("locallyTypicalSampling","checkboxNumeric",{min:0,max:1,step:.01,precision:2,slider:{min:0,max:1,step:.01}},{checked:!1,value:.9}).field("logitBias","llamaLogitBias",{},[]))).scope("llm.load",t=>t.field("contextLength","contextLength",{machineDependent:!0},2048).field("numExperts","numeric",{min:0,int:!0},0).field("seed","checkboxNumeric",{int:!0,min:-1,uncheckedHint:"config:seedUncheckedHint"},{checked:!1,value:-1}).field("offloadKVCacheToGpu","boolean",{},!0).field("numCpuExpertLayersRatio","llamaAccelerationOffloadRatio",{machineDependent:!0,isExperimental:!0},"off").scope("llama",e=>e.scope("acceleration",r=>r.field("offloadRatio","llamaAccelerationOffloadRatio",{machineDependent:!0},"max")).field("cpuThreadPoolSize","numeric",{min:1,machineDependent:!0},4).field("evalBatchSize","numeric",{min:1,int:!0},512).field("flashAttention","boolean",{isExperimental:!0,warning:"config:flashAttentionWarning"},!1).field("ropeFrequencyBase","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyBaseUncheckedHint"},{checked:!1,value:0}).field("ropeFrequencyScale","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyScaleUncheckedHint"},{checked:!1,value:0}).field("keepModelInMemory","boolean",{},!0).field("useFp16ForKVCache","boolean",{},!0).field("tryMmap","boolean",{},!0).field("kCacheQuantizationType","llamaCacheQuantizationType",{isExperimental:!0},{checked:!1,value:"f16"}).field("vCacheQuantizationType","llamaCacheQuantizationType",{isExperimental:!0,warning:"config:llamaKvCacheQuantizationWarning"},{checked:!1,value:"f16"})).scope("mlx",e=>e.field("kvCacheQuantization","mlxKvCacheQuantizationType",{isExperimental:!0},{enabled:!1,bits:8,groupSize:64,quantizedStart:5e3}))).scope("load",t=>t.field("gpuSplitConfig","gpuSplitConfig",{},xw).field("gpuStrictVramCap","boolean",{},!1)).scope("embedding.load",t=>t.field("contextLength","contextLength",{machineDependent:!0},2048).field("seed","checkboxNumeric",{int:!0,min:-1,uncheckedHint:"config:seedUncheckedHint"},{checked:!1,value:-1}).scope("llama",e=>e.scope("acceleration",r=>r.field("offloadRatio","llamaAccelerationOffloadRatio",{machineDependent:!0},"max")).field("evalBatchSize","numeric",{min:1,int:!0},512).field("ropeFrequencyBase","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyBaseUncheckedHint"},{checked:!1,value:0}).field("ropeFrequencyScale","checkboxNumeric",{min:0,uncheckedHint:"config:ropeFrequencyScaleUncheckedHint"},{checked:!1,value:0}).field("keepModelInMemory","boolean",{},!0).field("tryMmap","boolean",{},!0))).scope("retrieval",t=>t.field("databaseFile","string",{machineDependent:!0},"").field("chunkingMethod","retrievalChunkingMethod",{},{type:"recursive-v1",chunkSize:512,chunkOverlap:100}).field("limit","numeric",{min:1,int:!0},5).field("embeddingModel","modelIdentifier",{domain:["embedding"]},"")).build(),vn=qt.scoped("llm.prediction"),gi=vn.sliced("temperature","maxPredictedTokens","promptTemplate","systemPrompt","seed","contextPrefill","tools","toolNaming","reasoning.*");gi.union(vn.sliced("llama.*","contextOverflowPolicy","stopStrings","toolCallStopStrings","structured","topKSampling","repeatPenalty","minPSampling","topPSampling","logProbs","speculativeDecoding.draftModel","speculativeDecoding.minContinueDraftingProbability","speculativeDecoding.minDraftLengthToConsider","speculativeDecoding.maxTokensToDraft","speculativeDecoding.numReuseTokens"));gi.union(vn.sliced("mlx.*","contextOverflowPolicy","stopStrings","toolCallStopStrings","structured","repeatPenalty","minPSampling","topPSampling","topKSampling","speculativeDecoding.draftModel","speculativeDecoding.numDraftTokensExact"));gi.union(vn.sliced("transformers.*"));gi.union(vn.sliced("onnx.*","repeatPenalty","topPSampling","topKSampling"));var Dn=qt.scoped("llm.load").union(qt.sliced("envVars")),yi=Dn.sliced("contextLength","seed","envVars"),Ip=qt.sliced("llama.load.*","load.*"),j1=yi.union(Dn.sliced("llama.*","load.*","offloadKVCacheToGpu")).union(Ip);yi.union(Dn.sliced("mlx.*"));yi.union(Dn.sliced("transformers.*"));yi.union(Dn.sliced("onnx.*"));var B1=Dn.sliced("numExperts","numCpuExpertLayersRatio"),L1=j1.union(B1),Rp=qt.scoped("embedding.load").union(qt.sliced("load.*")),Mp=Rp.sliced("contextLength","seed"),N1=qt.scoped("retrieval"),$1=Mp.union(Rp.sliced("llama.*")).union(Ip);new Ms(Op).build();function wr(t,e){if(t!==void 0)return t===!1?{checked:!1,value:e}:{checked:!0,value:t}}function U1(t){let e=vn.buildPartialConfig({temperature:t.temperature,contextOverflowPolicy:t.contextOverflowPolicy,maxPredictedTokens:wr(t.maxTokens,1),stopStrings:t.stopStrings,toolCallStopStrings:t.toolCallStopStrings,structured:t.structured,tools:t.rawTools,toolNaming:t.toolNaming,topKSampling:t.topKSampling,repeatPenalty:wr(t.repeatPenalty,1.1),minPSampling:wr(t.minPSampling,.05),topPSampling:wr(t.topPSampling,.95),"llama.xtcProbability":wr(t.xtcProbability,0),"llama.xtcThreshold":wr(t.xtcThreshold,0),logProbs:wr(t.logProbs,0),"llama.cpuThreads":t.cpuThreads,promptTemplate:t.promptTemplate,"speculativeDecoding.draftModel":t.draftModel,"speculativeDecoding.numDraftTokensExact":t.speculativeDecodingNumDraftTokensExact,"speculativeDecoding.minDraftLengthToConsider":t.speculativeDecodingMinDraftLengthToConsider,"speculativeDecoding.minContinueDraftingProbability":t.speculativeDecodingMinContinueDraftingProbability,"reasoning.parsing":t.reasoningParsing});return t.raw!==void 0?Pp([t.raw,e]):e}var tt={},be={},yh;function _r(){if(yh)return be;yh=1;var t=be.ValidationError=function(g,y,b,D,v,S){if(Array.isArray(D)?(this.path=D,this.property=D.reduce(function(x,_){return x+l(_)},"instance")):D!==void 0&&(this.property=D),g&&(this.message=g),b){var C=b.$id||b.id;this.schema=C||b}y!==void 0&&(this.instance=y),this.name=v,this.argument=S,this.stack=this.toString()};t.prototype.toString=function(){return this.property+" "+this.message};var e=be.ValidatorResult=function(g,y,b,D){this.instance=g,this.schema=y,this.options=b,this.path=D.path,this.propertyPath=D.propertyPath,this.errors=[],this.throwError=b&&b.throwError,this.throwFirst=b&&b.throwFirst,this.throwAll=b&&b.throwAll,this.disableFormat=b&&b.disableFormat===!0};e.prototype.addError=function(g){var y;if(typeof g=="string")y=new t(g,this.instance,this.schema,this.path);else{if(!g)throw new Error("Missing error detail");if(!g.message)throw new Error("Missing error message");if(!g.name)throw new Error("Missing validator type");y=new t(g.message,this.instance,this.schema,this.path,g.name,g.argument)}if(this.errors.push(y),this.throwFirst)throw new n(this);if(this.throwError)throw y;return y},e.prototype.importErrors=function(g){typeof g=="string"||g&&g.validatorType?this.addError(g):g&&g.errors&&(this.errors=this.errors.concat(g.errors))};function r(m,g){return g+": "+m.toString()+`
226
+ `}e.prototype.toString=function(g){return this.errors.map(r).join("")},Object.defineProperty(e.prototype,"valid",{get:function(){return!this.errors.length}}),be.ValidatorResultError=n;function n(m){typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n),this.instance=m.instance,this.schema=m.schema,this.options=m.options,this.errors=m.errors}n.prototype=new Error,n.prototype.constructor=n,n.prototype.name="Validation Error";var i=be.SchemaError=function m(g,y){this.message=g,this.schema=y,Error.call(this,g),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,m)};i.prototype=Object.create(Error.prototype,{constructor:{value:i,enumerable:!1},name:{value:"SchemaError",enumerable:!1}});var s=be.SchemaContext=function(g,y,b,D,v){this.schema=g,this.options=y,Array.isArray(b)?(this.path=b,this.propertyPath=b.reduce(function(S,C){return S+l(C)},"instance")):this.propertyPath=b,this.base=D,this.schemas=v};s.prototype.resolve=function(g){return p(this.base,g)},s.prototype.makeChild=function(g,y){var b=y===void 0?this.path:this.path.concat([y]),D=g.$id||g.id;let v=p(this.base,D||"");var S=new s(g,this.options,b,v,Object.create(this.schemas));return D&&!S.schemas[v]&&(S.schemas[v]=g),S};var a=be.FORMAT_REGEXPS={"date-time":/^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,date:/^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,time:/^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,duration:/P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i,email:/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,"idn-email":/^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u,"ip-address":/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,ipv6:/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,uri:/^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,"uri-reference":/^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/,iri:/^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/,"iri-reference":/^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u,uuid:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,"uri-template":/(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu,"json-pointer":/^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu,"relative-json-pointer":/^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu,hostname:/^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,"host-name":/^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,"utc-millisec":function(m){return typeof m=="string"&&parseFloat(m)===parseInt(m,10)&&!isNaN(m)},regex:function(m){var g=!0;try{new RegExp(m)}catch{g=!1}return g},style:/[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/,color:/^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,phone:/^\+(?:[0-9] ?){6,14}[0-9]$/,alpha:/^[a-zA-Z]+$/,alphanumeric:/^[a-zA-Z0-9]+$/};a.regexp=a.regex,a.pattern=a.regex,a.ipv4=a["ip-address"],be.isFormat=function(g,y,b){if(typeof g=="string"&&a[y]!==void 0){if(a[y]instanceof RegExp)return a[y].test(g);if(typeof a[y]=="function")return a[y](g)}else if(b&&b.customFormats&&typeof b.customFormats[y]=="function")return b.customFormats[y](g);return!0};var l=be.makeSuffix=function(g){return g=g.toString(),!g.match(/[.\s\[\]]/)&&!g.match(/^[\d]/)?"."+g:g.match(/^\d+$/)?"["+g+"]":"["+JSON.stringify(g)+"]"};be.deepCompareStrict=function m(g,y){if(typeof g!=typeof y)return!1;if(Array.isArray(g))return!Array.isArray(y)||g.length!==y.length?!1:g.every(function(v,S){return m(g[S],y[S])});if(typeof g=="object"){if(!g||!y)return g===y;var b=Object.keys(g),D=Object.keys(y);return b.length!==D.length?!1:b.every(function(v){return m(g[v],y[v])})}return g===y};function c(m,g,y,b){typeof y=="object"?g[b]=f(m[b],y):m.indexOf(y)===-1&&g.push(y)}function u(m,g,y){g[y]=m[y]}function h(m,g,y,b){typeof g[b]!="object"||!g[b]?y[b]=g[b]:m[b]?y[b]=f(m[b],g[b]):y[b]=g[b]}function f(m,g){var y=Array.isArray(g),b=y&&[]||{};return y?(m=m||[],b=b.concat(m),g.forEach(c.bind(null,m,b))):(m&&typeof m=="object"&&Object.keys(m).forEach(u.bind(null,m,b)),Object.keys(g).forEach(h.bind(null,m,g,b))),b}be.deepMerge=f,be.objectGetPath=function(g,y){for(var b=y.split("/").slice(1),D;typeof(D=b.shift())=="string";){var v=decodeURIComponent(D.replace(/~0/,"~").replace(/~1/g,"/"));if(!(v in g))return;g=g[v]}return g};function d(m){return"/"+encodeURIComponent(m).replace(/~/g,"%7E")}be.encodePath=function(g){return g.map(d).join("")},be.getDecimalPlaces=function(g){var y=0;if(isNaN(g))return y;typeof g!="number"&&(g=Number(g));var b=g.toString().split("e");if(b.length===2){if(b[1][0]!=="-")return y;y=Number(b[1].slice(1))}var D=b[0].split(".");return D.length===2&&(y+=D[1].length),y},be.isSchema=function(g){return typeof g=="object"&&g||typeof g=="boolean"};var p=be.resolveUrl=function(g,y){let b=new URL(y,new URL(g,"resolve://"));if(b.protocol==="resolve:"){let{pathname:D,search:v,hash:S}=b;return D+v+S}return b.toString()};return be}var Ia,bh;function q1(){if(bh)return Ia;bh=1;var t=_r(),e=t.ValidatorResult,r=t.SchemaError,n={};n.ignoreProperties={id:!0,default:!0,description:!0,title:!0,additionalItems:!0,then:!0,else:!0,$schema:!0,$ref:!0,extends:!0};var i=n.validators={};i.type=function(f,d,p,m){if(f===void 0)return null;var g=new e(f,d,p,m),y=Array.isArray(d.type)?d.type:[d.type];if(!y.some(this.testType.bind(this,f,d,p,m))){var b=y.map(function(D){if(D){var v=D.$id||D.id;return v?"<"+v+">":D+""}});g.addError({name:"type",argument:b,message:"is not of a type(s) "+b})}return g};function s(h,f,d,p,m){var g=f.throwError,y=f.throwAll;f.throwError=!1,f.throwAll=!1;var b=this.validateSchema(h,m,f,d);return f.throwError=g,f.throwAll=y,!b.valid&&p instanceof Function&&p(b),b.valid}i.anyOf=function(f,d,p,m){if(f===void 0)return null;var g=new e(f,d,p,m),y=new e(f,d,p,m);if(!Array.isArray(d.anyOf))throw new r("anyOf must be an array");if(!d.anyOf.some(s.bind(this,f,p,m,function(D){y.importErrors(D)}))){var b=d.anyOf.map(function(D,v){var S=D.$id||D.id;return S?"<"+S+">":D.title&&JSON.stringify(D.title)||D.$ref&&"<"+D.$ref+">"||"[subschema "+v+"]"});p.nestedErrors&&g.importErrors(y),g.addError({name:"anyOf",argument:b,message:"is not any of "+b.join(",")})}return g},i.allOf=function(f,d,p,m){if(f===void 0)return null;if(!Array.isArray(d.allOf))throw new r("allOf must be an array");var g=new e(f,d,p,m),y=this;return d.allOf.forEach(function(b,D){var v=y.validateSchema(f,b,p,m);if(!v.valid){var S=b.$id||b.id,C=S||b.title&&JSON.stringify(b.title)||b.$ref&&"<"+b.$ref+">"||"[subschema "+D+"]";g.addError({name:"allOf",argument:{id:C,length:v.errors.length,valid:v},message:"does not match allOf schema "+C+" with "+v.errors.length+" error[s]:"}),g.importErrors(v)}}),g},i.oneOf=function(f,d,p,m){if(f===void 0)return null;if(!Array.isArray(d.oneOf))throw new r("oneOf must be an array");var g=new e(f,d,p,m),y=new e(f,d,p,m),b=d.oneOf.filter(s.bind(this,f,p,m,function(v){y.importErrors(v)})).length,D=d.oneOf.map(function(v,S){var C=v.$id||v.id;return C||v.title&&JSON.stringify(v.title)||v.$ref&&"<"+v.$ref+">"||"[subschema "+S+"]"});return b!==1&&(p.nestedErrors&&g.importErrors(y),g.addError({name:"oneOf",argument:D,message:"is not exactly one from "+D.join(",")})),g},i.if=function(f,d,p,m){if(f===void 0)return null;if(!t.isSchema(d.if))throw new Error('Expected "if" keyword to be a schema');var g=s.call(this,f,p,m,null,d.if),y=new e(f,d,p,m),b;if(g){if(d.then===void 0)return;if(!t.isSchema(d.then))throw new Error('Expected "then" keyword to be a schema');b=this.validateSchema(f,d.then,p,m.makeChild(d.then)),y.importErrors(b)}else{if(d.else===void 0)return;if(!t.isSchema(d.else))throw new Error('Expected "else" keyword to be a schema');b=this.validateSchema(f,d.else,p,m.makeChild(d.else)),y.importErrors(b)}return y};function a(h,f){if(Object.hasOwnProperty.call(h,f))return h[f];if(f in h){for(;h=Object.getPrototypeOf(h);)if(Object.propertyIsEnumerable.call(h,f))return h[f]}}i.propertyNames=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),y=d.propertyNames!==void 0?d.propertyNames:{};if(!t.isSchema(y))throw new r('Expected "propertyNames" to be a schema (object or boolean)');for(var b in f)if(a(f,b)!==void 0){var D=this.validateSchema(b,y,p,m.makeChild(y));g.importErrors(D)}return g}},i.properties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),y=d.properties||{};for(var b in y){var D=y[b];if(D!==void 0){if(D===null)throw new r('Unexpected null, expected schema in "properties"');typeof p.preValidateProperty=="function"&&p.preValidateProperty(f,b,D,p,m);var v=a(f,b),S=this.validateSchema(v,D,p,m.makeChild(D,b));S.instance!==g.instance[b]&&(g.instance[b]=S.instance),g.importErrors(S)}}return g}};function l(h,f,d,p,m,g){if(this.types.object(h)&&!(f.properties&&f.properties[m]!==void 0))if(f.additionalProperties===!1)g.addError({name:"additionalProperties",argument:m,message:"is not allowed to have the additional property "+JSON.stringify(m)});else{var y=f.additionalProperties||{};typeof d.preValidateProperty=="function"&&d.preValidateProperty(h,m,y,d,p);var b=this.validateSchema(h[m],y,d,p.makeChild(y,m));b.instance!==g.instance[m]&&(g.instance[m]=b.instance),g.importErrors(b)}}i.patternProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),y=d.patternProperties||{};for(var b in f){var D=!0;for(var v in y){var S=y[v];if(S!==void 0){if(S===null)throw new r('Unexpected null, expected schema in "patternProperties"');try{var C=new RegExp(v,"u")}catch{C=new RegExp(v)}if(C.test(b)){D=!1,typeof p.preValidateProperty=="function"&&p.preValidateProperty(f,b,S,p,m);var x=this.validateSchema(f[b],S,p,m.makeChild(S,b));x.instance!==g.instance[b]&&(g.instance[b]=x.instance),g.importErrors(x)}}}D&&l.call(this,f,d,p,m,b,g)}return g}},i.additionalProperties=function(f,d,p,m){if(this.types.object(f)){if(d.patternProperties)return null;var g=new e(f,d,p,m);for(var y in f)l.call(this,f,d,p,m,y,g);return g}},i.minProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),y=Object.keys(f);return y.length>=d.minProperties||g.addError({name:"minProperties",argument:d.minProperties,message:"does not meet minimum property length of "+d.minProperties}),g}},i.maxProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),y=Object.keys(f);return y.length<=d.maxProperties||g.addError({name:"maxProperties",argument:d.maxProperties,message:"does not meet maximum property length of "+d.maxProperties}),g}},i.items=function(f,d,p,m){var g=this;if(this.types.array(f)&&d.items!==void 0){var y=new e(f,d,p,m);return f.every(function(b,D){if(Array.isArray(d.items))var v=d.items[D]===void 0?d.additionalItems:d.items[D];else var v=d.items;if(v===void 0)return!0;if(v===!1)return y.addError({name:"items",message:"additionalItems not permitted"}),!1;var S=g.validateSchema(b,v,p,m.makeChild(v,D));return S.instance!==y.instance[D]&&(y.instance[D]=S.instance),y.importErrors(S),!0}),y}},i.contains=function(f,d,p,m){var g=this;if(this.types.array(f)&&d.contains!==void 0){if(!t.isSchema(d.contains))throw new Error('Expected "contains" keyword to be a schema');var y=new e(f,d,p,m),b=f.some(function(D,v){var S=g.validateSchema(D,d.contains,p,m.makeChild(d.contains,v));return S.errors.length===0});return b===!1&&y.addError({name:"contains",argument:d.contains,message:"must contain an item matching given schema"}),y}},i.minimum=function(f,d,p,m){if(this.types.number(f)){var g=new e(f,d,p,m);return d.exclusiveMinimum&&d.exclusiveMinimum===!0?f>d.minimum||g.addError({name:"minimum",argument:d.minimum,message:"must be greater than "+d.minimum}):f>=d.minimum||g.addError({name:"minimum",argument:d.minimum,message:"must be greater than or equal to "+d.minimum}),g}},i.maximum=function(f,d,p,m){if(this.types.number(f)){var g=new e(f,d,p,m);return d.exclusiveMaximum&&d.exclusiveMaximum===!0?f<d.maximum||g.addError({name:"maximum",argument:d.maximum,message:"must be less than "+d.maximum}):f<=d.maximum||g.addError({name:"maximum",argument:d.maximum,message:"must be less than or equal to "+d.maximum}),g}},i.exclusiveMinimum=function(f,d,p,m){if(typeof d.exclusiveMinimum!="boolean"&&this.types.number(f)){var g=new e(f,d,p,m),y=f>d.exclusiveMinimum;return y||g.addError({name:"exclusiveMinimum",argument:d.exclusiveMinimum,message:"must be strictly greater than "+d.exclusiveMinimum}),g}},i.exclusiveMaximum=function(f,d,p,m){if(typeof d.exclusiveMaximum!="boolean"&&this.types.number(f)){var g=new e(f,d,p,m),y=f<d.exclusiveMaximum;return y||g.addError({name:"exclusiveMaximum",argument:d.exclusiveMaximum,message:"must be strictly less than "+d.exclusiveMaximum}),g}};var c=function(f,d,p,m,g,y){if(this.types.number(f)){var b=d[g];if(b==0)throw new r(g+" cannot be zero");var D=new e(f,d,p,m),v=t.getDecimalPlaces(f),S=t.getDecimalPlaces(b),C=Math.max(v,S),x=Math.pow(10,C);return Math.round(f*x)%Math.round(b*x)!==0&&D.addError({name:g,argument:b,message:y+JSON.stringify(b)}),D}};i.multipleOf=function(f,d,p,m){return c.call(this,f,d,p,m,"multipleOf","is not a multiple of (divisible by) ")},i.divisibleBy=function(f,d,p,m){return c.call(this,f,d,p,m,"divisibleBy","is not divisible by (multiple of) ")},i.required=function(f,d,p,m){var g=new e(f,d,p,m);return f===void 0&&d.required===!0?g.addError({name:"required",message:"is required"}):this.types.object(f)&&Array.isArray(d.required)&&d.required.forEach(function(y){a(f,y)===void 0&&g.addError({name:"required",argument:y,message:"requires property "+JSON.stringify(y)})}),g},i.pattern=function(f,d,p,m){if(this.types.string(f)){var g=new e(f,d,p,m),y=d.pattern;try{var b=new RegExp(y,"u")}catch{b=new RegExp(y)}return f.match(b)||g.addError({name:"pattern",argument:d.pattern,message:"does not match pattern "+JSON.stringify(d.pattern.toString())}),g}},i.format=function(f,d,p,m){if(f!==void 0){var g=new e(f,d,p,m);return!g.disableFormat&&!t.isFormat(f,d.format,this)&&g.addError({name:"format",argument:d.format,message:"does not conform to the "+JSON.stringify(d.format)+" format"}),g}},i.minLength=function(f,d,p,m){if(this.types.string(f)){var g=new e(f,d,p,m),y=f.match(/[\uDC00-\uDFFF]/g),b=f.length-(y?y.length:0);return b>=d.minLength||g.addError({name:"minLength",argument:d.minLength,message:"does not meet minimum length of "+d.minLength}),g}},i.maxLength=function(f,d,p,m){if(this.types.string(f)){var g=new e(f,d,p,m),y=f.match(/[\uDC00-\uDFFF]/g),b=f.length-(y?y.length:0);return b<=d.maxLength||g.addError({name:"maxLength",argument:d.maxLength,message:"does not meet maximum length of "+d.maxLength}),g}},i.minItems=function(f,d,p,m){if(this.types.array(f)){var g=new e(f,d,p,m);return f.length>=d.minItems||g.addError({name:"minItems",argument:d.minItems,message:"does not meet minimum length of "+d.minItems}),g}},i.maxItems=function(f,d,p,m){if(this.types.array(f)){var g=new e(f,d,p,m);return f.length<=d.maxItems||g.addError({name:"maxItems",argument:d.maxItems,message:"does not meet maximum length of "+d.maxItems}),g}};function u(h,f,d){var p,m=d.length;for(p=f+1,m;p<m;p++)if(t.deepCompareStrict(h,d[p]))return!1;return!0}return i.uniqueItems=function(f,d,p,m){if(d.uniqueItems===!0&&this.types.array(f)){var g=new e(f,d,p,m);return f.every(u)||g.addError({name:"uniqueItems",message:"contains duplicate item"}),g}},i.dependencies=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m);for(var y in d.dependencies)if(f[y]!==void 0){var b=d.dependencies[y],D=m.makeChild(b,y);if(typeof b=="string"&&(b=[b]),Array.isArray(b))b.forEach(function(S){f[S]===void 0&&g.addError({name:"dependencies",argument:D.propertyPath,message:"property "+S+" not found, required by "+D.propertyPath})});else{var v=this.validateSchema(f,b,p,D);g.instance!==v.instance&&(g.instance=v.instance),v&&v.errors.length&&(g.addError({name:"dependencies",argument:D.propertyPath,message:"does not meet dependency required by "+D.propertyPath}),g.importErrors(v))}}return g}},i.enum=function(f,d,p,m){if(f===void 0)return null;if(!Array.isArray(d.enum))throw new r("enum expects an array",d);var g=new e(f,d,p,m);return d.enum.some(t.deepCompareStrict.bind(null,f))||g.addError({name:"enum",argument:d.enum,message:"is not one of enum values: "+d.enum.map(String).join(",")}),g},i.const=function(f,d,p,m){if(f===void 0)return null;var g=new e(f,d,p,m);return t.deepCompareStrict(d.const,f)||g.addError({name:"const",argument:d.const,message:"does not exactly match expected constant: "+d.const}),g},i.not=i.disallow=function(f,d,p,m){var g=this;if(f===void 0)return null;var y=new e(f,d,p,m),b=d.not||d.disallow;return b?(Array.isArray(b)||(b=[b]),b.forEach(function(D){if(g.testType(f,d,p,m,D)){var v=D&&(D.$id||D.id),S=v||D;y.addError({name:"not",argument:S,message:"is of prohibited type "+S})}}),y):null},Ia=n,Ia}var vs={},vh;function Xa(){if(vh)return vs;vh=1;var t=_r();vs.SchemaScanResult=e;function e(r,n){this.id=r,this.ref=n}return vs.scan=function(n,i){function s(h,f){if(!f||typeof f!="object")return;if(f.$ref){let g=t.resolveUrl(h,f.$ref);u[g]=u[g]?u[g]+1:0;return}var d=f.$id||f.id;let p=t.resolveUrl(h,d);var m=d?p:h;if(m){if(m.indexOf("#")<0&&(m+="#"),c[m]){if(!t.deepCompareStrict(c[m],f))throw new Error("Schema <"+m+"> already exists with different definition");return c[m]}c[m]=f,m[m.length-1]=="#"&&(c[m.substring(0,m.length-1)]=f)}a(m+"/items",Array.isArray(f.items)?f.items:[f.items]),a(m+"/extends",Array.isArray(f.extends)?f.extends:[f.extends]),s(m+"/additionalItems",f.additionalItems),l(m+"/properties",f.properties),s(m+"/additionalProperties",f.additionalProperties),l(m+"/definitions",f.definitions),l(m+"/patternProperties",f.patternProperties),l(m+"/dependencies",f.dependencies),a(m+"/disallow",f.disallow),a(m+"/allOf",f.allOf),a(m+"/anyOf",f.anyOf),a(m+"/oneOf",f.oneOf),s(m+"/not",f.not)}function a(h,f){if(Array.isArray(f))for(var d=0;d<f.length;d++)s(h+"/"+d,f[d])}function l(h,f){if(!(!f||typeof f!="object"))for(var d in f)s(h+"/"+d,f[d])}var c={},u={};return s(n,i),new e(c,u)},vs}var Ra,Dh;function z1(){if(Dh)return Ra;Dh=1;var t=q1(),e=_r(),r=Xa().scan,n=e.ValidatorResult,i=e.ValidatorResultError,s=e.SchemaError,a=e.SchemaContext,l="/",c=function f(){this.customFormats=Object.create(f.prototype.customFormats),this.schemas={},this.unresolvedRefs=[],this.types=Object.create(h),this.attributes=Object.create(t.validators)};c.prototype.customFormats={},c.prototype.schemas=null,c.prototype.types=null,c.prototype.attributes=null,c.prototype.unresolvedRefs=null,c.prototype.addSchema=function(d,p){var m=this;if(!d)return null;var g=r(p||l,d),y=p||d.$id||d.id;for(var b in g.id)this.schemas[b]=g.id[b];for(var b in g.ref)this.unresolvedRefs.push(b);return this.unresolvedRefs=this.unresolvedRefs.filter(function(D){return typeof m.schemas[D]>"u"}),this.schemas[y]},c.prototype.addSubSchemaArray=function(d,p){if(Array.isArray(p))for(var m=0;m<p.length;m++)this.addSubSchema(d,p[m])},c.prototype.addSubSchemaObject=function(d,p){if(!(!p||typeof p!="object"))for(var m in p)this.addSubSchema(d,p[m])},c.prototype.setSchemas=function(d){this.schemas=d},c.prototype.getSchema=function(d){return this.schemas[d]},c.prototype.validate=function(d,p,m,g){if(typeof p!="boolean"&&typeof p!="object"||p===null)throw new s("Expected `schema` to be an object or boolean");m||(m={});var y=p.$id||p.id;let b=e.resolveUrl(m.base,y||"");if(!g){g=new a(p,m,[],b,Object.create(this.schemas)),g.schemas[b]||(g.schemas[b]=p);var D=r(b,p);for(var v in D.id){var S=D.id[v];g.schemas[v]=S}}if(m.required&&d===void 0){var C=new n(d,p,m,g);return C.addError("is required, but is undefined"),C}var C=this.validateSchema(d,p,m,g);if(C){if(m.throwAll&&C.errors.length)throw new i(C)}else throw new Error("Result undefined");return C};function u(f){var d=typeof f=="string"?f:f.$ref;return typeof d=="string"?d:!1}c.prototype.validateSchema=function(d,p,m,g){var y=new n(d,p,m,g);if(typeof p=="boolean")p===!0?p={}:p===!1&&(p={type:[]});else if(!p)throw new Error("schema is undefined");if(p.extends)if(Array.isArray(p.extends)){var b={schema:p,ctx:g};p.extends.forEach(this.schemaTraverser.bind(this,b)),p=b.schema,b.schema=null,b.ctx=null,b=null}else p=e.deepMerge(p,this.superResolve(p.extends,g));var D=u(p);if(D){var v=this.resolve(p,D,g),S=new a(v.subschema,m,g.path,v.switchSchema,g.schemas);return this.validateSchema(d,v.subschema,m,S)}var C=m&&m.skipAttributes||[];for(var x in p)if(!t.ignoreProperties[x]&&C.indexOf(x)<0){var _=null,B=this.attributes[x];if(B)_=B.call(this,d,p,m,g);else if(m.allowUnknownAttributes===!1)throw new s("Unsupported attribute: "+x,p);_&&y.importErrors(_)}if(typeof m.rewrite=="function"){var w=m.rewrite.call(this,d,p,m,g);y.instance=w}return y},c.prototype.schemaTraverser=function(d,p){d.schema=e.deepMerge(d.schema,this.superResolve(p,d.ctx))},c.prototype.superResolve=function(d,p){var m=u(d);return m?this.resolve(d,m,p).subschema:d},c.prototype.resolve=function(d,p,m){if(p=m.resolve(p),m.schemas[p])return{subschema:m.schemas[p],switchSchema:p};let y=new URL(p,"thismessage::/").hash;var b=y&&y.length&&p.substr(0,p.length-y.length);if(!b||!m.schemas[b])throw new s("no such schema <"+p+">",d);var D=e.objectGetPath(m.schemas[b],y.substr(1));if(D===void 0)throw new s("no such schema "+y+" located in <"+b+">",d);return{subschema:D,switchSchema:p}},c.prototype.testType=function(d,p,m,g,y){if(y!==void 0){if(y===null)throw new s('Unexpected null in "type" keyword');if(typeof this.types[y]=="function")return this.types[y].call(this,d);if(y&&typeof y=="object"){var b=this.validateSchema(d,y,m,g);return b===void 0||!(b&&b.errors.length)}return!0}};var h=c.prototype.types={};return h.string=function(d){return typeof d=="string"},h.number=function(d){return typeof d=="number"&&isFinite(d)},h.integer=function(d){return typeof d=="number"&&d%1===0},h.boolean=function(d){return typeof d=="boolean"},h.array=function(d){return Array.isArray(d)},h.null=function(d){return d===null},h.date=function(d){return d instanceof Date},h.any=function(d){return!0},h.object=function(d){return d&&typeof d=="object"&&!Array.isArray(d)&&!(d instanceof Date)},Ra=c,Ra}var wh;function V1(){if(wh)return tt;wh=1;var t=tt.Validator=z1();return tt.ValidatorResult=_r().ValidatorResult,tt.ValidatorResultError=_r().ValidatorResultError,tt.ValidationError=_r().ValidationError,tt.SchemaError=_r().SchemaError,tt.SchemaScanResult=Xa().SchemaScanResult,tt.scan=Xa().scan,tt.validate=function(e,r,n){var i=new t;return i.validate(e,r,n)},tt}var W1=V1(),Qs=o.object({name:o.string(),description:o.string()}),el=class{constructor(e,r,n){this.logger=e,this.signal=r,this.callId=n}status(e){this.logger.info(e)}warn(e){this.logger.warn(e)}},G1=Qs.extend({type:o.literal("function"),parametersSchema:Rr,checkParameters:o.function(),implementation:o.function()}),Z1=Qs.extend({type:o.literal("rawFunction"),parametersSchema:Rr,checkParameters:o.function(),implementation:o.function()}),K1=Qs.extend({type:o.literal("unimplementedRawFunction"),parametersJsonSchema:Rr,checkParameters:o.function(),implementation:o.function()}),H1=Qs.extend({type:o.literal("remoteTool"),pluginIdentifier:o.string(),parametersJsonSchema:Rr,checkParameters:o.function(),implementation:o.function()});o.discriminatedUnion("type",[G1,Z1,K1,H1]);function Y1(t,e){return e.map(r=>`${[t,...r.path].join(".")} ${r.message}`).join(`
227
+ `)}var tl=class extends Error{constructor(e){super(`Tool "${e}" is not implemented.`)}};function J1({name:t,description:e,pluginIdentifier:r,parametersJsonSchema:n,implementation:i}){return{name:t,description:e,type:"remoteTool",pluginIdentifier:r,parametersJsonSchema:n,checkParameters:s=>{let l=new W1.Validator().validate(s,n);if(l.errors.length>0)throw new Error(j`
228
228
  Failed to parse arguments for tool "${t}":
229
- ${H1("params",l.errors)}
230
- `)},implementation:i}}function J1(t){return{type:"function",function:{name:t.name,description:t.description,parameters:ds(t.parametersSchema)}}}function Q1(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parametersJsonSchema}}}function X1(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parametersJsonSchema}}}function ac(t){let e=t.type;switch(e){case"function":return J1(t);case"rawFunction":case"unimplementedRawFunction":return Q1(t);case"remoteTool":return X1(t);default:{let r=e;throw new Error(`Unhandled type: ${r}`)}}}var xr=class extends Error{constructor(e,r){super(e),this.rawContent=r}},zt=class{constructor(){this.unhandledEndpoints=new Set,this.existingEndpointNames=new Set,this.rpcEndpoints=new Map,this.channelEndpoints=new Map,this.signalEndpoints=new Map,this.writableSignalEndpoints=new Map}withContextType(){return this}assertEndpointNameNotExists(e){if(this.existingEndpointNames.has(e))throw new Error(`Endpoint with name ${e} already exists`)}addRpcEndpoint(e,{parameter:r,returns:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.rpcEndpoints.set(e,{name:e,parameter:r,returns:n,serialization:i,handler:null}),this}addChannelEndpoint(e,{creationParameter:r,toServerPacket:n,toClientPacket:i,serialization:s="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.channelEndpoints.set(e,{name:e,creationParameter:r,toServerPacket:n,toClientPacket:i,serialization:s,handler:null}),this}addSignalEndpoint(e,{creationParameter:r,signalData:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.signalEndpoints.set(e,{name:e,creationParameter:r,signalData:n,serialization:i,handler:null}),this}addWritableSignalEndpoint(e,{creationParameter:r,signalData:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.writableSignalEndpoints.set(e,{name:e,creationParameter:r,signalData:n,serialization:i,handler:null}),this}handleRpcEndpoint(e,r){let n=this.rpcEndpoints.get(e);if(n===void 0)throw new Error(`No Rpc endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Rpc endpoint with name ${e} already has a handler`);n.handler=r,this.unhandledEndpoints.delete(e)}handleChannelEndpoint(e,r){let n=this.channelEndpoints.get(e);if(n===void 0)throw new Error(`No channel endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Channel endpoint with name ${e} already has a handler`);n.handler=r,this.unhandledEndpoints.delete(e)}handleSignalEndpoint(e,r){let n=this.signalEndpoints.get(e);if(n===void 0)throw new Error(`No signal endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Signal endpoint with name ${e} already has a handler`);n.handler=r,this.unhandledEndpoints.delete(e)}handleWritableSignalEndpoint(e,r){let n=this.writableSignalEndpoints.get(e);if(n===void 0)throw new Error(`No writable signal endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Writable signal endpoint with name ${e} already has a handler`);n.handler=r,this.unhandledEndpoints.delete(e)}assertAllEndpointsHandled(){if(this.unhandledEndpoints.size>0)throw new Error(`The following endpoints were not handled: ${Array.from(this.unhandledEndpoints).join(", ")}`)}getRpcEndpoint(e){return this.rpcEndpoints.get(e)}getAllRpcEndpoints(){return[...this.rpcEndpoints.values()]}getChannelEndpoint(e){return this.channelEndpoints.get(e)}getAllChannelEndpoints(){return[...this.channelEndpoints.values()]}getSignalEndpoint(e){return this.signalEndpoints.get(e)}getAllSignalEndpoints(){return[...this.signalEndpoints.values()]}getWritableSignalEndpoint(e){return this.writableSignalEndpoints.get(e)}getAllWritableSignalEndpoints(){return[...this.writableSignalEndpoints.values()]}},Nt;(function(t){t.Connected="CONNECTED",t.Errored="ERRORED",t.Closed="CLOSED"})(Nt||(Nt={}));var Ds=new Y("Channel"),tl=class t{constructor(e){this.innerSend=e,this.nextAckId=0,this.waitingForAck=new Map,this.receivedACK=r=>{if(this.connectionStatus.get()!==Nt.Connected){Ds.warn("Received ACK while in status",this.connectionStatus.get());return}let n=this.waitingForAck.get(r);if(n===void 0){Ds.warn("Received ACK for a message that is no longer waiting for ACK, ackId =",r);return}n.resolve(),this.waitingForAck.delete(r)},this.receivedMessage=r=>{if(this.connectionStatus.get()!==Nt.Connected){Ds.warn("Received message while in status",this.connectionStatus.get());return}this.emitOnMessage(r)},this.errored=r=>{if(this.connectionStatus.get()!==Nt.Connected){Ds.warn("Received error while in status",this.connectionStatus.get());return}this.rejectAllWaitingForAck(r),this.setConnectionStatus(Nt.Errored),this.emitOnError(r)},this.closed=()=>{this.rejectAllWaitingForAck(new Error("Channel closed")),this.setConnectionStatus(Nt.Closed),this.emitOnClose()},[this.onMessage,this.emitOnMessage]=Ct.create(),[this.onError,this.emitOnError]=Ct.create(),[this.onClose,this.emitOnClose]=Ct.create(),[this.connectionStatus,this.setConnectionStatus]=ri.create(Nt.Connected)}rejectAllWaitingForAck(e){let r=Array.from(this.waitingForAck.values()).map(({reject:n})=>n);this.waitingForAck.clear();for(let n of r)n(e)}static create(e){let r=new t(e);return{channel:r,receivedAck:r.receivedACK,receivedMessage:r.receivedMessage,errored:r.errored,closed:r.closed}}send(e){this.innerSend(e)}sendAndWaitForACK(e){let{promise:r,resolve:n,reject:i}=re(),s=this.nextAckId;return this.nextAckId++,this.waitingForAck.set(s,{resolve:n,reject:i}),this.innerSend(e,s),r}},eS=(function(){function t(){this.keyToValue=new Map,this.valueToKey=new Map}return t.prototype.set=function(e,r){this.keyToValue.set(e,r),this.valueToKey.set(r,e)},t.prototype.getByKey=function(e){return this.keyToValue.get(e)},t.prototype.getByValue=function(e){return this.valueToKey.get(e)},t.prototype.clear=function(){this.keyToValue.clear(),this.valueToKey.clear()},t})(),Mp=(function(){function t(e){this.generateIdentifier=e,this.kv=new eS}return t.prototype.register=function(e,r){this.kv.getByValue(e)||(r||(r=this.generateIdentifier(e)),this.kv.set(r,e))},t.prototype.clear=function(){this.kv.clear()},t.prototype.getIdentifier=function(e){return this.kv.getByValue(e)},t.prototype.getValue=function(e){return this.kv.getByKey(e)},t})(),tS=globalThis&&globalThis.__extends||(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),rS=(function(t){tS(e,t);function e(){var r=t.call(this,function(n){return n.name})||this;return r.classToAllowedProps=new Map,r}return e.prototype.register=function(r,n){typeof n=="object"?(n.allowProps&&this.classToAllowedProps.set(r,n.allowProps),t.prototype.register.call(this,r,n.identifier)):t.prototype.register.call(this,r,n)},e.prototype.getAllowedProps=function(r){return this.classToAllowedProps.get(r)},e})(Mp),nS=globalThis&&globalThis.__read||function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s};function iS(t){if("values"in Object)return Object.values(t);var e=[];for(var r in t)t.hasOwnProperty(r)&&e.push(t[r]);return e}function sS(t,e){var r=iS(t);if("find"in r)return r.find(e);for(var n=r,i=0;i<n.length;i++){var s=n[i];if(e(s))return s}}function bn(t,e){Object.entries(t).forEach(function(r){var n=nS(r,2),i=n[0],s=n[1];return e(s,i)})}function _s(t,e){return t.indexOf(e)!==-1}function wh(t,e){for(var r=0;r<t.length;r++){var n=t[r];if(e(n))return n}}var oS=(function(){function t(){this.transfomers={}}return t.prototype.register=function(e){this.transfomers[e.name]=e},t.prototype.findApplicable=function(e){return sS(this.transfomers,function(r){return r.isApplicable(e)})},t.prototype.findByName=function(e){return this.transfomers[e]},t})(),aS=function(t){return Object.prototype.toString.call(t).slice(8,-1)},jp=function(t){return typeof t>"u"},lS=function(t){return t===null},li=function(t){return typeof t!="object"||t===null||t===Object.prototype?!1:Object.getPrototypeOf(t)===null?!0:Object.getPrototypeOf(t)===Object.prototype},rl=function(t){return li(t)&&Object.keys(t).length===0},Vt=function(t){return Array.isArray(t)},cS=function(t){return typeof t=="string"},uS=function(t){return typeof t=="number"&&!isNaN(t)},dS=function(t){return typeof t=="boolean"},fS=function(t){return t instanceof RegExp},ci=function(t){return t instanceof Map},ui=function(t){return t instanceof Set},Bp=function(t){return aS(t)==="Symbol"},hS=function(t){return t instanceof Date&&!isNaN(t.valueOf())},pS=function(t){return t instanceof Error},Sh=function(t){return typeof t=="number"&&isNaN(t)},mS=function(t){return dS(t)||lS(t)||jp(t)||uS(t)||cS(t)||Bp(t)},gS=function(t){return typeof t=="bigint"},yS=function(t){return t===1/0||t===-1/0},bS=function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},vS=function(t){return t instanceof URL},Lp=function(t){return t.replace(/\./g,"\\.")},Ra=function(t){return t.map(String).map(Lp).join(".")},Kn=function(t){for(var e=[],r="",n=0;n<t.length;n++){var i=t.charAt(n),s=i==="\\"&&t.charAt(n+1)===".";if(s){r+=".",n++;continue}var a=i===".";if(a){e.push(r),r="";continue}r+=i}var l=r;return e.push(l),e},nl=globalThis&&globalThis.__assign||function(){return nl=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},nl.apply(this,arguments)},il=globalThis&&globalThis.__read||function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},sl=globalThis&&globalThis.__spreadArray||function(t,e){for(var r=0,n=e.length,i=t.length;r<n;r++,i++)t[i]=e[r];return t};function et(t,e,r,n){return{isApplicable:t,annotation:e,transform:r,untransform:n}}var Np=[et(jp,"undefined",function(){return null},function(){}),et(gS,"bigint",function(t){return t.toString()},function(t){return typeof BigInt<"u"?BigInt(t):(console.error("Please add a BigInt polyfill."),t)}),et(hS,"Date",function(t){return t.toISOString()},function(t){return new Date(t)}),et(pS,"Error",function(t,e){var r={name:t.name,message:t.message};return e.allowedErrorProps.forEach(function(n){r[n]=t[n]}),r},function(t,e){var r=new Error(t.message);return r.name=t.name,r.stack=t.stack,e.allowedErrorProps.forEach(function(n){r[n]=t[n]}),r}),et(fS,"regexp",function(t){return""+t},function(t){var e=t.slice(1,t.lastIndexOf("/")),r=t.slice(t.lastIndexOf("/")+1);return new RegExp(e,r)}),et(ui,"set",function(t){return sl([],il(t.values()))},function(t){return new Set(t)}),et(ci,"map",function(t){return sl([],il(t.entries()))},function(t){return new Map(t)}),et(function(t){return Sh(t)||yS(t)},"number",function(t){return Sh(t)?"NaN":t>0?"Infinity":"-Infinity"},Number),et(function(t){return t===0&&1/t===-1/0},"number",function(){return"-0"},Number),et(vS,"URL",function(t){return t.toString()},function(t){return new URL(t)})];function Xs(t,e,r,n){return{isApplicable:t,annotation:e,transform:r,untransform:n}}var $p=Xs(function(t,e){if(Bp(t)){var r=!!e.symbolRegistry.getIdentifier(t);return r}return!1},function(t,e){var r=e.symbolRegistry.getIdentifier(t);return["symbol",r]},function(t){return t.description},function(t,e,r){var n=r.symbolRegistry.getValue(e[1]);if(!n)throw new Error("Trying to deserialize unknown symbol");return n}),DS=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce(function(t,e){return t[e.name]=e,t},{}),Up=Xs(bS,function(t){return["typed-array",t.constructor.name]},function(t){return sl([],il(t))},function(t,e){var r=DS[e[1]];if(!r)throw new Error("Trying to deserialize unknown typed array");return new r(t)});function qp(t,e){if(t?.constructor){var r=!!e.classRegistry.getIdentifier(t.constructor);return r}return!1}var zp=Xs(qp,function(t,e){var r=e.classRegistry.getIdentifier(t.constructor);return["class",r]},function(t,e){var r=e.classRegistry.getAllowedProps(t.constructor);if(!r)return nl({},t);var n={};return r.forEach(function(i){n[i]=t[i]}),n},function(t,e,r){var n=r.classRegistry.getValue(e[1]);if(!n)throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");return Object.assign(Object.create(n.prototype),t)}),Vp=Xs(function(t,e){return!!e.customTransformerRegistry.findApplicable(t)},function(t,e){var r=e.customTransformerRegistry.findApplicable(t);return["custom",r.name]},function(t,e){var r=e.customTransformerRegistry.findApplicable(t);return r.serialize(t)},function(t,e,r){var n=r.customTransformerRegistry.findByName(e[1]);if(!n)throw new Error("Trying to deserialize unknown custom value");return n.deserialize(t)}),wS=[zp,$p,Vp,Up],Ch=function(t,e){var r=wh(wS,function(i){return i.isApplicable(t,e)});if(r)return{value:r.transform(t,e),type:r.annotation(t,e)};var n=wh(Np,function(i){return i.isApplicable(t,e)});if(n)return{value:n.transform(t,e),type:n.annotation}},Wp={};Np.forEach(function(t){Wp[t.annotation]=t});var SS=function(t,e,r){if(Vt(e))switch(e[0]){case"symbol":return $p.untransform(t,e,r);case"class":return zp.untransform(t,e,r);case"custom":return Vp.untransform(t,e,r);case"typed-array":return Up.untransform(t,e,r);default:throw new Error("Unknown transformation: "+e)}else{var n=Wp[e];if(!n)throw new Error("Unknown transformation: "+e);return n.untransform(t,r)}},mn=function(t,e){for(var r=t.keys();e>0;)r.next(),e--;return r.next().value};function Gp(t){if(_s(t,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(_s(t,"prototype"))throw new Error("prototype is not allowed as a property");if(_s(t,"constructor"))throw new Error("constructor is not allowed as a property")}var CS=function(t,e){Gp(e);for(var r=0;r<e.length;r++){var n=e[r];if(ui(t))t=mn(t,+n);else if(ci(t)){var i=+n,s=+e[++r]==0?"key":"value",a=mn(t,i);switch(s){case"key":t=a;break;case"value":t=t.get(a);break}}else t=t[n]}return t},ol=function(t,e,r){if(Gp(e),e.length===0)return r(t);for(var n=t,i=0;i<e.length-1;i++){var s=e[i];if(Vt(n)){var a=+s;n=n[a]}else if(li(n))n=n[s];else if(ui(n)){var l=+s;n=mn(n,l)}else if(ci(n)){var c=i===e.length-2;if(c)break;var l=+s,u=+e[++i]==0?"key":"value",h=mn(n,l);switch(u){case"key":n=h;break;case"value":n=n.get(h);break}}}var f=e[e.length-1];if(Vt(n)?n[+f]=r(n[+f]):li(n)&&(n[f]=r(n[f])),ui(n)){var d=mn(n,+f),p=r(d);d!==p&&(n.delete(d),n.add(p))}if(ci(n)){var l=+e[e.length-2],m=mn(n,l),u=+f==0?"key":"value";switch(u){case"key":{var g=r(m);n.set(g,n.get(m)),g!==m&&n.delete(m);break}case"value":{n.set(m,r(n.get(m)));break}}}return t},St=globalThis&&globalThis.__read||function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},$t=globalThis&&globalThis.__spreadArray||function(t,e){for(var r=0,n=e.length,i=t.length;r<n;r++,i++)t[i]=e[r];return t};function al(t,e,r){if(r===void 0&&(r=[]),!!t){if(!Vt(t)){bn(t,function(a,l){return al(a,e,$t($t([],St(r)),St(Kn(l))))});return}var n=St(t,2),i=n[0],s=n[1];s&&bn(s,function(a,l){al(a,e,$t($t([],St(r)),St(Kn(l))))}),e(i,r)}}function ES(t,e,r){return al(e,function(n,i){t=ol(t,i,function(s){return SS(s,n,r)})}),t}function _S(t,e){function r(a,l){var c=CS(t,Kn(l));a.map(Kn).forEach(function(u){t=ol(t,u,function(){return c})})}if(Vt(e)){var n=St(e,2),i=n[0],s=n[1];i.forEach(function(a){t=ol(t,Kn(a),function(){return t})}),s&&bn(s,r)}else bn(e,r);return t}var xS=function(t,e){return li(t)||Vt(t)||ci(t)||ui(t)||qp(t,e)};function kS(t,e,r){var n=r.get(t);n?n.push(e):r.set(t,[e])}function FS(t,e){var r={},n=void 0;return t.forEach(function(i){if(!(i.length<=1)){e||(i=i.map(function(c){return c.map(String)}).sort(function(c,u){return c.length-u.length}));var s=St(i),a=s[0],l=s.slice(1);a.length===0?n=l.map(Ra):r[Ra(a)]=l.map(Ra)}}),n?rl(r)?[n]:[n,r]:rl(r)?void 0:r}var Zp=function(t,e,r,n,i,s,a){var l;i===void 0&&(i=[]),s===void 0&&(s=[]),a===void 0&&(a=new Map);var c=mS(t);if(!c){kS(t,i,e);var u=a.get(t);if(u)return n?{transformedValue:null}:u}if(!xS(t,r)){var h=Ch(t,r),f=h?{transformedValue:h.value,annotations:[h.type]}:{transformedValue:t};return c||a.set(t,f),f}if(_s(s,t))return{transformedValue:null};var d=Ch(t,r),p=(l=d?.value)!==null&&l!==void 0?l:t,m=Vt(p)?[]:{},g={};bn(p,function(b,D){var v=Zp(b,e,r,n,$t($t([],St(i)),[D]),$t($t([],St(s)),[t]),a);m[D]=v.transformedValue,Vt(v.annotations)?g[D]=v.annotations:li(v.annotations)&&bn(v.annotations,function(S,C){g[Lp(D)+"."+C]=S})});var y=rl(g)?{transformedValue:m,annotations:d?[d.type]:void 0}:{transformedValue:m,annotations:d?[d.type,g]:g};return c||a.set(t,y),y};function Kp(t){return Object.prototype.toString.call(t).slice(8,-1)}function Eh(t){return Kp(t)==="Array"}function PS(t){if(Kp(t)!=="Object")return!1;let e=Object.getPrototypeOf(t);return!!e&&e.constructor===Object&&e===Object.prototype}function TS(t,e,r,n,i){let s={}.propertyIsEnumerable.call(n,e)?"enumerable":"nonenumerable";s==="enumerable"&&(t[e]=r),i&&s==="nonenumerable"&&Object.defineProperty(t,e,{value:r,enumerable:!1,writable:!0,configurable:!0})}function ll(t,e={}){if(Eh(t))return t.map(i=>ll(i,e));if(!PS(t))return t;let r=Object.getOwnPropertyNames(t),n=Object.getOwnPropertySymbols(t);return[...r,...n].reduce((i,s)=>{if(Eh(e.props)&&!e.props.includes(s))return i;let a=t[s],l=ll(a,e);return TS(i,s,l,t,e.nonenumerable),i},{})}var Cr=globalThis&&globalThis.__assign||function(){return Cr=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},Cr.apply(this,arguments)},AS=globalThis&&globalThis.__read||function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},OS=globalThis&&globalThis.__spreadArray||function(t,e){for(var r=0,n=e.length,i=t.length;r<n;r++,i++)t[i]=e[r];return t},Hp=(function(){function t(e){var r=e===void 0?{}:e,n=r.dedupe,i=n===void 0?!1:n;this.classRegistry=new rS,this.symbolRegistry=new Mp(function(s){var a;return(a=s.description)!==null&&a!==void 0?a:""}),this.customTransformerRegistry=new oS,this.allowedErrorProps=[],this.dedupe=i}return t.prototype.serialize=function(e){var r=new Map,n=Zp(e,r,this,this.dedupe),i={json:n.transformedValue};n.annotations&&(i.meta=Cr(Cr({},i.meta),{values:n.annotations}));var s=FS(r,this.dedupe);return s&&(i.meta=Cr(Cr({},i.meta),{referentialEqualities:s})),i},t.prototype.deserialize=function(e){var r=e.json,n=e.meta,i=ll(r);return n?.values&&(i=ES(i,n.values,this)),n?.referentialEqualities&&(i=_S(i,n.referentialEqualities)),i},t.prototype.stringify=function(e){return JSON.stringify(this.serialize(e))},t.prototype.parse=function(e){return this.deserialize(JSON.parse(e))},t.prototype.registerClass=function(e,r){this.classRegistry.register(e,r)},t.prototype.registerSymbol=function(e,r){this.symbolRegistry.register(e,r)},t.prototype.registerCustom=function(e,r){this.customTransformerRegistry.register(Cr({name:r},e))},t.prototype.allowErrorProps=function(){for(var e,r=[],n=0;n<arguments.length;n++)r[n]=arguments[n];(e=this.allowedErrorProps).push.apply(e,OS([],AS(r)))},t.defaultInstance=new t,t.serialize=t.defaultInstance.serialize.bind(t.defaultInstance),t.deserialize=t.defaultInstance.deserialize.bind(t.defaultInstance),t.stringify=t.defaultInstance.stringify.bind(t.defaultInstance),t.parse=t.defaultInstance.parse.bind(t.defaultInstance),t.registerClass=t.defaultInstance.registerClass.bind(t.defaultInstance),t.registerSymbol=t.defaultInstance.registerSymbol.bind(t.defaultInstance),t.registerCustom=t.defaultInstance.registerCustom.bind(t.defaultInstance),t.allowErrorProps=t.defaultInstance.allowErrorProps.bind(t.defaultInstance),t})(),IS=Hp.serialize,RS=Hp.deserialize;function fn(t,e){switch(t){case"raw":return e;case"superjson":return IS(e)}}function ws(t,e){switch(t){case"raw":return e;case"superjson":return RS(e)}}var rt=o.any(),MS=o.discriminatedUnion("type",[o.object({type:o.literal("communicationWarning"),warning:o.string()}),o.object({type:o.literal("keepAlive")}),o.object({type:o.literal("channelCreate"),endpoint:o.string(),channelId:o.number().int(),creationParameter:rt}),o.object({type:o.literal("channelSend"),channelId:o.number().int(),message:rt,ackId:o.number().int().optional()}),o.object({type:o.literal("channelAck"),channelId:o.number().int(),ackId:o.number().int()}),o.object({type:o.literal("rpcCall"),endpoint:o.string(),callId:o.number().int(),parameter:rt}),o.object({type:o.literal("signalSubscribe"),creationParameter:rt,endpoint:o.string(),subscribeId:o.number().int()}),o.object({type:o.literal("signalUnsubscribe"),subscribeId:o.number().int()}),o.object({type:o.literal("writableSignalSubscribe"),creationParameter:rt,endpoint:o.string(),subscribeId:o.number().int()}),o.object({type:o.literal("writableSignalUnsubscribe"),subscribeId:o.number().int()}),o.object({type:o.literal("writableSignalUpdate"),subscribeId:o.number().int(),patches:o.array(rt),tags:o.array(o.string())})]),jS=o.discriminatedUnion("type",[o.object({type:o.literal("communicationWarning"),warning:o.string()}),o.object({type:o.literal("keepAliveAck")}),o.object({type:o.literal("channelSend"),channelId:o.number().int(),message:rt,ackId:o.number().int().optional()}),o.object({type:o.literal("channelAck"),channelId:o.number().int(),ackId:o.number().int()}),o.object({type:o.literal("channelClose"),channelId:o.number().int()}),o.object({type:o.literal("channelError"),channelId:o.number().int(),error:Oe}),o.object({type:o.literal("rpcResult"),callId:o.number().int(),result:rt}),o.object({type:o.literal("rpcError"),callId:o.number().int(),error:Oe}),o.object({type:o.literal("signalUpdate"),subscribeId:o.number().int(),patches:o.array(rt),tags:o.array(o.string())}),o.object({type:o.literal("signalError"),subscribeId:o.number().int(),error:Oe}),o.object({type:o.literal("writableSignalUpdate"),subscribeId:o.number().int(),patches:o.array(rt),tags:o.array(o.string())}),o.object({type:o.literal("writableSignalError"),subscribeId:o.number().int(),error:Oe})]),cl=class{constructor(){this.disposed=!1}async[Symbol.asyncDispose](){if(this.disposed)throw new Error("Cannot dispose twice");this.disposed=!0}},Bs=class extends cl{parseIncomingMessage(e){return jS.parse(e)}send(e){let r=MS.parse(e);this.sendViaTransport(r)}onHavingOneOrMoreOpenCommunication(){}onHavingNoOpenCommunication(){}},BS=o.discriminatedUnion("success",[o.object({success:o.literal(!0)}),o.object({success:o.literal(!1),error:o.string()})]),Fe;(function(t){t.Disconnected="DISCONNECTED",t.Connecting="CONNECTING",t.Connected="CONNECTED"})(Fe||(Fe={}));var ul=class t extends Bs{constructor(e,r,n,{abortSignal:i,parentLogger:s}={}){super(),this.url=e,this.receivedMessage=r,this.errored=n,this.ws=null,this.queuedMessages=[],this.status=Fe.Disconnected,this.resolvedUrl=null,this.shouldRef=!1,this.resolveDisposed=null,this.abortSignal=i,this.logger=new Y("WsClientTransport",s)}static createWsClientTransportFactory(e,{abortSignal:r}={}){return(n,i,s)=>new t(e,n,i,{abortSignal:r,parentLogger:s})}connect(){if(this.status!==Fe.Disconnected){this.logger.warn("connect() called while not disconnected");return}if(this.disposed)throw new Error(j`
229
+ ${Y1("params",l.errors)}
230
+ `)},implementation:i}}function Q1(t){return{type:"function",function:{name:t.name,description:t.description,parameters:ds(t.parametersSchema)}}}function X1(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parametersJsonSchema}}}function eS(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parametersJsonSchema}}}function lc(t){let e=t.type;switch(e){case"function":return Q1(t);case"rawFunction":case"unimplementedRawFunction":return X1(t);case"remoteTool":return eS(t);default:{let r=e;throw new Error(`Unhandled type: ${r}`)}}}var xr=class extends Error{constructor(e,r){super(e),this.rawContent=r}},zt=class{constructor(){this.unhandledEndpoints=new Set,this.existingEndpointNames=new Set,this.rpcEndpoints=new Map,this.channelEndpoints=new Map,this.signalEndpoints=new Map,this.writableSignalEndpoints=new Map}withContextType(){return this}assertEndpointNameNotExists(e){if(this.existingEndpointNames.has(e))throw new Error(`Endpoint with name ${e} already exists`)}addRpcEndpoint(e,{parameter:r,returns:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.rpcEndpoints.set(e,{name:e,parameter:r,returns:n,serialization:i,handler:null}),this}addChannelEndpoint(e,{creationParameter:r,toServerPacket:n,toClientPacket:i,serialization:s="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.channelEndpoints.set(e,{name:e,creationParameter:r,toServerPacket:n,toClientPacket:i,serialization:s,handler:null}),this}addSignalEndpoint(e,{creationParameter:r,signalData:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.signalEndpoints.set(e,{name:e,creationParameter:r,signalData:n,serialization:i,handler:null}),this}addWritableSignalEndpoint(e,{creationParameter:r,signalData:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.writableSignalEndpoints.set(e,{name:e,creationParameter:r,signalData:n,serialization:i,handler:null}),this}handleRpcEndpoint(e,r){let n=this.rpcEndpoints.get(e);if(n===void 0)throw new Error(`No Rpc endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Rpc endpoint with name ${e} already has a handler`);n.handler=r,this.unhandledEndpoints.delete(e)}handleChannelEndpoint(e,r){let n=this.channelEndpoints.get(e);if(n===void 0)throw new Error(`No channel endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Channel endpoint with name ${e} already has a handler`);n.handler=r,this.unhandledEndpoints.delete(e)}handleSignalEndpoint(e,r){let n=this.signalEndpoints.get(e);if(n===void 0)throw new Error(`No signal endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Signal endpoint with name ${e} already has a handler`);n.handler=r,this.unhandledEndpoints.delete(e)}handleWritableSignalEndpoint(e,r){let n=this.writableSignalEndpoints.get(e);if(n===void 0)throw new Error(`No writable signal endpoint with name ${e}`);if(n.handler!==null)throw new Error(`Writable signal endpoint with name ${e} already has a handler`);n.handler=r,this.unhandledEndpoints.delete(e)}assertAllEndpointsHandled(){if(this.unhandledEndpoints.size>0)throw new Error(`The following endpoints were not handled: ${Array.from(this.unhandledEndpoints).join(", ")}`)}getRpcEndpoint(e){return this.rpcEndpoints.get(e)}getAllRpcEndpoints(){return[...this.rpcEndpoints.values()]}getChannelEndpoint(e){return this.channelEndpoints.get(e)}getAllChannelEndpoints(){return[...this.channelEndpoints.values()]}getSignalEndpoint(e){return this.signalEndpoints.get(e)}getAllSignalEndpoints(){return[...this.signalEndpoints.values()]}getWritableSignalEndpoint(e){return this.writableSignalEndpoints.get(e)}getAllWritableSignalEndpoints(){return[...this.writableSignalEndpoints.values()]}},Nt;(function(t){t.Connected="CONNECTED",t.Errored="ERRORED",t.Closed="CLOSED"})(Nt||(Nt={}));var Ds=new Y("Channel"),rl=class t{constructor(e){this.innerSend=e,this.nextAckId=0,this.waitingForAck=new Map,this.receivedACK=r=>{if(this.connectionStatus.get()!==Nt.Connected){Ds.warn("Received ACK while in status",this.connectionStatus.get());return}let n=this.waitingForAck.get(r);if(n===void 0){Ds.warn("Received ACK for a message that is no longer waiting for ACK, ackId =",r);return}n.resolve(),this.waitingForAck.delete(r)},this.receivedMessage=r=>{if(this.connectionStatus.get()!==Nt.Connected){Ds.warn("Received message while in status",this.connectionStatus.get());return}this.emitOnMessage(r)},this.errored=r=>{if(this.connectionStatus.get()!==Nt.Connected){Ds.warn("Received error while in status",this.connectionStatus.get());return}this.rejectAllWaitingForAck(r),this.setConnectionStatus(Nt.Errored),this.emitOnError(r)},this.closed=()=>{this.rejectAllWaitingForAck(new Error("Channel closed")),this.setConnectionStatus(Nt.Closed),this.emitOnClose()},[this.onMessage,this.emitOnMessage]=Et.create(),[this.onError,this.emitOnError]=Et.create(),[this.onClose,this.emitOnClose]=Et.create(),[this.connectionStatus,this.setConnectionStatus]=ri.create(Nt.Connected)}rejectAllWaitingForAck(e){let r=Array.from(this.waitingForAck.values()).map(({reject:n})=>n);this.waitingForAck.clear();for(let n of r)n(e)}static create(e){let r=new t(e);return{channel:r,receivedAck:r.receivedACK,receivedMessage:r.receivedMessage,errored:r.errored,closed:r.closed}}send(e){this.innerSend(e)}sendAndWaitForACK(e){let{promise:r,resolve:n,reject:i}=re(),s=this.nextAckId;return this.nextAckId++,this.waitingForAck.set(s,{resolve:n,reject:i}),this.innerSend(e,s),r}},tS=(function(){function t(){this.keyToValue=new Map,this.valueToKey=new Map}return t.prototype.set=function(e,r){this.keyToValue.set(e,r),this.valueToKey.set(r,e)},t.prototype.getByKey=function(e){return this.keyToValue.get(e)},t.prototype.getByValue=function(e){return this.valueToKey.get(e)},t.prototype.clear=function(){this.keyToValue.clear(),this.valueToKey.clear()},t})(),jp=(function(){function t(e){this.generateIdentifier=e,this.kv=new tS}return t.prototype.register=function(e,r){this.kv.getByValue(e)||(r||(r=this.generateIdentifier(e)),this.kv.set(r,e))},t.prototype.clear=function(){this.kv.clear()},t.prototype.getIdentifier=function(e){return this.kv.getByValue(e)},t.prototype.getValue=function(e){return this.kv.getByKey(e)},t})(),rS=globalThis&&globalThis.__extends||(function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),nS=(function(t){rS(e,t);function e(){var r=t.call(this,function(n){return n.name})||this;return r.classToAllowedProps=new Map,r}return e.prototype.register=function(r,n){typeof n=="object"?(n.allowProps&&this.classToAllowedProps.set(r,n.allowProps),t.prototype.register.call(this,r,n.identifier)):t.prototype.register.call(this,r,n)},e.prototype.getAllowedProps=function(r){return this.classToAllowedProps.get(r)},e})(jp),iS=globalThis&&globalThis.__read||function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s};function sS(t){if("values"in Object)return Object.values(t);var e=[];for(var r in t)t.hasOwnProperty(r)&&e.push(t[r]);return e}function oS(t,e){var r=sS(t);if("find"in r)return r.find(e);for(var n=r,i=0;i<n.length;i++){var s=n[i];if(e(s))return s}}function bn(t,e){Object.entries(t).forEach(function(r){var n=iS(r,2),i=n[0],s=n[1];return e(s,i)})}function _s(t,e){return t.indexOf(e)!==-1}function Sh(t,e){for(var r=0;r<t.length;r++){var n=t[r];if(e(n))return n}}var aS=(function(){function t(){this.transfomers={}}return t.prototype.register=function(e){this.transfomers[e.name]=e},t.prototype.findApplicable=function(e){return oS(this.transfomers,function(r){return r.isApplicable(e)})},t.prototype.findByName=function(e){return this.transfomers[e]},t})(),lS=function(t){return Object.prototype.toString.call(t).slice(8,-1)},Bp=function(t){return typeof t>"u"},cS=function(t){return t===null},li=function(t){return typeof t!="object"||t===null||t===Object.prototype?!1:Object.getPrototypeOf(t)===null?!0:Object.getPrototypeOf(t)===Object.prototype},nl=function(t){return li(t)&&Object.keys(t).length===0},Vt=function(t){return Array.isArray(t)},uS=function(t){return typeof t=="string"},dS=function(t){return typeof t=="number"&&!isNaN(t)},fS=function(t){return typeof t=="boolean"},hS=function(t){return t instanceof RegExp},ci=function(t){return t instanceof Map},ui=function(t){return t instanceof Set},Lp=function(t){return lS(t)==="Symbol"},pS=function(t){return t instanceof Date&&!isNaN(t.valueOf())},mS=function(t){return t instanceof Error},Ch=function(t){return typeof t=="number"&&isNaN(t)},gS=function(t){return fS(t)||cS(t)||Bp(t)||dS(t)||uS(t)||Lp(t)},yS=function(t){return typeof t=="bigint"},bS=function(t){return t===1/0||t===-1/0},vS=function(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)},DS=function(t){return t instanceof URL},Np=function(t){return t.replace(/\./g,"\\.")},Ma=function(t){return t.map(String).map(Np).join(".")},Kn=function(t){for(var e=[],r="",n=0;n<t.length;n++){var i=t.charAt(n),s=i==="\\"&&t.charAt(n+1)===".";if(s){r+=".",n++;continue}var a=i===".";if(a){e.push(r),r="";continue}r+=i}var l=r;return e.push(l),e},il=globalThis&&globalThis.__assign||function(){return il=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},il.apply(this,arguments)},sl=globalThis&&globalThis.__read||function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},ol=globalThis&&globalThis.__spreadArray||function(t,e){for(var r=0,n=e.length,i=t.length;r<n;r++,i++)t[i]=e[r];return t};function rt(t,e,r,n){return{isApplicable:t,annotation:e,transform:r,untransform:n}}var $p=[rt(Bp,"undefined",function(){return null},function(){}),rt(yS,"bigint",function(t){return t.toString()},function(t){return typeof BigInt<"u"?BigInt(t):(console.error("Please add a BigInt polyfill."),t)}),rt(pS,"Date",function(t){return t.toISOString()},function(t){return new Date(t)}),rt(mS,"Error",function(t,e){var r={name:t.name,message:t.message};return e.allowedErrorProps.forEach(function(n){r[n]=t[n]}),r},function(t,e){var r=new Error(t.message);return r.name=t.name,r.stack=t.stack,e.allowedErrorProps.forEach(function(n){r[n]=t[n]}),r}),rt(hS,"regexp",function(t){return""+t},function(t){var e=t.slice(1,t.lastIndexOf("/")),r=t.slice(t.lastIndexOf("/")+1);return new RegExp(e,r)}),rt(ui,"set",function(t){return ol([],sl(t.values()))},function(t){return new Set(t)}),rt(ci,"map",function(t){return ol([],sl(t.entries()))},function(t){return new Map(t)}),rt(function(t){return Ch(t)||bS(t)},"number",function(t){return Ch(t)?"NaN":t>0?"Infinity":"-Infinity"},Number),rt(function(t){return t===0&&1/t===-1/0},"number",function(){return"-0"},Number),rt(DS,"URL",function(t){return t.toString()},function(t){return new URL(t)})];function Xs(t,e,r,n){return{isApplicable:t,annotation:e,transform:r,untransform:n}}var Up=Xs(function(t,e){if(Lp(t)){var r=!!e.symbolRegistry.getIdentifier(t);return r}return!1},function(t,e){var r=e.symbolRegistry.getIdentifier(t);return["symbol",r]},function(t){return t.description},function(t,e,r){var n=r.symbolRegistry.getValue(e[1]);if(!n)throw new Error("Trying to deserialize unknown symbol");return n}),wS=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce(function(t,e){return t[e.name]=e,t},{}),qp=Xs(vS,function(t){return["typed-array",t.constructor.name]},function(t){return ol([],sl(t))},function(t,e){var r=wS[e[1]];if(!r)throw new Error("Trying to deserialize unknown typed array");return new r(t)});function zp(t,e){if(t?.constructor){var r=!!e.classRegistry.getIdentifier(t.constructor);return r}return!1}var Vp=Xs(zp,function(t,e){var r=e.classRegistry.getIdentifier(t.constructor);return["class",r]},function(t,e){var r=e.classRegistry.getAllowedProps(t.constructor);if(!r)return il({},t);var n={};return r.forEach(function(i){n[i]=t[i]}),n},function(t,e,r){var n=r.classRegistry.getValue(e[1]);if(!n)throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564");return Object.assign(Object.create(n.prototype),t)}),Wp=Xs(function(t,e){return!!e.customTransformerRegistry.findApplicable(t)},function(t,e){var r=e.customTransformerRegistry.findApplicable(t);return["custom",r.name]},function(t,e){var r=e.customTransformerRegistry.findApplicable(t);return r.serialize(t)},function(t,e,r){var n=r.customTransformerRegistry.findByName(e[1]);if(!n)throw new Error("Trying to deserialize unknown custom value");return n.deserialize(t)}),SS=[Vp,Up,Wp,qp],Eh=function(t,e){var r=Sh(SS,function(i){return i.isApplicable(t,e)});if(r)return{value:r.transform(t,e),type:r.annotation(t,e)};var n=Sh($p,function(i){return i.isApplicable(t,e)});if(n)return{value:n.transform(t,e),type:n.annotation}},Gp={};$p.forEach(function(t){Gp[t.annotation]=t});var CS=function(t,e,r){if(Vt(e))switch(e[0]){case"symbol":return Up.untransform(t,e,r);case"class":return Vp.untransform(t,e,r);case"custom":return Wp.untransform(t,e,r);case"typed-array":return qp.untransform(t,e,r);default:throw new Error("Unknown transformation: "+e)}else{var n=Gp[e];if(!n)throw new Error("Unknown transformation: "+e);return n.untransform(t,r)}},mn=function(t,e){for(var r=t.keys();e>0;)r.next(),e--;return r.next().value};function Zp(t){if(_s(t,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(_s(t,"prototype"))throw new Error("prototype is not allowed as a property");if(_s(t,"constructor"))throw new Error("constructor is not allowed as a property")}var ES=function(t,e){Zp(e);for(var r=0;r<e.length;r++){var n=e[r];if(ui(t))t=mn(t,+n);else if(ci(t)){var i=+n,s=+e[++r]==0?"key":"value",a=mn(t,i);switch(s){case"key":t=a;break;case"value":t=t.get(a);break}}else t=t[n]}return t},al=function(t,e,r){if(Zp(e),e.length===0)return r(t);for(var n=t,i=0;i<e.length-1;i++){var s=e[i];if(Vt(n)){var a=+s;n=n[a]}else if(li(n))n=n[s];else if(ui(n)){var l=+s;n=mn(n,l)}else if(ci(n)){var c=i===e.length-2;if(c)break;var l=+s,u=+e[++i]==0?"key":"value",h=mn(n,l);switch(u){case"key":n=h;break;case"value":n=n.get(h);break}}}var f=e[e.length-1];if(Vt(n)?n[+f]=r(n[+f]):li(n)&&(n[f]=r(n[f])),ui(n)){var d=mn(n,+f),p=r(d);d!==p&&(n.delete(d),n.add(p))}if(ci(n)){var l=+e[e.length-2],m=mn(n,l),u=+f==0?"key":"value";switch(u){case"key":{var g=r(m);n.set(g,n.get(m)),g!==m&&n.delete(m);break}case"value":{n.set(m,r(n.get(m)));break}}}return t},Ct=globalThis&&globalThis.__read||function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},$t=globalThis&&globalThis.__spreadArray||function(t,e){for(var r=0,n=e.length,i=t.length;r<n;r++,i++)t[i]=e[r];return t};function ll(t,e,r){if(r===void 0&&(r=[]),!!t){if(!Vt(t)){bn(t,function(a,l){return ll(a,e,$t($t([],Ct(r)),Ct(Kn(l))))});return}var n=Ct(t,2),i=n[0],s=n[1];s&&bn(s,function(a,l){ll(a,e,$t($t([],Ct(r)),Ct(Kn(l))))}),e(i,r)}}function _S(t,e,r){return ll(e,function(n,i){t=al(t,i,function(s){return CS(s,n,r)})}),t}function xS(t,e){function r(a,l){var c=ES(t,Kn(l));a.map(Kn).forEach(function(u){t=al(t,u,function(){return c})})}if(Vt(e)){var n=Ct(e,2),i=n[0],s=n[1];i.forEach(function(a){t=al(t,Kn(a),function(){return t})}),s&&bn(s,r)}else bn(e,r);return t}var kS=function(t,e){return li(t)||Vt(t)||ci(t)||ui(t)||zp(t,e)};function FS(t,e,r){var n=r.get(t);n?n.push(e):r.set(t,[e])}function PS(t,e){var r={},n=void 0;return t.forEach(function(i){if(!(i.length<=1)){e||(i=i.map(function(c){return c.map(String)}).sort(function(c,u){return c.length-u.length}));var s=Ct(i),a=s[0],l=s.slice(1);a.length===0?n=l.map(Ma):r[Ma(a)]=l.map(Ma)}}),n?nl(r)?[n]:[n,r]:nl(r)?void 0:r}var Kp=function(t,e,r,n,i,s,a){var l;i===void 0&&(i=[]),s===void 0&&(s=[]),a===void 0&&(a=new Map);var c=gS(t);if(!c){FS(t,i,e);var u=a.get(t);if(u)return n?{transformedValue:null}:u}if(!kS(t,r)){var h=Eh(t,r),f=h?{transformedValue:h.value,annotations:[h.type]}:{transformedValue:t};return c||a.set(t,f),f}if(_s(s,t))return{transformedValue:null};var d=Eh(t,r),p=(l=d?.value)!==null&&l!==void 0?l:t,m=Vt(p)?[]:{},g={};bn(p,function(b,D){var v=Kp(b,e,r,n,$t($t([],Ct(i)),[D]),$t($t([],Ct(s)),[t]),a);m[D]=v.transformedValue,Vt(v.annotations)?g[D]=v.annotations:li(v.annotations)&&bn(v.annotations,function(S,C){g[Np(D)+"."+C]=S})});var y=nl(g)?{transformedValue:m,annotations:d?[d.type]:void 0}:{transformedValue:m,annotations:d?[d.type,g]:g};return c||a.set(t,y),y};function Hp(t){return Object.prototype.toString.call(t).slice(8,-1)}function _h(t){return Hp(t)==="Array"}function TS(t){if(Hp(t)!=="Object")return!1;let e=Object.getPrototypeOf(t);return!!e&&e.constructor===Object&&e===Object.prototype}function AS(t,e,r,n,i){let s={}.propertyIsEnumerable.call(n,e)?"enumerable":"nonenumerable";s==="enumerable"&&(t[e]=r),i&&s==="nonenumerable"&&Object.defineProperty(t,e,{value:r,enumerable:!1,writable:!0,configurable:!0})}function cl(t,e={}){if(_h(t))return t.map(i=>cl(i,e));if(!TS(t))return t;let r=Object.getOwnPropertyNames(t),n=Object.getOwnPropertySymbols(t);return[...r,...n].reduce((i,s)=>{if(_h(e.props)&&!e.props.includes(s))return i;let a=t[s],l=cl(a,e);return AS(i,s,l,t,e.nonenumerable),i},{})}var Cr=globalThis&&globalThis.__assign||function(){return Cr=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++){e=arguments[r];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},Cr.apply(this,arguments)},OS=globalThis&&globalThis.__read||function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},IS=globalThis&&globalThis.__spreadArray||function(t,e){for(var r=0,n=e.length,i=t.length;r<n;r++,i++)t[i]=e[r];return t},Yp=(function(){function t(e){var r=e===void 0?{}:e,n=r.dedupe,i=n===void 0?!1:n;this.classRegistry=new nS,this.symbolRegistry=new jp(function(s){var a;return(a=s.description)!==null&&a!==void 0?a:""}),this.customTransformerRegistry=new aS,this.allowedErrorProps=[],this.dedupe=i}return t.prototype.serialize=function(e){var r=new Map,n=Kp(e,r,this,this.dedupe),i={json:n.transformedValue};n.annotations&&(i.meta=Cr(Cr({},i.meta),{values:n.annotations}));var s=PS(r,this.dedupe);return s&&(i.meta=Cr(Cr({},i.meta),{referentialEqualities:s})),i},t.prototype.deserialize=function(e){var r=e.json,n=e.meta,i=cl(r);return n?.values&&(i=_S(i,n.values,this)),n?.referentialEqualities&&(i=xS(i,n.referentialEqualities)),i},t.prototype.stringify=function(e){return JSON.stringify(this.serialize(e))},t.prototype.parse=function(e){return this.deserialize(JSON.parse(e))},t.prototype.registerClass=function(e,r){this.classRegistry.register(e,r)},t.prototype.registerSymbol=function(e,r){this.symbolRegistry.register(e,r)},t.prototype.registerCustom=function(e,r){this.customTransformerRegistry.register(Cr({name:r},e))},t.prototype.allowErrorProps=function(){for(var e,r=[],n=0;n<arguments.length;n++)r[n]=arguments[n];(e=this.allowedErrorProps).push.apply(e,IS([],OS(r)))},t.defaultInstance=new t,t.serialize=t.defaultInstance.serialize.bind(t.defaultInstance),t.deserialize=t.defaultInstance.deserialize.bind(t.defaultInstance),t.stringify=t.defaultInstance.stringify.bind(t.defaultInstance),t.parse=t.defaultInstance.parse.bind(t.defaultInstance),t.registerClass=t.defaultInstance.registerClass.bind(t.defaultInstance),t.registerSymbol=t.defaultInstance.registerSymbol.bind(t.defaultInstance),t.registerCustom=t.defaultInstance.registerCustom.bind(t.defaultInstance),t.allowErrorProps=t.defaultInstance.allowErrorProps.bind(t.defaultInstance),t})(),RS=Yp.serialize,MS=Yp.deserialize;function fn(t,e){switch(t){case"raw":return e;case"superjson":return RS(e)}}function ws(t,e){switch(t){case"raw":return e;case"superjson":return MS(e)}}var it=o.any(),jS=o.discriminatedUnion("type",[o.object({type:o.literal("communicationWarning"),warning:o.string()}),o.object({type:o.literal("keepAlive")}),o.object({type:o.literal("channelCreate"),endpoint:o.string(),channelId:o.number().int(),creationParameter:it}),o.object({type:o.literal("channelSend"),channelId:o.number().int(),message:it,ackId:o.number().int().optional()}),o.object({type:o.literal("channelAck"),channelId:o.number().int(),ackId:o.number().int()}),o.object({type:o.literal("rpcCall"),endpoint:o.string(),callId:o.number().int(),parameter:it}),o.object({type:o.literal("signalSubscribe"),creationParameter:it,endpoint:o.string(),subscribeId:o.number().int()}),o.object({type:o.literal("signalUnsubscribe"),subscribeId:o.number().int()}),o.object({type:o.literal("writableSignalSubscribe"),creationParameter:it,endpoint:o.string(),subscribeId:o.number().int()}),o.object({type:o.literal("writableSignalUnsubscribe"),subscribeId:o.number().int()}),o.object({type:o.literal("writableSignalUpdate"),subscribeId:o.number().int(),patches:o.array(it),tags:o.array(o.string())})]),BS=o.discriminatedUnion("type",[o.object({type:o.literal("communicationWarning"),warning:o.string()}),o.object({type:o.literal("keepAliveAck")}),o.object({type:o.literal("channelSend"),channelId:o.number().int(),message:it,ackId:o.number().int().optional()}),o.object({type:o.literal("channelAck"),channelId:o.number().int(),ackId:o.number().int()}),o.object({type:o.literal("channelClose"),channelId:o.number().int()}),o.object({type:o.literal("channelError"),channelId:o.number().int(),error:Ie}),o.object({type:o.literal("rpcResult"),callId:o.number().int(),result:it}),o.object({type:o.literal("rpcError"),callId:o.number().int(),error:Ie}),o.object({type:o.literal("signalUpdate"),subscribeId:o.number().int(),patches:o.array(it),tags:o.array(o.string())}),o.object({type:o.literal("signalError"),subscribeId:o.number().int(),error:Ie}),o.object({type:o.literal("writableSignalUpdate"),subscribeId:o.number().int(),patches:o.array(it),tags:o.array(o.string())}),o.object({type:o.literal("writableSignalError"),subscribeId:o.number().int(),error:Ie})]),ul=class{constructor(){this.disposed=!1}async[Symbol.asyncDispose](){if(this.disposed)throw new Error("Cannot dispose twice");this.disposed=!0}},Bs=class extends ul{parseIncomingMessage(e){return BS.parse(e)}send(e){let r=jS.parse(e);this.sendViaTransport(r)}onHavingOneOrMoreOpenCommunication(){}onHavingNoOpenCommunication(){}},LS=o.discriminatedUnion("success",[o.object({success:o.literal(!0)}),o.object({success:o.literal(!1),error:o.string()})]),Fe;(function(t){t.Disconnected="DISCONNECTED",t.Connecting="CONNECTING",t.Connected="CONNECTED"})(Fe||(Fe={}));var dl=class t extends Bs{constructor(e,r,n,{abortSignal:i,parentLogger:s}={}){super(),this.url=e,this.receivedMessage=r,this.errored=n,this.ws=null,this.queuedMessages=[],this.status=Fe.Disconnected,this.resolvedUrl=null,this.shouldRef=!1,this.resolveDisposed=null,this.abortSignal=i,this.logger=new Y("WsClientTransport",s)}static createWsClientTransportFactory(e,{abortSignal:r}={}){return(n,i,s)=>new t(e,n,i,{abortSignal:r,parentLogger:s})}connect(){if(this.status!==Fe.Disconnected){this.logger.warn("connect() called while not disconnected");return}if(this.disposed)throw new Error(j`
231
231
  Cannot establish WebSocket connection because the transport has been disposed.
232
- `);if(this.abortSignal!==void 0&&this.abortSignal.aborted)throw new Error(this.abortSignal.reason);this.status=Fe.Connecting,Promise.resolve(this.url).then(e=>{this.resolvedUrl=e,this.ws=new st.WebSocket(e),this.ws.addEventListener("open",this.onWsOpen.bind(this)),this.ws.addEventListener("error",n=>this.onWsError(n.error)),this.ws.addEventListener("close",()=>{this.onWsError(new Error("WebSocket connection closed"))});let r=this.abortSignal;if(r!==void 0)if(r.aborted)this.onWsError(r.reason);else{let n=()=>{this.onWsError(r.reason)};r.addEventListener("abort",n,{once:!0}),this.ws.addEventListener("close",()=>{r.removeEventListener("abort",n)})}})}onWsOpen(){this.ws.addEventListener("message",this.onWsMessage.bind(this)),this.status=Fe.Connected,this.queuedMessages.forEach(e=>this.sendViaTransport(e)),this.queuedMessages=[],this.updateShouldRef(this.shouldRef)}onWsMessage(e){if(this.status!==Fe.Connected){this.logger.warn("Received message while not connected. Message ignored:",e.data);return}let r;try{r=JSON.parse(String(e.data))}catch{this.logger.warn("Received invalid JSON message from server:",e.data);return}let n;try{n=this.parseIncomingMessage(r)}catch{this.logger.warn("Received invalid message from server:",r);return}this.receivedMessage(n)}onWsError(e){if(this.status!==Fe.Disconnected){this.logger.warn("WebSocket error:",e),e.code==="ECONNREFUSED"&&this.logger.warnText`
232
+ `);if(this.abortSignal!==void 0&&this.abortSignal.aborted)throw new Error(this.abortSignal.reason);this.status=Fe.Connecting,Promise.resolve(this.url).then(e=>{this.resolvedUrl=e,this.ws=new at.WebSocket(e),this.ws.addEventListener("open",this.onWsOpen.bind(this)),this.ws.addEventListener("error",n=>this.onWsError(n.error)),this.ws.addEventListener("close",()=>{this.onWsError(new Error("WebSocket connection closed"))});let r=this.abortSignal;if(r!==void 0)if(r.aborted)this.onWsError(r.reason);else{let n=()=>{this.onWsError(r.reason)};r.addEventListener("abort",n,{once:!0}),this.ws.addEventListener("close",()=>{r.removeEventListener("abort",n)})}})}onWsOpen(){this.ws.addEventListener("message",this.onWsMessage.bind(this)),this.status=Fe.Connected,this.queuedMessages.forEach(e=>this.sendViaTransport(e)),this.queuedMessages=[],this.updateShouldRef(this.shouldRef)}onWsMessage(e){if(this.status!==Fe.Connected){this.logger.warn("Received message while not connected. Message ignored:",e.data);return}let r;try{r=JSON.parse(String(e.data))}catch{this.logger.warn("Received invalid JSON message from server:",e.data);return}let n;try{n=this.parseIncomingMessage(r)}catch{this.logger.warn("Received invalid message from server:",r);return}this.receivedMessage(n)}onWsError(e){if(this.status!==Fe.Disconnected){this.logger.warn("WebSocket error:",e),e.code==="ECONNREFUSED"&&this.logger.warnText`
233
233
  WebSocket connection refused. This can happen if the server is not running or the client
234
234
  is trying to connect to the wrong path. The server path that this client is
235
235
  attempting to connect to is:
@@ -242,7 +242,7 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
242
242
  2. The API server in LM Studio has started
243
243
 
244
244
  3. The client is attempting to connect to the correct path
245
- `;try{this.ws?.close()}catch{}this.status=Fe.Disconnected,this.errored(e)}}onWsTimeout(){if(this.status!==Fe.Disconnected){this.logger.warn("Websocket timed out");try{this.ws?.close()}catch{}this.status=Fe.Disconnected,this.errored(new Error("WebSocket timed out"))}}onHavingNoOpenCommunication(){this.updateShouldRef(!1),this.disposed&&this.resolveDisposed!==null&&(this.resolveDisposed(),this.resolveDisposed=null)}onHavingOneOrMoreOpenCommunication(){this.updateShouldRef(!0)}updateShouldRef(e){this.shouldRef=e,this.ws!==null&&this.ws._socket&&(e?this.ws._socket.ref():this.ws._socket.unref())}sendViaTransport(e){this.status===Fe.Connected?this.ws.send(JSON.stringify(e)):(this.queuedMessages.push(e),this.status===Fe.Disconnected&&this.connect())}async[Symbol.asyncDispose](){if(await super[Symbol.asyncDispose](),this.shouldRef){let{promise:e,resolve:r}=re();this.resolveDisposed=r,await e}if(this.ws!==null){try{this.ws.close()}catch{}this.ws=null}this.errored(new Error("WebSocket client transport disposed")),this.status=Fe.Disconnected}},dl=class t extends ul{constructor(e,r,n,i,s,{parentLogger:a,abortSignal:l}={}){super(e,i,s,{parentLogger:a,abortSignal:l}),this.clientIdentifier=r,this.clientPasskey=n,this.logger=this.logger.subclass("AuthenticatedWsClientTransport")}static createAuthenticatedWsClientTransportFactory({url:e,clientIdentifier:r,clientPasskey:n,abortSignal:i}){return(s,a,l)=>new t(e,r,n,s,a,{parentLogger:l,abortSignal:i})}onWsOpen(){this.ws.send(JSON.stringify({authVersion:1,clientIdentifier:this.clientIdentifier,clientPasskey:this.clientPasskey})),this.ws.addEventListener("message",e=>{try{let r=JSON.parse(e.data.toString("utf-8")),n=BS.parse(r);n.success?super.onWsOpen():this.onWsError(new Error("Failed to authenticate: "+n.error))}catch(r){this.onWsError(new Error("Failed to parse authentication result: "+r?.message))}},{once:!0})}};function LS(t,e,r){return Os(t,e,r)}var Ls=class{constructor(e,r,{parentLogger:n,errorDeserializer:i,verboseErrorMessage:s}={}){this.backendInterface=e,this.openChannels=new Map,this.ongoingRpcs=new Map,this.openSignalSubscriptions=new Map,this.openWritableSignalSubscriptions=new Map,this.openCommunicationsCount=0,this.nextChannelId=0,this.nextSubscribeId=0,this.nextWritableSubscribeId=0,this.producedCommunicationWarningsCount=0,this.receivedMessage=a=>{switch(a.type){case"channelSend":{this.receivedChannelSend(a);break}case"channelAck":{this.receivedChannelAck(a);break}case"channelClose":{this.receivedChannelClose(a);break}case"channelError":{this.receivedChannelError(a);break}case"rpcResult":{this.receivedRpcResult(a);break}case"rpcError":{this.receivedRpcError(a);break}case"signalUpdate":{this.receivedSignalUpdate(a);break}case"signalError":{this.receivedSignalError(a);break}case"writableSignalUpdate":{this.receivedWritableSignalUpdate(a);break}case"writableSignalError":{this.receivedWritableSignalError(a);break}case"communicationWarning":{this.receivedCommunicationWarning(a);break}case"keepAliveAck":{this.receivedKeepAliveAck(a);break}}},this.errored=a=>{for(let l of this.openChannels.values())l.errored(a);this.openChannels.clear();for(let l of this.ongoingRpcs.values())l.reject(a);this.ongoingRpcs.clear();for(let l of this.openSignalSubscriptions.values())l.errored(a);this.openSignalSubscriptions.clear();for(let l of this.openWritableSignalSubscriptions.values())l.errored(a);this.openWritableSignalSubscriptions.clear(),this.updateOpenCommunicationsCount()},this.logger=new Y("ClientPort",n),this.errorDeserializer=i??LS,this.verboseErrorMessage=s??!0,this.transport=r(this.receivedMessage,this.errored,this.logger)}communicationWarning(e){this.producedCommunicationWarningsCount>=5||(this.logger.warnText`
245
+ `;try{this.ws?.close()}catch{}this.status=Fe.Disconnected,this.errored(e)}}onWsTimeout(){if(this.status!==Fe.Disconnected){this.logger.warn("Websocket timed out");try{this.ws?.close()}catch{}this.status=Fe.Disconnected,this.errored(new Error("WebSocket timed out"))}}onHavingNoOpenCommunication(){this.updateShouldRef(!1),this.disposed&&this.resolveDisposed!==null&&(this.resolveDisposed(),this.resolveDisposed=null)}onHavingOneOrMoreOpenCommunication(){this.updateShouldRef(!0)}updateShouldRef(e){this.shouldRef=e,this.ws!==null&&this.ws._socket&&(e?this.ws._socket.ref():this.ws._socket.unref())}sendViaTransport(e){this.status===Fe.Connected?this.ws.send(JSON.stringify(e)):(this.queuedMessages.push(e),this.status===Fe.Disconnected&&this.connect())}async[Symbol.asyncDispose](){if(await super[Symbol.asyncDispose](),this.shouldRef){let{promise:e,resolve:r}=re();this.resolveDisposed=r,await e}if(this.ws!==null){try{this.ws.close()}catch{}this.ws=null}this.errored(new Error("WebSocket client transport disposed")),this.status=Fe.Disconnected}},fl=class t extends dl{constructor(e,r,n,i,s,{parentLogger:a,abortSignal:l}={}){super(e,i,s,{parentLogger:a,abortSignal:l}),this.clientIdentifier=r,this.clientPasskey=n,this.logger=this.logger.subclass("AuthenticatedWsClientTransport")}static createAuthenticatedWsClientTransportFactory({url:e,clientIdentifier:r,clientPasskey:n,abortSignal:i}){return(s,a,l)=>new t(e,r,n,s,a,{parentLogger:l,abortSignal:i})}onWsOpen(){this.ws.send(JSON.stringify({authVersion:1,clientIdentifier:this.clientIdentifier,clientPasskey:this.clientPasskey})),this.ws.addEventListener("message",e=>{try{let r=JSON.parse(e.data.toString("utf-8")),n=LS.parse(r);n.success?super.onWsOpen():this.onWsError(new Error("Failed to authenticate: "+n.error))}catch(r){this.onWsError(new Error("Failed to parse authentication result: "+r?.message))}},{once:!0})}};function NS(t,e,r){return Os(t,e,r)}var Ls=class{constructor(e,r,{parentLogger:n,errorDeserializer:i,verboseErrorMessage:s}={}){this.backendInterface=e,this.openChannels=new Map,this.ongoingRpcs=new Map,this.openSignalSubscriptions=new Map,this.openWritableSignalSubscriptions=new Map,this.openCommunicationsCount=0,this.nextChannelId=0,this.nextSubscribeId=0,this.nextWritableSubscribeId=0,this.producedCommunicationWarningsCount=0,this.receivedMessage=a=>{switch(a.type){case"channelSend":{this.receivedChannelSend(a);break}case"channelAck":{this.receivedChannelAck(a);break}case"channelClose":{this.receivedChannelClose(a);break}case"channelError":{this.receivedChannelError(a);break}case"rpcResult":{this.receivedRpcResult(a);break}case"rpcError":{this.receivedRpcError(a);break}case"signalUpdate":{this.receivedSignalUpdate(a);break}case"signalError":{this.receivedSignalError(a);break}case"writableSignalUpdate":{this.receivedWritableSignalUpdate(a);break}case"writableSignalError":{this.receivedWritableSignalError(a);break}case"communicationWarning":{this.receivedCommunicationWarning(a);break}case"keepAliveAck":{this.receivedKeepAliveAck(a);break}}},this.errored=a=>{for(let l of this.openChannels.values())l.errored(a);this.openChannels.clear();for(let l of this.ongoingRpcs.values())l.reject(a);this.ongoingRpcs.clear();for(let l of this.openSignalSubscriptions.values())l.errored(a);this.openSignalSubscriptions.clear();for(let l of this.openWritableSignalSubscriptions.values())l.errored(a);this.openWritableSignalSubscriptions.clear(),this.updateOpenCommunicationsCount()},this.logger=new Y("ClientPort",n),this.errorDeserializer=i??NS,this.verboseErrorMessage=s??!0,this.transport=r(this.receivedMessage,this.errored,this.logger)}communicationWarning(e){this.producedCommunicationWarningsCount>=5||(this.logger.warnText`
246
246
  Produced communication warning: ${e}
247
247
 
248
248
  This is usually caused by communication protocol incompatibility. Please make sure you are
@@ -253,13 +253,13 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
253
253
  Received invalid message for channel: endpointName = ${r.endpoint.name}, message =
254
254
  ${n}. Zod error:
255
255
 
256
- ${it.prettyPrintZod("message",i.error)}
256
+ ${ot.prettyPrintZod("message",i.error)}
257
257
  `);return}r.receivedMessage(i.data)}receivedChannelAck(e){let r=this.openChannels.get(e.channelId);if(r===void 0){this.communicationWarning(`Received channelAck for unknown channel, channelId = ${e.channelId}`);return}r.receivedAck(e.ackId)}receivedChannelClose(e){let r=this.openChannels.get(e.channelId);if(r===void 0){this.communicationWarning(`Received channelClose for unknown channel, channelId = ${e.channelId}`);return}this.openChannels.delete(e.channelId),r.closed(),this.updateOpenCommunicationsCount()}receivedChannelError(e){let r=this.openChannels.get(e.channelId);if(r===void 0){this.communicationWarning(`Received channelError for unknown channel, channelId = ${e.channelId}`);return}this.openChannels.delete(e.channelId);let n=this.errorDeserializer(e.error,"Channel Error",this.verboseErrorMessage?r.stack:void 0);r.errored(n),this.updateOpenCommunicationsCount()}receivedRpcResult(e){let r=this.ongoingRpcs.get(e.callId);if(r===void 0){this.communicationWarning(`Received rpcResult for unknown rpc, callId = ${e.callId}`);return}let n=ws(r.endpoint.serialization,e.result),i=r.endpoint.returns.safeParse(n);if(!i.success){this.communicationWarning(j`
258
258
  Received invalid result for rpc, endpointName = ${r.endpoint.name}, result =
259
259
  ${n}. Zod error:
260
260
 
261
- ${it.prettyPrintZod("result",i.error)}
262
- `);return}r.resolve(i.data),this.ongoingRpcs.delete(e.callId),this.updateOpenCommunicationsCount()}receivedRpcError(e){let r=this.ongoingRpcs.get(e.callId);if(r===void 0){this.communicationWarning(`Received rpcError for unknown rpc, callId = ${e.callId}`);return}let n=this.errorDeserializer(e.error,"RPC Error",this.verboseErrorMessage?r.stack:void 0);r.reject(n),this.ongoingRpcs.delete(e.callId),this.updateOpenCommunicationsCount()}receivedSignalUpdate(e){let r=this.openSignalSubscriptions.get(e.subscribeId);if(r===void 0)return;let n=e.patches.map(l=>ws(r.endpoint.serialization,l)),i=r.getValue(),s;try{s=Na(i,n)}catch(l){this.communicationWarning(j`
261
+ ${ot.prettyPrintZod("result",i.error)}
262
+ `);return}r.resolve(i.data),this.ongoingRpcs.delete(e.callId),this.updateOpenCommunicationsCount()}receivedRpcError(e){let r=this.ongoingRpcs.get(e.callId);if(r===void 0){this.communicationWarning(`Received rpcError for unknown rpc, callId = ${e.callId}`);return}let n=this.errorDeserializer(e.error,"RPC Error",this.verboseErrorMessage?r.stack:void 0);r.reject(n),this.ongoingRpcs.delete(e.callId),this.updateOpenCommunicationsCount()}receivedSignalUpdate(e){let r=this.openSignalSubscriptions.get(e.subscribeId);if(r===void 0)return;let n=e.patches.map(l=>ws(r.endpoint.serialization,l)),i=r.getValue(),s;try{s=$a(i,n)}catch(l){this.communicationWarning(j`
263
263
  Failed to apply patches to signal on signalUpdate. subscribeId = ${e.subscribeId}.
264
264
 
265
265
  beforeValue = ${JSON.stringify(i,null,2)},
@@ -278,8 +278,8 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
278
278
 
279
279
  Zod error:
280
280
 
281
- ${it.prettyPrintZod("value",a.error)}
282
- `);return}r.receivedPatches(s,n,e.tags)}receivedSignalError(e){let r=this.openSignalSubscriptions.get(e.subscribeId);if(r===void 0){this.communicationWarning(`Received signalError for unknown signal, subscribeId = ${e.subscribeId}`);return}let n=this.errorDeserializer(e.error,"Signal Error",this.verboseErrorMessage?r.stack:void 0);r.errored(n),this.openSignalSubscriptions.delete(e.subscribeId),this.updateOpenCommunicationsCount()}receivedWritableSignalUpdate(e){let r=this.openWritableSignalSubscriptions.get(e.subscribeId);if(r===void 0)return;let n=e.patches.map(l=>ws(r.endpoint.serialization,l)),i=r.getValue(),s;try{s=Na(r.getValue(),n)}catch(l){this.communicationWarning(j`
281
+ ${ot.prettyPrintZod("value",a.error)}
282
+ `);return}r.receivedPatches(s,n,e.tags)}receivedSignalError(e){let r=this.openSignalSubscriptions.get(e.subscribeId);if(r===void 0){this.communicationWarning(`Received signalError for unknown signal, subscribeId = ${e.subscribeId}`);return}let n=this.errorDeserializer(e.error,"Signal Error",this.verboseErrorMessage?r.stack:void 0);r.errored(n),this.openSignalSubscriptions.delete(e.subscribeId),this.updateOpenCommunicationsCount()}receivedWritableSignalUpdate(e){let r=this.openWritableSignalSubscriptions.get(e.subscribeId);if(r===void 0)return;let n=e.patches.map(l=>ws(r.endpoint.serialization,l)),i=r.getValue(),s;try{s=$a(r.getValue(),n)}catch(l){this.communicationWarning(j`
283
283
  Failed to apply patches to writable signal on writableSignalUpdate. subscribeId =
284
284
  ${e.subscribeId}.
285
285
 
@@ -299,7 +299,7 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
299
299
 
300
300
  Zod error:
301
301
 
302
- ${it.prettyPrintZod("value",a.error)}
302
+ ${ot.prettyPrintZod("value",a.error)}
303
303
  `);return}r.firstUpdateReceived=!0,r.receivedPatches(s,n,e.tags)}receivedWritableSignalError(e){let r=this.openWritableSignalSubscriptions.get(e.subscribeId);if(r===void 0){this.communicationWarning(`Received writableSignalError for unknown signal, subscribeId = ${e.subscribeId}`);return}let n=this.errorDeserializer(e.error,"Writable Signal Error",this.verboseErrorMessage?r.stack:void 0);r.errored(n),this.openWritableSignalSubscriptions.delete(e.subscribeId),this.updateOpenCommunicationsCount()}receivedCommunicationWarning(e){this.logger.warnText`
304
304
  Received communication warning from the server: ${e.warning}
305
305
 
@@ -307,10 +307,10 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
307
307
  using the up-to-date versions of the SDK and LM Studio.
308
308
 
309
309
  Note: This warning was received from the server and is printed on the client for convenience.
310
- `}receivedKeepAliveAck(e){}async callRpc(e,r,{stack:n}={}){let i=this.backendInterface.getRpcEndpoint(e);if(i===void 0)throw new Error(`No Rpc endpoint with name ${e}`);let s=i.parameter.parse(r),a=fn(i.serialization,s),l=this.nextChannelId;this.nextChannelId++;let{promise:c,resolve:u,reject:h}=re();return n=n??A(1),this.ongoingRpcs.set(l,{endpoint:i,stack:n,resolve:u,reject:h}),this.transport.send({type:"rpcCall",endpoint:e,callId:l,parameter:a}),this.updateOpenCommunicationsCount(),await c}createChannel(e,r,n,{stack:i}={}){let s=this.backendInterface.getChannelEndpoint(e);if(s===void 0)throw new Error(`No channel endpoint with name ${e}`);let a=s.creationParameter.parse(r),l=fn(s.serialization,a),c=this.nextChannelId;this.nextChannelId++,this.transport.send({type:"channelCreate",endpoint:e,channelId:c,creationParameter:l}),i=i??A(1);let u={endpoint:s,stack:i,...tl.create(h=>{let f=s.toServerPacket.parse(h),d=fn(s.serialization,f);this.transport.send({type:"channelSend",channelId:c,message:d})})};return n!==void 0&&u.channel.onMessage.subscribe(n),this.openChannels.set(c,u),this.updateOpenCommunicationsCount(),u.channel}createSignal(e,r,{stack:n}={}){let i=this.backendInterface.getSignalEndpoint(e);if(i===void 0)throw new Error(`No signal endpoint with name ${e}`);let s=i.creationParameter.parse(r),a=fn(i.serialization,s);n=n??A(1);let l=Ge.createWithoutInitialValue((c,u)=>{let h=this.nextSubscribeId;return this.nextSubscribeId++,this.transport.send({type:"signalSubscribe",endpoint:e,subscribeId:h,creationParameter:a}),this.openSignalSubscriptions.set(h,{endpoint:i,getValue:()=>l.get(),receivedPatches:c.withValueAndPatches,errored:u,stack:n}),this.updateOpenCommunicationsCount(),()=>{this.transport.send({type:"signalUnsubscribe",subscribeId:h}),this.openSignalSubscriptions.delete(h)}});return l}createWritableSignal(e,r,{stack:n}={}){let i=this.backendInterface.getWritableSignalEndpoint(e);if(i===void 0)throw new Error(`No writable signal endpoint with name ${e}`);let s=i.creationParameter.parse(r),a=fn(i.serialization,s);n=n??A(1);let l=null,c=(f,d,p)=>l===null?(console.warn("writeUpstream called when not subscribed"),!1):this.openWritableSignalSubscriptions.get(l)?.firstUpdateReceived?(this.transport.send({type:"writableSignalUpdate",subscribeId:l,patches:d.map(g=>fn(i.serialization,g)),tags:p}),!0):(console.warn("writeUpstream called before the first update is received"),!1),[u,h]=Ua.createWithoutInitialValue((f,d)=>{let p=this.nextWritableSubscribeId;return l=p,this.nextWritableSubscribeId++,this.transport.send({type:"writableSignalSubscribe",endpoint:e,subscribeId:p,creationParameter:a}),this.openWritableSignalSubscriptions.set(p,{endpoint:i,getValue:()=>u.getPessimistic(),receivedPatches:f.withValueAndPatches,firstUpdateReceived:!1,errored:d,stack:n}),this.updateOpenCommunicationsCount(),()=>{l=null,this.transport.send({type:"writableSignalUnsubscribe",subscribeId:p}),this.openWritableSignalSubscriptions.delete(p)}},c);return[u,h]}async[Symbol.asyncDispose](){await this.transport[Symbol.asyncDispose]()}},fl=class t extends Bs{constructor(e,r,n,i,s,a){super(),this.sendMessage=n,this.receivedMessage=i,this.errored=s,this.closed=!1,this.logger=new Y("GenericClientTransport",a),e.subscribe(l=>{let c;try{c=this.parseIncomingMessage(l)}catch{this.logger.warn("Received invalid message from server:",l);return}this.receivedMessage(c)}),r.subscribeOnce(()=>{this.closed||(this.closed=!0,this.errored(new Error("Server closed the connection")))})}static createFactory(e,r,n){return(i,s,a)=>new t(e,r,n,i,s,a)}sendViaTransport(e){this.sendMessage(e)}};function Yp(){let t;try{t=window}catch{t=void 0}return t!==void 0&&t.lmsHostedEnv!==void 0?t.lmsHostedEnv:null}function Jp(t,e){let r=t,n=e;return new zt().addChannelEndpoint("loadModel",{creationParameter:o.object({modelKey:o.string(),identifier:o.string().optional(),ttlMs:o.number().int().min(1).optional(),loadConfigStack:Is}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("resolved"),info:n,ambiguous:o.array(o.string()).optional()}),o.object({type:o.literal("progress"),progress:o.number()}),o.object({type:o.literal("success"),info:r})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addRpcEndpoint("unloadModel",{parameter:o.object({identifier:o.string()}),returns:o.void()}).addRpcEndpoint("listLoaded",{parameter:o.undefined(),returns:o.array(r)}).addRpcEndpoint("getModelInfo",{parameter:o.object({specifier:nt,throwIfNotFound:o.boolean()}),returns:r.optional()}).addRpcEndpoint("getLoadConfig",{parameter:o.object({specifier:nt}),returns:te}).addChannelEndpoint("getOrLoad",{creationParameter:o.object({identifier:o.string(),loadTtlMs:o.number().int().min(1).optional(),loadConfigStack:Is}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("alreadyLoaded"),info:r}),o.object({type:o.literal("startLoading"),identifier:o.string(),info:n}),o.object({type:o.literal("unloadingOtherJITModel"),info:r1}),o.object({type:o.literal("loadProgress"),progress:o.number()}),o.object({type:o.literal("loadSuccess"),info:r})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])})}function NS(){return new zt().addChannelEndpoint("streamLogs",{creationParameter:o.void(),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("stop")})]),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("log"),log:uw})])})}function $S(){return Jp(Gh,Wh).addRpcEndpoint("embedString",{parameter:o.object({modelSpecifier:nt,inputString:o.string()}),returns:o.object({embedding:o.array(o.number())})}).addRpcEndpoint("tokenize",{parameter:o.object({specifier:nt,inputString:o.string()}),returns:o.object({tokens:o.array(o.number())})}).addRpcEndpoint("countTokens",{parameter:o.object({specifier:nt,inputString:o.string()}),returns:o.object({tokenCount:o.number().int()})})}function US(){return new zt().addRpcEndpoint("getLocalFileAbsolutePath",{parameter:o.object({fileName:o.string()}),returns:o.object({path:o.string()})}).addRpcEndpoint("uploadFileBase64",{parameter:o.object({name:o.string(),contentBase64:o.string()}),returns:o.object({identifier:o.string(),fileType:Lh,sizeBytes:o.number().int()})}).addChannelEndpoint("retrieve",{creationParameter:o.object({query:o.string(),fileIdentifiers:o.array(o.string()),config:te}),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("stop")})]),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("onFileProcessList"),indices:o.array(o.number().int())}),o.object({type:o.literal("onFileProcessingStart"),index:o.number().int()}),o.object({type:o.literal("onFileProcessingEnd"),index:o.number().int()}),o.object({type:o.literal("onFileProcessingStepStart"),index:o.number().int(),step:Ta}),o.object({type:o.literal("onFileProcessingStepProgress"),index:o.number().int(),step:Ta,progress:o.number()}),o.object({type:o.literal("onFileProcessingStepEnd"),index:o.number().int(),step:Ta}),o.object({type:o.literal("onSearchingStart")}),o.object({type:o.literal("onSearchingEnd")}),o.object({type:o.literal("result"),result:u1})])}).addChannelEndpoint("parseDocument",{creationParameter:o.object({fileIdentifier:o.string(),parseOpts:Kh}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("parserLoaded"),parser:za}),o.object({type:o.literal("progress"),progress:o.number()}),o.object({type:o.literal("result"),content:o.string(),parser:za})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addRpcEndpoint("getDocumentParsingLibrary",{parameter:o.object({fileIdentifier:o.string()}),returns:o.object({library:o.string(),version:o.string()})})}function qS(){return Jp(Va,tp).addChannelEndpoint("predict",{creationParameter:o.object({modelSpecifier:nt,history:Fr,predictionConfigStack:Is,fuzzyPresetIdentifier:o.string().optional(),ignoreServerSessionConfig:o.boolean().optional()}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("fragment"),fragment:ap,logprobs:o.array(o.array(o.object({text:o.string(),logprob:o.number()}))).optional()}),o.object({type:o.literal("promptProcessingProgress"),progress:o.number()}),o.object({type:o.literal("toolCallGenerationStart"),toolCallId:o.string().optional()}),o.object({type:o.literal("toolCallGenerationNameReceived"),name:o.string()}),o.object({type:o.literal("toolCallGenerationArgumentFragmentGenerated"),content:o.string()}),o.object({type:o.literal("toolCallGenerationEnd"),toolCallRequest:si,rawContent:o.string().optional()}),o.object({type:o.literal("toolCallGenerationFailed"),error:Oe,rawContent:o.string().optional()}),o.object({type:o.literal("success"),stats:cp,modelInfo:Va,loadModelConfig:te,predictionConfig:te})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addRpcEndpoint("applyPromptTemplate",{parameter:o.object({specifier:nt,history:Fr,predictionConfigStack:Is,opts:Xh}),returns:o.object({formatted:o.string()})}).addRpcEndpoint("tokenize",{parameter:o.object({specifier:nt,inputString:o.string()}),returns:o.object({tokens:o.array(o.number())})}).addRpcEndpoint("countTokens",{parameter:o.object({specifier:nt,inputString:o.string()}),returns:o.object({tokenCount:o.number().int()})}).addRpcEndpoint("preloadDraftModel",{parameter:o.object({specifier:nt,draftModelKey:o.string()}),returns:o.void()})}function zS(){return new zt().addChannelEndpoint("startToolUseSession",{creationParameter:o.object({pluginIdentifier:o.string(),pluginConfigSpecifier:ah}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("sessionReady"),toolDefinitions:o.array(Er)}),o.object({type:o.literal("toolCallComplete"),callId:o.number(),result:Pe}),o.object({type:o.literal("toolCallError"),callId:o.number(),error:Oe}),o.object({type:o.literal("toolCallStatus"),callId:o.number(),statusText:o.string()}),o.object({type:o.literal("toolCallWarn"),callId:o.number(),warnText:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("callTool"),callId:o.number(),name:o.string(),arguments:Pe}),o.object({type:o.literal("abortToolCall"),callId:o.number()}),o.object({type:o.literal("discardSession")})])}).addChannelEndpoint("generateWithGenerator",{creationParameter:o.object({pluginIdentifier:o.string(),pluginConfigSpecifier:ah,tools:o.array(Er),history:Fr}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("fragment"),fragment:ap}),o.object({type:o.literal("promptProcessingProgress"),progress:o.number()}),o.object({type:o.literal("toolCallGenerationStart"),toolCallId:o.string().optional()}),o.object({type:o.literal("toolCallGenerationNameReceived"),name:o.string()}),o.object({type:o.literal("toolCallGenerationArgumentFragmentGenerated"),content:o.string()}),o.object({type:o.literal("toolCallGenerationEnd"),toolCallRequest:si}),o.object({type:o.literal("toolCallGenerationFailed")}),o.object({type:o.literal("success")})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addChannelEndpoint("registerDevelopmentPlugin",{creationParameter:o.object({manifest:Zl}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("ready"),clientIdentifier:o.string(),clientPasskey:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("end")})])}).addRpcEndpoint("reindexPlugins",{parameter:o.void(),returns:o.void()}).addChannelEndpoint("setPromptPreprocessor",{creationParameter:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("preprocess"),taskId:o.string(),input:kr,config:te,pluginConfig:te,globalPluginConfig:te,workingDirectoryPath:o.string().nullable(),enabledPluginInfos:o.array(lh),pci:o.string(),token:o.string()}),o.object({type:o.literal("abort"),taskId:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("complete"),taskId:o.string(),processed:kr}),o.object({type:o.literal("aborted"),taskId:o.string()}),o.object({type:o.literal("error"),taskId:o.string(),error:Oe})])}).addChannelEndpoint("setPredictionLoopHandler",{creationParameter:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("handlePredictionLoop"),taskId:o.string(),config:te,pluginConfig:te,globalPluginConfig:te,workingDirectoryPath:o.string().nullable(),enabledPluginInfos:o.array(lh),pci:o.string(),token:o.string()}),o.object({type:o.literal("abort"),taskId:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("complete"),taskId:o.string()}),o.object({type:o.literal("aborted"),taskId:o.string()}),o.object({type:o.literal("error"),taskId:o.string(),error:Oe})])}).addChannelEndpoint("setToolsProvider",{creationParameter:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("initSession"),pluginConfig:te,globalPluginConfig:te,workingDirectoryPath:o.string().nullable(),sessionId:o.string()}),o.object({type:o.literal("discardSession"),sessionId:o.string()}),o.object({type:o.literal("callTool"),sessionId:o.string(),callId:o.string(),toolName:o.string(),parameters:Pe}),o.object({type:o.literal("abortToolCall"),sessionId:o.string(),callId:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("sessionInitialized"),sessionId:o.string(),toolDefinitions:o.array(Er)}),o.object({type:o.literal("sessionInitializationFailed"),sessionId:o.string(),error:Oe}),o.object({type:o.literal("toolCallComplete"),sessionId:o.string(),callId:o.string(),result:Pe}),o.object({type:o.literal("toolCallError"),sessionId:o.string(),callId:o.string(),error:Oe}),o.object({type:o.literal("toolCallStatus"),sessionId:o.string(),callId:o.string(),statusText:o.string()}),o.object({type:o.literal("toolCallWarn"),sessionId:o.string(),callId:o.string(),warnText:o.string()})])}).addChannelEndpoint("setGenerator",{creationParameter:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("generate"),taskId:o.string(),input:Fr,pluginConfig:te,globalPluginConfig:te,toolDefinitions:o.array(Er),workingDirectoryPath:o.string().nullable()}),o.object({type:o.literal("abort"),taskId:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("complete"),taskId:o.string()}),o.object({type:o.literal("aborted"),taskId:o.string()}),o.object({type:o.literal("error"),taskId:o.string(),error:Oe}),o.object({type:o.literal("fragmentGenerated"),taskId:o.string(),content:o.string(),opts:lp}),o.object({type:o.literal("toolCallGenerationStarted"),taskId:o.string(),toolCallId:o.string().optional()}),o.object({type:o.literal("toolCallGenerationNameReceived"),taskId:o.string(),toolName:o.string()}),o.object({type:o.literal("toolCallGenerationArgumentFragmentGenerated"),taskId:o.string(),content:o.string()}),o.object({type:o.literal("toolCallGenerationEnded"),taskId:o.string(),toolCallRequest:si}),o.object({type:o.literal("toolCallGenerationFailed"),taskId:o.string(),error:Oe})])}).addRpcEndpoint("processingHandleUpdate",{parameter:o.object({pci:o.string(),token:o.string(),update:Zw}),returns:o.void()}).addRpcEndpoint("processingHandleRequest",{parameter:o.object({pci:o.string(),token:o.string(),request:Yw}),returns:o.object({response:Xw})}).addRpcEndpoint("processingPullHistory",{parameter:o.object({pci:o.string(),token:o.string(),includeCurrent:o.boolean()}),returns:Fr}).addRpcEndpoint("processingGetOrLoadTokenSource",{parameter:o.object({pci:o.string(),token:o.string()}),returns:o.object({tokenSourceIdentifier:e1})}).addRpcEndpoint("processingHasStatus",{parameter:o.object({pci:o.string(),token:o.string()}),returns:o.boolean()}).addRpcEndpoint("processingNeedsNaming",{parameter:o.object({pci:o.string(),token:o.string()}),returns:o.boolean()}).addRpcEndpoint("processingSuggestName",{parameter:o.object({pci:o.string(),token:o.string(),name:o.string()}),returns:o.void()}).addRpcEndpoint("processingSetSenderName",{parameter:o.object({pci:o.string(),token:o.string(),name:o.string()}),returns:o.void()}).addRpcEndpoint("setConfigSchematics",{parameter:o.object({schematics:fh}),returns:o.void()}).addRpcEndpoint("setGlobalConfigSchematics",{parameter:o.object({schematics:fh}),returns:o.void()}).addRpcEndpoint("pluginInitCompleted",{parameter:o.void(),returns:o.void()})}function VS(){return new zt().addRpcEndpoint("searchModels",{parameter:o.object({opts:_p}),returns:o.object({results:o.array(l1)})}).addRpcEndpoint("getModelDownloadOptions",{parameter:o.object({modelSearchResultIdentifier:Ep}),returns:o.object({results:o.array(a1)})}).addChannelEndpoint("downloadModel",{creationParameter:o.object({downloadIdentifier:o.string()}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("downloadProgress"),update:Pa}),o.object({type:o.literal("startFinalizing")}),o.object({type:o.literal("success"),defaultIdentifier:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addChannelEndpoint("downloadArtifact",{creationParameter:o.object({artifactOwner:ni,artifactName:ii,revisionNumber:o.number().int().nullable(),path:o.string()}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("downloadProgress"),update:Pa}),o.object({type:o.literal("startFinalizing")}),o.object({type:o.literal("success")})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addRpcEndpoint("installPluginDependencies",{parameter:o.object({pluginFolder:o.string()}),returns:o.void()}).addRpcEndpoint("getLocalArtifactFiles",{parameter:o.object({path:o.string()}),returns:o.object({fileList:s1})}).addChannelEndpoint("pushArtifact",{creationParameter:o.object({path:o.string(),description:o.string().max(1e3).optional(),makePrivate:o.boolean().optional(),writeRevision:o.boolean().optional(),overrides:Pe.optional()}),toServerPacket:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("message"),message:o.string()})])}).addChannelEndpoint("ensureAuthenticated",{creationParameter:o.void(),toServerPacket:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("authenticationUrl"),url:o.string()}),o.object({type:o.literal("authenticated")})])}).addRpcEndpoint("loginWithPreAuthenticatedKeys",{parameter:o.object({keyId:o.string(),publicKey:o.string(),privateKey:o.string()}),returns:o.object({userName:o.string()})}).addChannelEndpoint("createArtifactDownloadPlan",{creationParameter:o.object({owner:ni,name:ii}),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")}),o.object({type:o.literal("commit")})]),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("planUpdated"),plan:dh}),o.object({type:o.literal("planReady"),plan:dh}),o.object({type:o.literal("downloadProgress"),update:Pa}),o.object({type:o.literal("startFinalizing")}),o.object({type:o.literal("success")})])})}function WS(){return new zt().addRpcEndpoint("listDownloadedModels",{parameter:o.void(),returns:o.array(t1)}).addChannelEndpoint("alive",{creationParameter:o.void(),toServerPacket:o.void(),toClientPacket:o.void()}).addRpcEndpoint("notify",{parameter:Bh,returns:o.void()}).addRpcEndpoint("version",{parameter:o.void(),returns:o.object({version:o.string(),build:o.number()})}).addRpcEndpoint("setExperimentFlag",{parameter:o.object({code:o.string(),value:o.boolean()}),returns:o.void()}).addRpcEndpoint("getExperimentFlags",{parameter:o.void(),returns:o.array(o.string())}).addRpcEndpoint("startHttpServer",{parameter:o.object({port:o.number().int().min(1).max(65535).optional(),cors:o.boolean().optional()}),returns:o.void()}).addRpcEndpoint("stopHttpServer",{parameter:o.void(),returns:o.void()})}function GS(t,e,r,n){let[i,s]=Ct.create(),[a,l]=Ct.create(),c=e.getApiIpcTunnel(t,{authVersion:1,clientIdentifier:r,clientPasskey:n},s,l);return fl.createFactory(i,a,c)}function ZS(t,e,r,n){return dl.createAuthenticatedWsClientTransportFactory({url:Promise.resolve(e).then(i=>`${i}/${t}`),clientIdentifier:r,clientPasskey:n})}function KS(t,e,r,n,i,s,{errorDeserializer:a,verboseErrorMessage:l}={}){let c=Yp();return c!==null?(e!==void 0&&s.debug("Ignoring wsAddress parameter when constructing the client because the client is running in a hosted environment. This is not an error."),new Ls(t,GS(r,c,n,i),{parentLogger:s,errorDeserializer:a,verboseErrorMessage:l})):new Ls(t,ZS(r,e,n,i),{parentLogger:s,errorDeserializer:a,verboseErrorMessage:l})}var hl=class{constructor(e,r,n){this.diagnosticsPort=e,this.validator=r,this.logger=new Y("Diagnostics",n)}unstable_streamLogs(e){let r=A(1);this.validator.validateMethodParamOrThrow("client.diagnostics","unstable_streamLogs","listener",o.function(),e,r);let n=this.diagnosticsPort.createChannel("streamLogs",void 0,void 0,{stack:r}),i=n.onMessage.subscribe(s=>{s.type==="log"&&e(s.log)});return()=>{i(),n.send({type:"stop"})}}};function HS(t){return o.object({identifier:o.string().optional(),config:t.optional(),signal:o.instanceof(AbortSignal).optional(),ttl:o.number().optional(),verbose:o.union([o.boolean(),_1]).optional(),onProgress:o.function().optional()})}var Ns=class{getLoadModelOptsSchema(){return this.loadModelOptsSchema===null&&(this.loadModelOptsSchema=HS(this.loadModelConfigSchema)),this.loadModelOptsSchema}constructor(e,r,n,i){this.client=e,this.port=r,this.logger=n,this.validator=i,this.loadModelOptsSchema=null}async load(e,r={}){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`,"load",["modelKey","opts"],[pn,this.getLoadModelOptsSchema()],[e,r],n);let{identifier:i,signal:s,verbose:a="info",config:l,onProgress:c}=r,u=0,{promise:h,resolve:f,reject:d}=re(),p=typeof a=="boolean"?"info":a,m=Date.now();a&&this.logger.logAtLevel(p,j`
310
+ `}receivedKeepAliveAck(e){}async callRpc(e,r,{stack:n}={}){let i=this.backendInterface.getRpcEndpoint(e);if(i===void 0)throw new Error(`No Rpc endpoint with name ${e}`);let s=i.parameter.parse(r),a=fn(i.serialization,s),l=this.nextChannelId;this.nextChannelId++;let{promise:c,resolve:u,reject:h}=re();return n=n??A(1),this.ongoingRpcs.set(l,{endpoint:i,stack:n,resolve:u,reject:h}),this.transport.send({type:"rpcCall",endpoint:e,callId:l,parameter:a}),this.updateOpenCommunicationsCount(),await c}createChannel(e,r,n,{stack:i}={}){let s=this.backendInterface.getChannelEndpoint(e);if(s===void 0)throw new Error(`No channel endpoint with name ${e}`);let a=s.creationParameter.parse(r),l=fn(s.serialization,a),c=this.nextChannelId;this.nextChannelId++,this.transport.send({type:"channelCreate",endpoint:e,channelId:c,creationParameter:l}),i=i??A(1);let u={endpoint:s,stack:i,...rl.create(h=>{let f=s.toServerPacket.parse(h),d=fn(s.serialization,f);this.transport.send({type:"channelSend",channelId:c,message:d})})};return n!==void 0&&u.channel.onMessage.subscribe(n),this.openChannels.set(c,u),this.updateOpenCommunicationsCount(),u.channel}createSignal(e,r,{stack:n}={}){let i=this.backendInterface.getSignalEndpoint(e);if(i===void 0)throw new Error(`No signal endpoint with name ${e}`);let s=i.creationParameter.parse(r),a=fn(i.serialization,s);n=n??A(1);let l=Ze.createWithoutInitialValue((c,u)=>{let h=this.nextSubscribeId;return this.nextSubscribeId++,this.transport.send({type:"signalSubscribe",endpoint:e,subscribeId:h,creationParameter:a}),this.openSignalSubscriptions.set(h,{endpoint:i,getValue:()=>l.get(),receivedPatches:c.withValueAndPatches,errored:u,stack:n}),this.updateOpenCommunicationsCount(),()=>{this.transport.send({type:"signalUnsubscribe",subscribeId:h}),this.openSignalSubscriptions.delete(h)}});return l}createWritableSignal(e,r,{stack:n}={}){let i=this.backendInterface.getWritableSignalEndpoint(e);if(i===void 0)throw new Error(`No writable signal endpoint with name ${e}`);let s=i.creationParameter.parse(r),a=fn(i.serialization,s);n=n??A(1);let l=null,c=(f,d,p)=>l===null?(console.warn("writeUpstream called when not subscribed"),!1):this.openWritableSignalSubscriptions.get(l)?.firstUpdateReceived?(this.transport.send({type:"writableSignalUpdate",subscribeId:l,patches:d.map(g=>fn(i.serialization,g)),tags:p}),!0):(console.warn("writeUpstream called before the first update is received"),!1),[u,h]=qa.createWithoutInitialValue((f,d)=>{let p=this.nextWritableSubscribeId;return l=p,this.nextWritableSubscribeId++,this.transport.send({type:"writableSignalSubscribe",endpoint:e,subscribeId:p,creationParameter:a}),this.openWritableSignalSubscriptions.set(p,{endpoint:i,getValue:()=>u.getPessimistic(),receivedPatches:f.withValueAndPatches,firstUpdateReceived:!1,errored:d,stack:n}),this.updateOpenCommunicationsCount(),()=>{l=null,this.transport.send({type:"writableSignalUnsubscribe",subscribeId:p}),this.openWritableSignalSubscriptions.delete(p)}},c);return[u,h]}async[Symbol.asyncDispose](){await this.transport[Symbol.asyncDispose]()}},hl=class t extends Bs{constructor(e,r,n,i,s,a){super(),this.sendMessage=n,this.receivedMessage=i,this.errored=s,this.closed=!1,this.logger=new Y("GenericClientTransport",a),e.subscribe(l=>{let c;try{c=this.parseIncomingMessage(l)}catch{this.logger.warn("Received invalid message from server:",l);return}this.receivedMessage(c)}),r.subscribeOnce(()=>{this.closed||(this.closed=!0,this.errored(new Error("Server closed the connection")))})}static createFactory(e,r,n){return(i,s,a)=>new t(e,r,n,i,s,a)}sendViaTransport(e){this.sendMessage(e)}};function Jp(){let t;try{t=window}catch{t=void 0}return t!==void 0&&t.lmsHostedEnv!==void 0?t.lmsHostedEnv:null}function Qp(t,e){let r=t,n=e;return new zt().addChannelEndpoint("loadModel",{creationParameter:o.object({modelKey:o.string(),identifier:o.string().optional(),ttlMs:o.number().int().min(1).optional(),loadConfigStack:Is}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("resolved"),info:n,ambiguous:o.array(o.string()).optional()}),o.object({type:o.literal("progress"),progress:o.number()}),o.object({type:o.literal("success"),info:r})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addRpcEndpoint("unloadModel",{parameter:o.object({identifier:o.string()}),returns:o.void()}).addRpcEndpoint("listLoaded",{parameter:o.undefined(),returns:o.array(r)}).addRpcEndpoint("getModelInfo",{parameter:o.object({specifier:st,throwIfNotFound:o.boolean()}),returns:r.optional()}).addRpcEndpoint("getLoadConfig",{parameter:o.object({specifier:st}),returns:te}).addChannelEndpoint("getOrLoad",{creationParameter:o.object({identifier:o.string(),loadTtlMs:o.number().int().min(1).optional(),loadConfigStack:Is}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("alreadyLoaded"),info:r}),o.object({type:o.literal("startLoading"),identifier:o.string(),info:n}),o.object({type:o.literal("unloadingOtherJITModel"),info:n1}),o.object({type:o.literal("loadProgress"),progress:o.number()}),o.object({type:o.literal("loadSuccess"),info:r})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])})}function $S(){return new zt().addChannelEndpoint("streamLogs",{creationParameter:o.void(),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("stop")})]),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("log"),log:dw})])})}function US(){return Qp(Zh,Gh).addRpcEndpoint("embedString",{parameter:o.object({modelSpecifier:st,inputString:o.string()}),returns:o.object({embedding:o.array(o.number())})}).addRpcEndpoint("tokenize",{parameter:o.object({specifier:st,inputString:o.string()}),returns:o.object({tokens:o.array(o.number())})}).addRpcEndpoint("countTokens",{parameter:o.object({specifier:st,inputString:o.string()}),returns:o.object({tokenCount:o.number().int()})})}function qS(){return new zt().addRpcEndpoint("getLocalFileAbsolutePath",{parameter:o.object({fileName:o.string()}),returns:o.object({path:o.string()})}).addRpcEndpoint("uploadFileBase64",{parameter:o.object({name:o.string(),contentBase64:o.string()}),returns:o.object({identifier:o.string(),fileType:Nh,sizeBytes:o.number().int()})}).addChannelEndpoint("retrieve",{creationParameter:o.object({query:o.string(),fileIdentifiers:o.array(o.string()),config:te}),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("stop")})]),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("onFileProcessList"),indices:o.array(o.number().int())}),o.object({type:o.literal("onFileProcessingStart"),index:o.number().int()}),o.object({type:o.literal("onFileProcessingEnd"),index:o.number().int()}),o.object({type:o.literal("onFileProcessingStepStart"),index:o.number().int(),step:Aa}),o.object({type:o.literal("onFileProcessingStepProgress"),index:o.number().int(),step:Aa,progress:o.number()}),o.object({type:o.literal("onFileProcessingStepEnd"),index:o.number().int(),step:Aa}),o.object({type:o.literal("onSearchingStart")}),o.object({type:o.literal("onSearchingEnd")}),o.object({type:o.literal("result"),result:d1})])}).addChannelEndpoint("parseDocument",{creationParameter:o.object({fileIdentifier:o.string(),parseOpts:Hh}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("parserLoaded"),parser:Va}),o.object({type:o.literal("progress"),progress:o.number()}),o.object({type:o.literal("result"),content:o.string(),parser:Va})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addRpcEndpoint("getDocumentParsingLibrary",{parameter:o.object({fileIdentifier:o.string()}),returns:o.object({library:o.string(),version:o.string()})})}function zS(){return Qp(Wa,rp).addChannelEndpoint("predict",{creationParameter:o.object({modelSpecifier:st,history:Fr,predictionConfigStack:Is,fuzzyPresetIdentifier:o.string().optional(),ignoreServerSessionConfig:o.boolean().optional()}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("fragment"),fragment:lp,logprobs:o.array(o.array(o.object({text:o.string(),logprob:o.number()}))).optional()}),o.object({type:o.literal("promptProcessingProgress"),progress:o.number()}),o.object({type:o.literal("toolCallGenerationStart"),toolCallId:o.string().optional()}),o.object({type:o.literal("toolCallGenerationNameReceived"),name:o.string()}),o.object({type:o.literal("toolCallGenerationArgumentFragmentGenerated"),content:o.string()}),o.object({type:o.literal("toolCallGenerationEnd"),toolCallRequest:si,rawContent:o.string().optional()}),o.object({type:o.literal("toolCallGenerationFailed"),error:Ie,rawContent:o.string().optional()}),o.object({type:o.literal("success"),stats:up,modelInfo:Wa,loadModelConfig:te,predictionConfig:te})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addRpcEndpoint("applyPromptTemplate",{parameter:o.object({specifier:st,history:Fr,predictionConfigStack:Is,opts:ep}),returns:o.object({formatted:o.string()})}).addRpcEndpoint("tokenize",{parameter:o.object({specifier:st,inputString:o.string()}),returns:o.object({tokens:o.array(o.number())})}).addRpcEndpoint("countTokens",{parameter:o.object({specifier:st,inputString:o.string()}),returns:o.object({tokenCount:o.number().int()})}).addRpcEndpoint("preloadDraftModel",{parameter:o.object({specifier:st,draftModelKey:o.string()}),returns:o.void()})}function VS(){return new zt().addChannelEndpoint("startToolUseSession",{creationParameter:o.object({pluginIdentifier:o.string(),pluginConfigSpecifier:lh}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("sessionReady"),toolDefinitions:o.array(Er)}),o.object({type:o.literal("toolCallComplete"),callId:o.number(),result:Pe}),o.object({type:o.literal("toolCallError"),callId:o.number(),error:Ie}),o.object({type:o.literal("toolCallStatus"),callId:o.number(),statusText:o.string()}),o.object({type:o.literal("toolCallWarn"),callId:o.number(),warnText:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("callTool"),callId:o.number(),name:o.string(),arguments:Pe}),o.object({type:o.literal("abortToolCall"),callId:o.number()}),o.object({type:o.literal("discardSession")})])}).addChannelEndpoint("generateWithGenerator",{creationParameter:o.object({pluginIdentifier:o.string(),pluginConfigSpecifier:lh,tools:o.array(Er),history:Fr}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("fragment"),fragment:lp}),o.object({type:o.literal("promptProcessingProgress"),progress:o.number()}),o.object({type:o.literal("toolCallGenerationStart"),toolCallId:o.string().optional()}),o.object({type:o.literal("toolCallGenerationNameReceived"),name:o.string()}),o.object({type:o.literal("toolCallGenerationArgumentFragmentGenerated"),content:o.string()}),o.object({type:o.literal("toolCallGenerationEnd"),toolCallRequest:si}),o.object({type:o.literal("toolCallGenerationFailed")}),o.object({type:o.literal("success")})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addChannelEndpoint("registerDevelopmentPlugin",{creationParameter:o.object({manifest:Kl}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("ready"),clientIdentifier:o.string(),clientPasskey:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("end")})])}).addRpcEndpoint("reindexPlugins",{parameter:o.void(),returns:o.void()}).addChannelEndpoint("setPromptPreprocessor",{creationParameter:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("preprocess"),taskId:o.string(),input:kr,config:te,pluginConfig:te,globalPluginConfig:te,workingDirectoryPath:o.string().nullable(),enabledPluginInfos:o.array(ch),pci:o.string(),token:o.string()}),o.object({type:o.literal("abort"),taskId:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("complete"),taskId:o.string(),processed:kr}),o.object({type:o.literal("aborted"),taskId:o.string()}),o.object({type:o.literal("error"),taskId:o.string(),error:Ie})])}).addChannelEndpoint("setPredictionLoopHandler",{creationParameter:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("handlePredictionLoop"),taskId:o.string(),config:te,pluginConfig:te,globalPluginConfig:te,workingDirectoryPath:o.string().nullable(),enabledPluginInfos:o.array(ch),pci:o.string(),token:o.string()}),o.object({type:o.literal("abort"),taskId:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("complete"),taskId:o.string()}),o.object({type:o.literal("aborted"),taskId:o.string()}),o.object({type:o.literal("error"),taskId:o.string(),error:Ie})])}).addChannelEndpoint("setToolsProvider",{creationParameter:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("initSession"),pluginConfig:te,globalPluginConfig:te,workingDirectoryPath:o.string().nullable(),sessionId:o.string()}),o.object({type:o.literal("discardSession"),sessionId:o.string()}),o.object({type:o.literal("callTool"),sessionId:o.string(),callId:o.string(),toolName:o.string(),parameters:Pe}),o.object({type:o.literal("abortToolCall"),sessionId:o.string(),callId:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("sessionInitialized"),sessionId:o.string(),toolDefinitions:o.array(Er)}),o.object({type:o.literal("sessionInitializationFailed"),sessionId:o.string(),error:Ie}),o.object({type:o.literal("toolCallComplete"),sessionId:o.string(),callId:o.string(),result:Pe}),o.object({type:o.literal("toolCallError"),sessionId:o.string(),callId:o.string(),error:Ie}),o.object({type:o.literal("toolCallStatus"),sessionId:o.string(),callId:o.string(),statusText:o.string()}),o.object({type:o.literal("toolCallWarn"),sessionId:o.string(),callId:o.string(),warnText:o.string()})])}).addChannelEndpoint("setGenerator",{creationParameter:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("generate"),taskId:o.string(),input:Fr,pluginConfig:te,globalPluginConfig:te,toolDefinitions:o.array(Er),workingDirectoryPath:o.string().nullable()}),o.object({type:o.literal("abort"),taskId:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("complete"),taskId:o.string()}),o.object({type:o.literal("aborted"),taskId:o.string()}),o.object({type:o.literal("error"),taskId:o.string(),error:Ie}),o.object({type:o.literal("fragmentGenerated"),taskId:o.string(),content:o.string(),opts:cp}),o.object({type:o.literal("toolCallGenerationStarted"),taskId:o.string(),toolCallId:o.string().optional()}),o.object({type:o.literal("toolCallGenerationNameReceived"),taskId:o.string(),toolName:o.string()}),o.object({type:o.literal("toolCallGenerationArgumentFragmentGenerated"),taskId:o.string(),content:o.string()}),o.object({type:o.literal("toolCallGenerationEnded"),taskId:o.string(),toolCallRequest:si}),o.object({type:o.literal("toolCallGenerationFailed"),taskId:o.string(),error:Ie})])}).addRpcEndpoint("processingHandleUpdate",{parameter:o.object({pci:o.string(),token:o.string(),update:Kw}),returns:o.void()}).addRpcEndpoint("processingHandleRequest",{parameter:o.object({pci:o.string(),token:o.string(),request:Jw}),returns:o.object({response:e1})}).addRpcEndpoint("processingPullHistory",{parameter:o.object({pci:o.string(),token:o.string(),includeCurrent:o.boolean()}),returns:Fr}).addRpcEndpoint("processingGetOrLoadTokenSource",{parameter:o.object({pci:o.string(),token:o.string()}),returns:o.object({tokenSourceIdentifier:t1})}).addRpcEndpoint("processingHasStatus",{parameter:o.object({pci:o.string(),token:o.string()}),returns:o.boolean()}).addRpcEndpoint("processingNeedsNaming",{parameter:o.object({pci:o.string(),token:o.string()}),returns:o.boolean()}).addRpcEndpoint("processingSuggestName",{parameter:o.object({pci:o.string(),token:o.string(),name:o.string()}),returns:o.void()}).addRpcEndpoint("processingSetSenderName",{parameter:o.object({pci:o.string(),token:o.string(),name:o.string()}),returns:o.void()}).addRpcEndpoint("setConfigSchematics",{parameter:o.object({schematics:hh}),returns:o.void()}).addRpcEndpoint("setGlobalConfigSchematics",{parameter:o.object({schematics:hh}),returns:o.void()}).addRpcEndpoint("pluginInitCompleted",{parameter:o.void(),returns:o.void()})}function WS(){return new zt().addRpcEndpoint("searchModels",{parameter:o.object({opts:xp}),returns:o.object({results:o.array(c1)})}).addRpcEndpoint("getModelDownloadOptions",{parameter:o.object({modelSearchResultIdentifier:_p}),returns:o.object({results:o.array(l1)})}).addChannelEndpoint("downloadModel",{creationParameter:o.object({downloadIdentifier:o.string()}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("downloadProgress"),update:Ta}),o.object({type:o.literal("startFinalizing")}),o.object({type:o.literal("success"),defaultIdentifier:o.string()})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addChannelEndpoint("downloadArtifact",{creationParameter:o.object({artifactOwner:ni,artifactName:ii,revisionNumber:o.number().int().nullable(),path:o.string()}),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("downloadProgress"),update:Ta}),o.object({type:o.literal("startFinalizing")}),o.object({type:o.literal("success")})]),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")})])}).addRpcEndpoint("installPluginDependencies",{parameter:o.object({pluginFolder:o.string()}),returns:o.void()}).addRpcEndpoint("getLocalArtifactFiles",{parameter:o.object({path:o.string()}),returns:o.object({fileList:o1})}).addChannelEndpoint("pushArtifact",{creationParameter:o.object({path:o.string(),description:o.string().max(1e3).optional(),makePrivate:o.boolean().optional(),writeRevision:o.boolean().optional(),overrides:Pe.optional()}),toServerPacket:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("message"),message:o.string()})])}).addChannelEndpoint("ensureAuthenticated",{creationParameter:o.void(),toServerPacket:o.void(),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("authenticationUrl"),url:o.string()}),o.object({type:o.literal("authenticated")})])}).addRpcEndpoint("loginWithPreAuthenticatedKeys",{parameter:o.object({keyId:o.string(),publicKey:o.string(),privateKey:o.string()}),returns:o.object({userName:o.string()})}).addChannelEndpoint("createArtifactDownloadPlan",{creationParameter:o.object({owner:ni,name:ii}),toServerPacket:o.discriminatedUnion("type",[o.object({type:o.literal("cancel")}),o.object({type:o.literal("commit")})]),toClientPacket:o.discriminatedUnion("type",[o.object({type:o.literal("planUpdated"),plan:fh}),o.object({type:o.literal("planReady"),plan:fh}),o.object({type:o.literal("downloadProgress"),update:Ta}),o.object({type:o.literal("startFinalizing")}),o.object({type:o.literal("success")})])})}function GS(){return new zt().addRpcEndpoint("listDownloadedModels",{parameter:o.void(),returns:o.array(r1)}).addChannelEndpoint("alive",{creationParameter:o.void(),toServerPacket:o.void(),toClientPacket:o.void()}).addRpcEndpoint("notify",{parameter:Lh,returns:o.void()}).addRpcEndpoint("version",{parameter:o.void(),returns:o.object({version:o.string(),build:o.number()})}).addRpcEndpoint("setExperimentFlag",{parameter:o.object({code:o.string(),value:o.boolean()}),returns:o.void()}).addRpcEndpoint("getExperimentFlags",{parameter:o.void(),returns:o.array(o.string())}).addRpcEndpoint("startHttpServer",{parameter:o.object({port:o.number().int().min(1).max(65535).optional(),cors:o.boolean().optional()}),returns:o.void()}).addRpcEndpoint("stopHttpServer",{parameter:o.void(),returns:o.void()})}function ZS(t,e,r,n){let[i,s]=Et.create(),[a,l]=Et.create(),c=e.getApiIpcTunnel(t,{authVersion:1,clientIdentifier:r,clientPasskey:n},s,l);return hl.createFactory(i,a,c)}function KS(t,e,r,n){return fl.createAuthenticatedWsClientTransportFactory({url:Promise.resolve(e).then(i=>`${i}/${t}`),clientIdentifier:r,clientPasskey:n})}function HS(t,e,r,n,i,s,{errorDeserializer:a,verboseErrorMessage:l}={}){let c=Jp();return c!==null?(e!==void 0&&s.debug("Ignoring wsAddress parameter when constructing the client because the client is running in a hosted environment. This is not an error."),new Ls(t,ZS(r,c,n,i),{parentLogger:s,errorDeserializer:a,verboseErrorMessage:l})):new Ls(t,KS(r,e,n,i),{parentLogger:s,errorDeserializer:a,verboseErrorMessage:l})}var pl=class{constructor(e,r,n){this.diagnosticsPort=e,this.validator=r,this.logger=new Y("Diagnostics",n)}unstable_streamLogs(e){let r=A(1);this.validator.validateMethodParamOrThrow("client.diagnostics","unstable_streamLogs","listener",o.function(),e,r);let n=this.diagnosticsPort.createChannel("streamLogs",void 0,void 0,{stack:r}),i=n.onMessage.subscribe(s=>{s.type==="log"&&e(s.log)});return()=>{i(),n.send({type:"stop"})}}};function YS(t){return o.object({identifier:o.string().optional(),config:t.optional(),signal:o.instanceof(AbortSignal).optional(),ttl:o.number().optional(),verbose:o.union([o.boolean(),x1]).optional(),onProgress:o.function().optional()})}var Ns=class{getLoadModelOptsSchema(){return this.loadModelOptsSchema===null&&(this.loadModelOptsSchema=YS(this.loadModelConfigSchema)),this.loadModelOptsSchema}constructor(e,r,n,i){this.client=e,this.port=r,this.logger=n,this.validator=i,this.loadModelOptsSchema=null}async load(e,r={}){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`,"load",["modelKey","opts"],[pn,this.getLoadModelOptsSchema()],[e,r],n);let{identifier:i,signal:s,verbose:a="info",config:l,onProgress:c}=r,u=0,{promise:h,resolve:f,reject:d}=re(),p=typeof a=="boolean"?"info":a,m=Date.now();a&&this.logger.logAtLevel(p,j`
311
311
  Verbose logging is enabled. To hide progress logs, set the "verbose" option to false in
312
312
  client.llm.load.
313
- `);let g=e,y=this.port.createChannel("loadModel",{modelKey:e,identifier:i,ttlMs:r.ttl===void 0?void 0:r.ttl*1e3,loadConfigStack:mh("apiOverride",this.loadConfigToKVConfig(l??this.defaultLoadConfig))},b=>{switch(b.type){case"resolved":{g=b.info.modelKey,b.ambiguous!==void 0&&this.logger.warn(j`
313
+ `);let g=e,y=this.port.createChannel("loadModel",{modelKey:e,identifier:i,ttlMs:r.ttl===void 0?void 0:r.ttl*1e3,loadConfigStack:gh("apiOverride",this.loadConfigToKVConfig(l??this.defaultLoadConfig))},b=>{switch(b.type){case"resolved":{g=b.info.modelKey,b.ambiguous!==void 0&&this.logger.warn(j`
314
314
  Multiple models found for key ${e}:
315
315
 
316
316
  ${b.ambiguous.map(D=>` - ${D}`).join(`
@@ -321,10 +321,10 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
321
321
  Start loading model ${g}...
322
322
  `);break}case"success":{a&&this.logger.logAtLevel(p,j`
323
323
  Successfully loaded model ${g} in ${Date.now()-m}ms
324
- `),f(this.createDomainSpecificModel(this.port,b.info,this.validator,this.logger));break}case"progress":{let{progress:D}=b;if(c!==void 0)L(this.logger,"onProgress",c,[D]);else if(a){let v=Date.now();if(v-u>500||D===1){let S=(D*100).toFixed(1);this.logger.logAtLevel(p,`Loading the model, progress: ${S}%`),u=v}}}}},{stack:n});return y.onError.subscribeOnce(d),s!==void 0&&(s.aborted?(y.send({type:"cancel"}),d(s.reason)):s.addEventListener("abort",()=>{y.send({type:"cancel"}),d(s.reason)},{once:!0})),await h}unload(e){let r=A(1);return this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"unload","identifier",pn,e,r),this.port.callRpc("unloadModel",{identifier:e},{stack:r})}async listLoaded(){let e=A(1);return(await this.port.callRpc("listLoaded",void 0,{stack:e})).map(n=>this.createDomainSpecificModel(this.port,n,this.validator,this.logger))}async getAny(e){let r=await this.port.callRpc("getModelInfo",{specifier:{type:"query",query:{}},throwIfNotFound:!0},{stack:e});if(r===void 0)throw new Error("Backend should have thrown.");return this.createDomainSpecificModel(this.port,r,this.validator,new Y("LLM",this.logger))}createDynamicHandle(e){let r=A(1);this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"createDynamicHandle","param",o.union([pn,Hl]),e,r);let n;if(typeof e=="string"?n={identifier:e}:n=e,n.path?.includes("\\"))throw Ee(j`
324
+ `),f(this.createDomainSpecificModel(this.port,b.info,this.validator,this.logger));break}case"progress":{let{progress:D}=b;if(c!==void 0)L(this.logger,"onProgress",c,[D]);else if(a){let v=Date.now();if(v-u>500||D===1){let S=(D*100).toFixed(1);this.logger.logAtLevel(p,`Loading the model, progress: ${S}%`),u=v}}}}},{stack:n});return y.onError.subscribeOnce(d),s!==void 0&&(s.aborted?(y.send({type:"cancel"}),d(s.reason)):s.addEventListener("abort",()=>{y.send({type:"cancel"}),d(s.reason)},{once:!0})),await h}unload(e){let r=A(1);return this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"unload","identifier",pn,e,r),this.port.callRpc("unloadModel",{identifier:e},{stack:r})}async listLoaded(){let e=A(1);return(await this.port.callRpc("listLoaded",void 0,{stack:e})).map(n=>this.createDomainSpecificModel(this.port,n,this.validator,this.logger))}async getAny(e){let r=await this.port.callRpc("getModelInfo",{specifier:{type:"query",query:{}},throwIfNotFound:!0},{stack:e});if(r===void 0)throw new Error("Backend should have thrown.");return this.createDomainSpecificModel(this.port,r,this.validator,new Y("LLM",this.logger))}createDynamicHandle(e){let r=A(1);this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"createDynamicHandle","param",o.union([pn,Yl]),e,r);let n;if(typeof e=="string"?n={identifier:e}:n=e,n.path?.includes("\\"))throw Ee(j`
325
325
  Model path should not contain backslashes, even if you are on Windows. Use forward
326
326
  slashes instead.
327
- `,r);return this.createDomainDynamicHandle(this.port,{type:"query",query:n},this.validator,new Y("DynamicHandle",this.logger))}createDynamicHandleFromInstanceReference(e){let r=A(1);return this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"createDynamicHandleFromInstanceReference","instanceReference",o.string(),e,r),this.createDomainDynamicHandle(this.port,{type:"instanceReference",instanceReference:e},this.validator,new Y("DynamicHandle",this.logger))}async model(e,r={}){let n=A(1);if(e===void 0)return await this.getAny(n);[e,r]=this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`,"model",["modelKey","opts"],[pn,this.getLoadModelOptsSchema()],[e,r],n);let{identifier:i,signal:s,verbose:a="info",config:l,onProgress:c}=r;if(i!==void 0)throw new Error("The identifier option is not allowed when using `.model`.");let u=0,{promise:h,resolve:f,reject:d}=re(),p=typeof a=="boolean"?"info":a,m=Date.now(),g=this.port.createChannel("getOrLoad",{identifier:e,loadTtlMs:r.ttl===void 0?void 0:r.ttl*1e3,loadConfigStack:mh("apiOverride",this.loadConfigToKVConfig(l??this.defaultLoadConfig))},y=>{switch(y.type){case"alreadyLoaded":return f(this.createDomainSpecificModel(this.port,y.info,this.validator,this.logger));case"unloadingOtherJITModel":{a&&this.logger.logAtLevel(p,j`
327
+ `,r);return this.createDomainDynamicHandle(this.port,{type:"query",query:n},this.validator,new Y("DynamicHandle",this.logger))}createDynamicHandleFromInstanceReference(e){let r=A(1);return this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"createDynamicHandleFromInstanceReference","instanceReference",o.string(),e,r),this.createDomainDynamicHandle(this.port,{type:"instanceReference",instanceReference:e},this.validator,new Y("DynamicHandle",this.logger))}async model(e,r={}){let n=A(1);if(e===void 0)return await this.getAny(n);[e,r]=this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`,"model",["modelKey","opts"],[pn,this.getLoadModelOptsSchema()],[e,r],n);let{identifier:i,signal:s,verbose:a="info",config:l,onProgress:c}=r;if(i!==void 0)throw new Error("The identifier option is not allowed when using `.model`.");let u=0,{promise:h,resolve:f,reject:d}=re(),p=typeof a=="boolean"?"info":a,m=Date.now(),g=this.port.createChannel("getOrLoad",{identifier:e,loadTtlMs:r.ttl===void 0?void 0:r.ttl*1e3,loadConfigStack:gh("apiOverride",this.loadConfigToKVConfig(l??this.defaultLoadConfig))},y=>{switch(y.type){case"alreadyLoaded":return f(this.createDomainSpecificModel(this.port,y.info,this.validator,this.logger));case"unloadingOtherJITModel":{a&&this.logger.logAtLevel(p,j`
328
328
  Unloading other JIT model ${y.info.modelKey}. (You can disable this behavior
329
329
  by going to LM Studio -> Settings -> Developer -> Turn OFF JIT models auto-evict)
330
330
  `);break}case"startLoading":{a&&(this.logger.logAtLevel(p,j`
@@ -334,13 +334,13 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
334
334
  Model ${e} is not loaded. Start loading...
335
335
  `));break}case"loadProgress":{let{progress:b}=y;if(c!==void 0)L(this.logger,"onProgress",c,[b]);else if(a){let D=Date.now();if(D-u>500||b===1){let v=(b*100).toFixed(1);this.logger.logAtLevel(p,`Loading the model, progress: ${v}%`),u=D}}break}case"loadSuccess":a&&this.logger.logAtLevel(p,j`
336
336
  Successfully loaded model ${y.info.modelKey} in ${Date.now()-m}ms
337
- `),f(this.createDomainSpecificModel(this.port,y.info,this.validator,this.logger))}},{stack:n});return g.onError.subscribeOnce(d),s?.addEventListener("abort",()=>{g.send({type:"cancel"}),d(s.reason)}),await h}};function Hn(t,e,r){if(t!==void 0)return t===e?{checked:!1,value:r}:{checked:!0,value:t}}var $s=class{constructor(e,r){this.port=e,this.specifier=r}async getModelInfo(){let e=await this.port.callRpc("getModelInfo",{specifier:this.specifier,throwIfNotFound:!1},{stack:A(1)});if(e!==void 0)return e}async getLoadConfig(e){return await this.port.callRpc("getLoadConfig",{specifier:this.specifier},{stack:e})}},di=class extends $s{constructor(e,r,n,i=new Y("EmbeddingModel")){super(e,r),this.validator=n,this.logger=i}async embed(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("client.embedding","embed","inputString",o.string().or(o.array(o.string())),e,r),Array.isArray(e)?await Promise.all(e.map(n=>this.port.callRpc("embedString",{inputString:n,modelSpecifier:this.specifier},{stack:r}))):await this.port.callRpc("embedString",{inputString:e,modelSpecifier:this.specifier},{stack:r})}async getContextLength(){let e=A(1),r=await this.getLoadConfig(e);return Rp.access(r,"contextLength")}async getEvalBatchSize(){let e=A(1),r=await this.getLoadConfig(e);return qt.access(r,"embedding.load.llama.evalBatchSize")}async tokenize(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("model","tokenize","inputString",o.string().or(o.array(o.string())),e,r),Array.isArray(e)?(await Promise.all(e.map(n=>this.port.callRpc("tokenize",{specifier:this.specifier,inputString:n},{stack:r})))).map(n=>n.tokens):(await this.port.callRpc("tokenize",{specifier:this.specifier,inputString:e},{stack:r})).tokens}async countTokens(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("model","countTokens","inputString",o.string(),e,r),(await this.port.callRpc("countTokens",{specifier:this.specifier,inputString:e},{stack:r})).tokenCount}},pl=class extends di{constructor(e,r,n,i=new Y("EmbeddingModel")){let s={type:"instanceReference",instanceReference:r.instanceReference};super(e,s,n,i),this.identifier=r.identifier,this.path=r.path,this.modelKey=r.modelKey,this.format=r.format,this.displayName=r.displayName,this.sizeBytes=r.sizeBytes}async unload(){let e=A(1);await this.port.callRpc("unloadModel",{identifier:this.identifier},{stack:e})}async getModelInfo(){let e=await super.getModelInfo();if(e===void 0){let r=A(1);throw Ee("This model has already been unloaded",r)}return e}},ml=class extends Ns{constructor(){super(...arguments),this.namespace="embedding",this.defaultLoadConfig={},this.loadModelConfigSchema=yw}loadConfigToKVConfig(e){return N1.buildPartialConfig({"llama.acceleration.offloadRatio":e.gpu?.ratio,"load.gpuSplitConfig":Hh(e.gpu),contextLength:e.contextLength,"llama.ropeFrequencyBase":Hn(e.ropeFrequencyBase,0,0),"llama.ropeFrequencyScale":Hn(e.ropeFrequencyScale,0,0),"llama.keepModelInMemory":e.keepModelInMemory,"llama.tryMmap":e.tryMmap})}createDomainSpecificModel(e,r,n,i){return new pl(e,r,n,i)}createDomainDynamicHandle(e,r,n,i){return new di(e,r,n,i)}},YS=Kh.extend({onProgress:o.function().optional(),signal:o.instanceof(AbortSignal).optional()}),JS=o.object({onFileProcessList:o.function().optional(),onFileProcessingStart:o.function().optional(),onFileProcessingEnd:o.function().optional(),onFileProcessingStepStart:o.function().optional(),onFileProcessingStepProgress:o.function().optional(),onFileProcessingStepEnd:o.function().optional(),onSearchingStart:o.function().optional(),onSearchingEnd:o.function().optional(),verbose:o.union([o.boolean(),o.string()]).optional()}),QS=o.object({chunkingMethod:xp.optional(),limit:o.number().int().optional(),embeddingModel:o.instanceof(di).optional(),databasePath:o.string().optional(),signal:o.instanceof(AbortSignal).optional(),...JS.shape});function XS(t){switch(t){case"loading":return"Loading";case"chunking":return"Chunking";case"embedding":return"Embedding";default:{let e=t;throw new Error(`Unexpected processing step: ${e}`)}}}var gl=class{constructor(e,r,n){this.filesPort=e,this.validator=r,this.logger=new Y("File",n)}async getLocalFileAbsolutePath(e,r){return await this.filesPort.callRpc("getLocalFileAbsolutePath",{fileName:e},{stack:r})}createFileHandleFromChatMessagePartFileData(e){return new Ce(this,e.identifier,e.fileType,e.sizeBytes,e.name)}async prepareImage(e){let r=await(0,st.readFileAsBase64)(e);if(r.success===!1)throw new Error(j`
337
+ `),f(this.createDomainSpecificModel(this.port,y.info,this.validator,this.logger))}},{stack:n});return g.onError.subscribeOnce(d),s?.addEventListener("abort",()=>{g.send({type:"cancel"}),d(s.reason)}),await h}};function Hn(t,e,r){if(t!==void 0)return t===e?{checked:!1,value:r}:{checked:!0,value:t}}var $s=class{constructor(e,r){this.port=e,this.specifier=r}async getModelInfo(){let e=await this.port.callRpc("getModelInfo",{specifier:this.specifier,throwIfNotFound:!1},{stack:A(1)});if(e!==void 0)return e}async getLoadConfig(e){return await this.port.callRpc("getLoadConfig",{specifier:this.specifier},{stack:e})}},di=class extends $s{constructor(e,r,n,i=new Y("EmbeddingModel")){super(e,r),this.validator=n,this.logger=i}async embed(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("client.embedding","embed","inputString",o.string().or(o.array(o.string())),e,r),Array.isArray(e)?await Promise.all(e.map(n=>this.port.callRpc("embedString",{inputString:n,modelSpecifier:this.specifier},{stack:r}))):await this.port.callRpc("embedString",{inputString:e,modelSpecifier:this.specifier},{stack:r})}async getContextLength(){let e=A(1),r=await this.getLoadConfig(e);return Mp.access(r,"contextLength")}async getEvalBatchSize(){let e=A(1),r=await this.getLoadConfig(e);return qt.access(r,"embedding.load.llama.evalBatchSize")}async tokenize(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("model","tokenize","inputString",o.string().or(o.array(o.string())),e,r),Array.isArray(e)?(await Promise.all(e.map(n=>this.port.callRpc("tokenize",{specifier:this.specifier,inputString:n},{stack:r})))).map(n=>n.tokens):(await this.port.callRpc("tokenize",{specifier:this.specifier,inputString:e},{stack:r})).tokens}async countTokens(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("model","countTokens","inputString",o.string(),e,r),(await this.port.callRpc("countTokens",{specifier:this.specifier,inputString:e},{stack:r})).tokenCount}},ml=class extends di{constructor(e,r,n,i=new Y("EmbeddingModel")){let s={type:"instanceReference",instanceReference:r.instanceReference};super(e,s,n,i),this.identifier=r.identifier,this.path=r.path,this.modelKey=r.modelKey,this.format=r.format,this.displayName=r.displayName,this.sizeBytes=r.sizeBytes}async unload(){let e=A(1);await this.port.callRpc("unloadModel",{identifier:this.identifier},{stack:e})}async getModelInfo(){let e=await super.getModelInfo();if(e===void 0){let r=A(1);throw Ee("This model has already been unloaded",r)}return e}},gl=class extends Ns{constructor(){super(...arguments),this.namespace="embedding",this.defaultLoadConfig={},this.loadModelConfigSchema=bw}loadConfigToKVConfig(e){return $1.buildPartialConfig({"llama.acceleration.offloadRatio":e.gpu?.ratio,"load.gpuSplitConfig":Yh(e.gpu),contextLength:e.contextLength,"llama.ropeFrequencyBase":Hn(e.ropeFrequencyBase,0,0),"llama.ropeFrequencyScale":Hn(e.ropeFrequencyScale,0,0),"llama.keepModelInMemory":e.keepModelInMemory,"llama.tryMmap":e.tryMmap})}createDomainSpecificModel(e,r,n,i){return new ml(e,r,n,i)}createDomainDynamicHandle(e,r,n,i){return new di(e,r,n,i)}},JS=Hh.extend({onProgress:o.function().optional(),signal:o.instanceof(AbortSignal).optional()}),QS=o.object({onFileProcessList:o.function().optional(),onFileProcessingStart:o.function().optional(),onFileProcessingEnd:o.function().optional(),onFileProcessingStepStart:o.function().optional(),onFileProcessingStepProgress:o.function().optional(),onFileProcessingStepEnd:o.function().optional(),onSearchingStart:o.function().optional(),onSearchingEnd:o.function().optional(),verbose:o.union([o.boolean(),o.string()]).optional()}),XS=o.object({chunkingMethod:kp.optional(),limit:o.number().int().optional(),embeddingModel:o.instanceof(di).optional(),databasePath:o.string().optional(),signal:o.instanceof(AbortSignal).optional(),...QS.shape});function eC(t){switch(t){case"loading":return"Loading";case"chunking":return"Chunking";case"embedding":return"Embedding";default:{let e=t;throw new Error(`Unexpected processing step: ${e}`)}}}var yl=class{constructor(e,r,n){this.filesPort=e,this.validator=r,this.logger=new Y("File",n)}async getLocalFileAbsolutePath(e,r){return await this.filesPort.callRpc("getLocalFileAbsolutePath",{fileName:e},{stack:r})}createFileHandleFromChatMessagePartFileData(e){return new Ce(this,e.identifier,e.fileType,e.sizeBytes,e.name)}async prepareImage(e){let r=await(0,at.readFileAsBase64)(e);if(r.success===!1)throw new Error(j`
338
338
  Your current JavaScript environment does not support reading files. If you can read the file
339
339
  using other methods, please use "prepareImageBase64".
340
- `);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:s,sizeBytes:a}=await this.filesPort.callRpc("uploadFileBase64",{name:n,contentBase64:r.base64});return new Ce(this,i,s,a,n)}async prepareImageBase64(e,r){let{identifier:n,fileType:i,sizeBytes:s}=await this.filesPort.callRpc("uploadFileBase64",{name:e,contentBase64:r});return new Ce(this,n,i,s,e)}async prepareFile(e){let r=await(0,st.readFileAsBase64)(e);if(r.success===!1)throw new Error(j`
340
+ `);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:s,sizeBytes:a}=await this.filesPort.callRpc("uploadFileBase64",{name:n,contentBase64:r.base64});return new Ce(this,i,s,a,n)}async prepareImageBase64(e,r){let{identifier:n,fileType:i,sizeBytes:s}=await this.filesPort.callRpc("uploadFileBase64",{name:e,contentBase64:r});return new Ce(this,n,i,s,e)}async prepareFile(e){let r=await(0,at.readFileAsBase64)(e);if(r.success===!1)throw new Error(j`
341
341
  Your current JavaScript environment does not support reading files. If you can read the file
342
342
  using other methods, please use "prepareFileBase64".
343
- `);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:s,sizeBytes:a}=await this.filesPort.callRpc("uploadFileBase64",{name:n,contentBase64:r.base64});return new Ce(this,i,s,a,n)}async prepareFileBase64(e,r){let{identifier:n,fileType:i,sizeBytes:s}=await this.filesPort.callRpc("uploadFileBase64",{name:e,contentBase64:r});return new Ce(this,n,i,s,e)}async retrieve(e,r,n={}){let i=this.logger,s=A(1);this.validator.validateMethodParamsOrThrow("client.retrieval","retrieve",["query","filePaths","opts"],[o.string(),o.array(o.instanceof(Ce)),QS],[e,r,n],s);let{verbose:a="info"}=n,l=typeof a=="boolean"?"info":a,c=a&&n.onFileProcessList===void 0&&n.onFileProcessingStart===void 0&&n.onFileProcessingEnd===void 0&&n.onFileProcessingStepStart===void 0&&n.onFileProcessingStepProgress===void 0&&n.onFileProcessingStepEnd===void 0&&n.onSearchingStart===void 0&&n.onSearchingEnd===void 0;if(n.embeddingModel===void 0)throw new Error("Embedding model currently is required.");let u=b=>{let D=r[b];if(D===void 0)throw new Error(`File not found: ${b}`);return D},h=b=>b.map(u),f=L1.buildPartialConfig({chunkingMethod:n.chunkingMethod,databaseFile:n.databasePath,embeddingModel:(await n.embeddingModel.getModelInfo())?.identifier,limit:n.limit}),d,p=[],m=0,g=0,y="";return await new Promise((b,D)=>{let v=this.filesPort.createChannel("retrieve",{query:e,fileIdentifiers:r.map(S=>S.identifier),config:f},S=>{switch(S.type){case"onFileProcessList":d=h(S.indices),L(i,"onFileProcessList",n.onFileProcessList,[d]),c&&i.logAtLevel(l,j`
343
+ `);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:s,sizeBytes:a}=await this.filesPort.callRpc("uploadFileBase64",{name:n,contentBase64:r.base64});return new Ce(this,i,s,a,n)}async prepareFileBase64(e,r){let{identifier:n,fileType:i,sizeBytes:s}=await this.filesPort.callRpc("uploadFileBase64",{name:e,contentBase64:r});return new Ce(this,n,i,s,e)}async retrieve(e,r,n={}){let i=this.logger,s=A(1);this.validator.validateMethodParamsOrThrow("client.retrieval","retrieve",["query","filePaths","opts"],[o.string(),o.array(o.instanceof(Ce)),XS],[e,r,n],s);let{verbose:a="info"}=n,l=typeof a=="boolean"?"info":a,c=a&&n.onFileProcessList===void 0&&n.onFileProcessingStart===void 0&&n.onFileProcessingEnd===void 0&&n.onFileProcessingStepStart===void 0&&n.onFileProcessingStepProgress===void 0&&n.onFileProcessingStepEnd===void 0&&n.onSearchingStart===void 0&&n.onSearchingEnd===void 0;if(n.embeddingModel===void 0)throw new Error("Embedding model currently is required.");let u=b=>{let D=r[b];if(D===void 0)throw new Error(`File not found: ${b}`);return D},h=b=>b.map(u),f=N1.buildPartialConfig({chunkingMethod:n.chunkingMethod,databaseFile:n.databasePath,embeddingModel:(await n.embeddingModel.getModelInfo())?.identifier,limit:n.limit}),d,p=[],m=0,g=0,y="";return await new Promise((b,D)=>{let v=this.filesPort.createChannel("retrieve",{query:e,fileIdentifiers:r.map(S=>S.identifier),config:f},S=>{switch(S.type){case"onFileProcessList":d=h(S.indices),L(i,"onFileProcessList",n.onFileProcessList,[d]),c&&i.logAtLevel(l,j`
344
344
  Found ${d.length} files need processing:
345
345
  ${d.map(C=>C.name).join(", ")}
346
346
  `);break;case"onFileProcessingStart":{if(d===null)throw new Error("onFileProcessList must be called before onFileProcessingStart");let C=u(S.index);L(i,"onFileProcessingStart",n.onFileProcessingStart,[C,d.indexOf(C),d]),c&&(p[S.index]=Date.now(),i.logAtLevel(l,j`
@@ -350,11 +350,11 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
350
350
  File processed: ${C.name}.
351
351
  Time took: ${Date.now()-p[S.index]}ms
352
352
  `);break}case"onFileProcessingStepStart":L(i,"onFileProcessingStepStart",n.onFileProcessingStepStart,[u(S.index),S.step]);break;case"onFileProcessingStepProgress":{L(i,"onFileProcessingStepProgress",n.onFileProcessingStepProgress,[u(S.index),S.step,S.progress]);let C=Date.now();if(c&&(C-g>500||S.progress===1)){g=C;let x=j`
353
- > ${XS(S.step)}: ${Math.round(S.progress*100)}%
353
+ > ${eC(S.step)}: ${Math.round(S.progress*100)}%
354
354
  `;y!==x&&(y=x,i.logAtLevel(l,x))}break}case"onFileProcessingStepEnd":L(i,"onFileProcessingStepEnd",n.onFileProcessingStepEnd,[u(S.index),S.step]);break;case"onSearchingStart":L(i,"onSearchingStart",n.onSearchingStart,[]),c&&(m=Date.now(),i.logAtLevel(l,"Start searching in the vector database..."));break;case"onSearchingEnd":L(i,"onSearchingEnd",n.onSearchingEnd,[]),c&&i.logAtLevel(l,j`
355
355
  Finished searching in the vector database.
356
356
  Time took: ${Date.now()-m}ms
357
- `);break;case"result":{b({entries:S.result.entries.map(C=>({content:C.content,score:C.score,source:r[C.sourceIndex]}))});break}}});n.signal!==void 0&&(n.signal.aborted?(D(n.signal.reason),v.send({type:"stop"})):n.signal?.addEventListener("abort",()=>{D(n.signal.reason),v.send({type:"stop"})})),v.onError.subscribeOnce(D)})}async parseDocument(e,r={}){let n=A(1);this.validator.validateMethodParamsOrThrow("client.files","parseDocument",["fileHandle","opts"],[o.instanceof(Ce),YS],[e,r],n);let{onParserLoaded:i,onProgress:s,signal:a,...l}=r,{promise:c,resolve:u,reject:h}=re();r.signal?.throwIfAborted();let f=!1,d=this.filesPort.createChannel("parseDocument",{fileIdentifier:e.identifier,parseOpts:l},p=>{switch(p.type){case"progress":{L(this.logger,"onProgress",s,[p.progress]);break}case"parserLoaded":{L(this.logger,"onParserLoaded",i,[p.parser]);break}case"result":{u({content:p.content,parser:p.parser}),f=!0;break}}},{stack:n});return a?.addEventListener("abort",()=>{f||(h(a.reason),d.send({type:"cancel"}))}),d.onError.subscribeOnce(h),d.onClose.subscribeOnce(()=>{f||h(new Error("Channel closed before receiving a result."))}),await c}async getDocumentParsingLibrary(e){let r=A(1);return await this.filesPort.callRpc("getDocumentParsingLibrary",{fileIdentifier:e.identifier},{stack:r})}};function _h(t,e){let r=I.default.redBright(` ${t.title} `);return t.suggestion!==void 0&&(r+=`
357
+ `);break;case"result":{b({entries:S.result.entries.map(C=>({content:C.content,score:C.score,source:r[C.sourceIndex]}))});break}}});n.signal!==void 0&&(n.signal.aborted?(D(n.signal.reason),v.send({type:"stop"})):n.signal?.addEventListener("abort",()=>{D(n.signal.reason),v.send({type:"stop"})})),v.onError.subscribeOnce(D)})}async parseDocument(e,r={}){let n=A(1);this.validator.validateMethodParamsOrThrow("client.files","parseDocument",["fileHandle","opts"],[o.instanceof(Ce),JS],[e,r],n);let{onParserLoaded:i,onProgress:s,signal:a,...l}=r,{promise:c,resolve:u,reject:h}=re();r.signal?.throwIfAborted();let f=!1,d=this.filesPort.createChannel("parseDocument",{fileIdentifier:e.identifier,parseOpts:l},p=>{switch(p.type){case"progress":{L(this.logger,"onProgress",s,[p.progress]);break}case"parserLoaded":{L(this.logger,"onParserLoaded",i,[p.parser]);break}case"result":{u({content:p.content,parser:p.parser}),f=!0;break}}},{stack:n});return a?.addEventListener("abort",()=>{f||(h(a.reason),d.send({type:"cancel"}))}),d.onError.subscribeOnce(h),d.onClose.subscribeOnce(()=>{f||h(new Error("Channel closed before receiving a result."))}),await c}async getDocumentParsingLibrary(e){let r=A(1);return await this.filesPort.callRpc("getDocumentParsingLibrary",{fileIdentifier:e.identifier},{stack:r})}};function xh(t,e){let r=I.default.redBright(` ${t.title} `);return t.suggestion!==void 0&&(r+=`
358
358
 
359
359
 
360
360
  `+I.default.bgWhite.black(" (!) SUGGESTION ")+`
@@ -364,24 +364,24 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
364
364
 
365
365
  `+I.default.bgWhite.black(" (X) CAUSE ")+`
366
366
 
367
- `+I.default.gray(t.cause)),Ee(r,e)}var Qp=new Map;function wn(t,e){Qp.set(t,e)}function eC(t,e){if(t.length===0)return I.default.gray(" You don't have any LLMs downloaded.");let r=t.map(n=>I.default.cyanBright(" \u2022 "+n)).join(`
367
+ `+I.default.gray(t.cause)),Ee(r,e)}var Xp=new Map;function wn(t,e){Xp.set(t,e)}function tC(t,e){if(t.length===0)return I.default.gray(" You don't have any LLMs downloaded.");let r=t.map(n=>I.default.cyanBright(" \u2022 "+n)).join(`
368
368
  `);return t.length<e&&(r+=I.default.gray(`
369
369
  ... (and ${e-t.length} more)`)),r}wn("generic.pathNotFound",({availablePathsSample:t,path:e,totalModels:r},n)=>Ir(`Cannot find a model with path "${I.default.yellowBright(e)}"`,j`
370
370
  Here are your available models:
371
371
 
372
- ${eC(t,r)}
372
+ ${tC(t,r)}
373
373
 
374
374
  Run
375
375
 
376
376
  ${I.default.yellowBright("lms ls")}
377
377
 
378
378
  to see a full list of loadable models
379
- `,n));function Xp(t,e){if(t.length===0)return I.default.gray(" You don't have any models loaded.");let r=t.map(n=>I.default.cyanBright(" \u2022 "+n)).join(`
379
+ `,n));function em(t,e){if(t.length===0)return I.default.gray(" You don't have any models loaded.");let r=t.map(n=>I.default.cyanBright(" \u2022 "+n)).join(`
380
380
  `);return t.length<e&&(r+=I.default.gray(`
381
381
  ... (and ${e-t.length} more)`)),r}wn("generic.identifierNotFound",({loadedModelsSample:t,identifier:e,totalLoadedModels:r},n)=>Ir(`Cannot find a model with identifier "${I.default.yellowBright(e)}"`,j`
382
382
  Here are your loaded models:
383
383
 
384
- ${Xp(t,r)}
384
+ ${em(t,r)}
385
385
 
386
386
  Run
387
387
 
@@ -390,19 +390,19 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
390
390
  to see a full list of loaded models
391
391
  `,n));wn("generic.specificModelUnloaded",(t,e)=>Ee(I.default.bgRed.white(j`
392
392
  This model has already been unloaded.
393
- `),e));function yl(t){switch(t){case"llm":return"an LLM";case"embedding":return"an embedding model";case"imageGen":return"an image generation model";case"transcription":return"a transcription model";case"tts":return"a text-to-speech model";default:return console.error(`Unexpected domain type: ${t}`),"Unknown Model Domain"}}function tC(t){let e=[];return t.domain!==void 0&&e.push(j`
394
- The model must be ${I.default.yellowBright(yl(t.domain))}
393
+ `),e));function bl(t){switch(t){case"llm":return"an LLM";case"embedding":return"an embedding model";case"imageGen":return"an image generation model";case"transcription":return"a transcription model";case"tts":return"a text-to-speech model";default:return console.error(`Unexpected domain type: ${t}`),"Unknown Model Domain"}}function rC(t){let e=[];return t.domain!==void 0&&e.push(j`
394
+ The model must be ${I.default.yellowBright(bl(t.domain))}
395
395
  `),t.identifier!==void 0&&e.push(`The identifier must be exactly "${I.default.yellowBright(t.identifier)}"`),t.path!==void 0&&e.push(`The path must match "${I.default.yellowBright(t.path)}"`),e.length===0?I.default.gray(" \u2022 Any Model"):e.map(r=>I.default.white(" \u2022 "+r)).join(`
396
396
  `)}wn("generic.noModelMatchingQuery",({loadedModelsSample:t,totalLoadedModels:e,query:r},n)=>Ee(j`
397
397
  ${I.default.bgRed.white(" No loaded model satisfies all requirements specified in the query. ")}
398
398
 
399
399
  Loaded Models:
400
400
 
401
- ${Xp(t,e)}
401
+ ${em(t,e)}
402
402
 
403
403
  Your query:
404
404
 
405
- ${tC(r)}
405
+ ${rC(r)}
406
406
 
407
407
  Run
408
408
 
@@ -412,34 +412,34 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
412
412
  `,n));wn("generic.domainMismatch",({actualDomain:t,expectedDomain:e,path:r},n)=>Ee(j`
413
413
  ${I.default.bgRed.white(" Model has wrong domain. ")}
414
414
 
415
- Expecting ${I.default.greenBright(r)} to be ${I.default.yellowBright(yl(e))}, but it is actually ${I.default.yellowBright(yl(t))}.
416
- `,n));function rC(t,e){if(t.length===0)return I.default.gray(" You don't have any presets available.");let r=t.map(({identifier:n,name:i})=>I.default.cyanBright(` \u2022 ${i} (${I.default.cyan(n)})`)).join(`
415
+ Expecting ${I.default.greenBright(r)} to be ${I.default.yellowBright(bl(e))}, but it is actually ${I.default.yellowBright(bl(t))}.
416
+ `,n));function nC(t,e){if(t.length===0)return I.default.gray(" You don't have any presets available.");let r=t.map(({identifier:n,name:i})=>I.default.cyanBright(` \u2022 ${i} (${I.default.cyan(n)})`)).join(`
417
417
  `);return t.length<e&&(r+=I.default.gray(`
418
418
  ... (and ${e-t.length} more)`)),r}wn("generic.presetNotFound",({specifiedFuzzyPresetIdentifier:t,availablePresetsSample:e,totalAvailablePresets:r})=>Ir(`Cannot find a preset with identifier "${I.default.yellowBright(t)}"`,j`
419
419
  Here are your available presets:
420
420
 
421
- ${rC(e,r)}
421
+ ${nC(e,r)}
422
422
 
423
423
  Note: To specify a preset in the SDK, you need to use its identifier (in parentheses). You
424
424
  can get a preset's identifier by right-clicking on it and then select "Copy Preset
425
425
  Identifier".
426
- `));function nC(t,e,r){if(t.displayData===void 0)return _h(t,r);let n,i=Qp.get(t.displayData.code);return i!==void 0?(n=i(t.displayData,r),Zh(n,t),n):_h(t,r)}function xh({value:t,falseDefault:e}){return t===void 0?void 0:t===!1?{checked:!1,value:e}:{checked:!0,value:t}}var bl=class{constructor(e,r){this.rounds=e,this.totalExecutionTimeSeconds=r}},iC=new Ts(Math.floor(Math.random()*(Number.MAX_SAFE_INTEGER/2/1e4))*1e4),vl=class{needsQueueing(){return!1}async runInQueue(e,r){if(r?.aborted)throw new Error("Operation aborted");return e()}},Dl=class{constructor(){this.queue=[],this.executing=!1,this.poisoned=!1,this.poisonError=null}needsQueueing(){return this.executing||this.queue.length>0}async runInQueue(e,r){if(r?.aborted)throw new Error("Operation aborted");if(this.poisoned)throw this.poisonError??new Error("Queue has been poisoned by a previous error");if(!this.needsQueueing()){this.executing=!0;try{if(r?.aborted)throw new Error("Operation aborted");return await e()}catch(n){throw this.poisoned=!0,this.poisonError=n,this.clearQueue(n),n}finally{this.executing=!1,this.processQueue()}}return new Promise((n,i)=>{if(r){if(r.aborted)return i(new Error("Operation aborted"));r.addEventListener("abort",()=>{let s=this.queue.findIndex(a=>a.resolve===n&&a.reject===i);s!==-1&&(this.queue.splice(s,1),i(new Error("Operation aborted")))},{once:!0})}this.queue.push({fn:async()=>{try{if(r?.aborted)throw new Error("Operation aborted");let s=await e();return n(s),s}catch(s){throw i(s),s}},resolve:n,reject:i,signal:r})})}async processQueue(){if(this.executing||this.queue.length===0||this.poisoned)return;let e=this.queue.shift();if(e){if(e.signal?.aborted){e.reject(new Error("Operation aborted")),this.processQueue();return}this.executing=!0;try{await e.fn()}catch(r){this.poisoned=!0,this.poisonError=r,this.clearQueue(r)}finally{this.executing=!1,this.poisoned||this.processQueue()}}}clearQueue(e){for(let r of this.queue)r.reject(e);this.queue=[]}},wl=class{constructor(e,r,n){this.toolCallRequest=e,this.tool=r,this.resultContainer=n,this.allow=()=>{this.assertNoResultYet("allow",A(1)),this.resultContainer[0]={type:"allow"}},this.allowAndOverrideParameters=i=>{this.assertNoResultYet("allowAndOverrideParameters",A(1)),this.resultContainer[0]={type:"allowAndOverrideParameters",parameters:i}},this.deny=i=>{this.assertNoResultYet("deny",A(1)),this.resultContainer[0]={type:"deny",reason:i}}}assertNoResultYet(e,r){if(this.resultContainer[0]!==null)throw Ir(`Cannot call ${e} after a result has been set`,j`
426
+ `));function iC(t,e,r){if(t.displayData===void 0)return xh(t,r);let n,i=Xp.get(t.displayData.code);return i!==void 0?(n=i(t.displayData,r),Kh(n,t),n):xh(t,r)}function kh({value:t,falseDefault:e}){return t===void 0?void 0:t===!1?{checked:!1,value:e}:{checked:!0,value:t}}var vl=class{constructor(e,r){this.rounds=e,this.totalExecutionTimeSeconds=r}},sC=new Ts(Math.floor(Math.random()*(Number.MAX_SAFE_INTEGER/2/1e4))*1e4),Dl=class{needsQueueing(){return!1}async runInQueue(e,r){if(r?.aborted)throw new Error("Operation aborted");return e()}},wl=class{constructor(){this.queue=[],this.executing=!1,this.poisoned=!1,this.poisonError=null}needsQueueing(){return this.executing||this.queue.length>0}async runInQueue(e,r){if(r?.aborted)throw new Error("Operation aborted");if(this.poisoned)throw this.poisonError??new Error("Queue has been poisoned by a previous error");if(!this.needsQueueing()){this.executing=!0;try{if(r?.aborted)throw new Error("Operation aborted");return await e()}catch(n){throw this.poisoned=!0,this.poisonError=n,this.clearQueue(n),n}finally{this.executing=!1,this.processQueue()}}return new Promise((n,i)=>{if(r){if(r.aborted)return i(new Error("Operation aborted"));r.addEventListener("abort",()=>{let s=this.queue.findIndex(a=>a.resolve===n&&a.reject===i);s!==-1&&(this.queue.splice(s,1),i(new Error("Operation aborted")))},{once:!0})}this.queue.push({fn:async()=>{try{if(r?.aborted)throw new Error("Operation aborted");let s=await e();return n(s),s}catch(s){throw i(s),s}},resolve:n,reject:i,signal:r})})}async processQueue(){if(this.executing||this.queue.length===0||this.poisoned)return;let e=this.queue.shift();if(e){if(e.signal?.aborted){e.reject(new Error("Operation aborted")),this.processQueue();return}this.executing=!0;try{await e.fn()}catch(r){this.poisoned=!0,this.poisonError=r,this.clearQueue(r)}finally{this.executing=!1,this.poisoned||this.processQueue()}}}clearQueue(e){for(let r of this.queue)r.reject(e);this.queue=[]}},Sl=class{constructor(e,r,n){this.toolCallRequest=e,this.tool=r,this.resultContainer=n,this.allow=()=>{this.assertNoResultYet("allow",A(1)),this.resultContainer[0]={type:"allow"}},this.allowAndOverrideParameters=i=>{this.assertNoResultYet("allowAndOverrideParameters",A(1)),this.resultContainer[0]={type:"allowAndOverrideParameters",parameters:i}},this.deny=i=>{this.assertNoResultYet("deny",A(1)),this.resultContainer[0]={type:"deny",reason:i}}}assertNoResultYet(e,r){if(this.resultContainer[0]!==null)throw Ir(`Cannot call ${e} after a result has been set`,j`
427
427
  This tool call guard has already set a result previously (${this.resultContainer[0].type}).
428
428
  You cannot set a result more than once.
429
- `,r)}},em=o.object({onFirstToken:o.function().optional(),onPredictionFragment:o.function().optional(),onMessage:o.function().optional(),onRoundStart:o.function().optional(),onRoundEnd:o.function().optional(),onPredictionCompleted:o.function().optional(),onPromptProcessingProgress:o.function().optional(),onToolCallRequestStart:o.function().optional(),onToolCallRequestNameReceived:o.function().optional(),onToolCallRequestArgumentFragmentGenerated:o.function().optional(),onToolCallRequestEnd:o.function().optional(),onToolCallRequestFinalized:o.function().optional(),onToolCallRequestFailure:o.function().optional(),onToolCallRequestDequeued:o.function().optional(),guardToolCall:o.function().optional(),handleInvalidToolRequest:o.function().optional(),maxPredictionRounds:o.number().int().min(1).optional(),signal:o.instanceof(AbortSignal).optional(),allowParallelToolExecution:o.boolean().optional()}),sC=(t,e)=>{if(e)return t.message;throw t};async function tm(t,e,r,n,i,s,a,l){let c=new AbortController,u=Et.from(t),h=-1,f=!1;r.signal!==void 0&&(r.signal.aborted?c.abort(r.signal.reason):r.signal.addEventListener("abort",()=>{c.abort(r.signal?.reason)},{once:!0}));let d=!1,p=0,m=new Map;for(let g of e)m.has(g.name)&&i.warnText`
429
+ `,r)}},tm=o.object({onFirstToken:o.function().optional(),onPredictionFragment:o.function().optional(),onMessage:o.function().optional(),onRoundStart:o.function().optional(),onRoundEnd:o.function().optional(),onPredictionCompleted:o.function().optional(),onPromptProcessingProgress:o.function().optional(),onToolCallRequestStart:o.function().optional(),onToolCallRequestNameReceived:o.function().optional(),onToolCallRequestArgumentFragmentGenerated:o.function().optional(),onToolCallRequestEnd:o.function().optional(),onToolCallRequestFinalized:o.function().optional(),onToolCallRequestFailure:o.function().optional(),onToolCallRequestDequeued:o.function().optional(),guardToolCall:o.function().optional(),handleInvalidToolRequest:o.function().optional(),maxPredictionRounds:o.number().int().min(1).optional(),signal:o.instanceof(AbortSignal).optional(),allowParallelToolExecution:o.boolean().optional()}),oC=(t,e)=>{if(e)return t.message;throw t};async function rm(t,e,r,n,i,s,a,l){let c=new AbortController,u=_t.from(t),h=-1,f=!1;r.signal!==void 0&&(r.signal.aborted?c.abort(r.signal.reason):r.signal.addEventListener("abort",()=>{c.abort(r.signal?.reason)},{once:!0}));let d=!1,p=0,m=new Map;for(let g of e)m.has(g.name)&&i.warnText`
430
430
  Duplicate tool (${g.name}) found in the tools array. The last tool with the same name
431
431
  will be used.
432
- `,m.set(g.name,g);do{let g=!0;r.maxPredictionRounds!==void 0&&p+1>=r.maxPredictionRounds&&(g=!1);let y=!1,b=!1,D=[],v=[],S=[],C=[],x=0,_=[],B=[],{promise:w,resolve:E,reject:P}=re(),{promise:q,resolve:W,reject:V}=re(),pe=async(N,se,we)=>{let Ft;try{Ft=await(r.handleInvalidToolRequest??sC)(N,se)}catch(Pt){throw c.signal.aborted?c.signal.reason:(c.abort(),Pt)}if(Ft===void 0)return;let Jt;try{Jt=JSON.stringify(Ft)}catch{throw c.abort(),Ee("handleInvalidToolRequest returned a value that cannot be converted to JSON.",n)}se===void 0?i.warnText`
432
+ `,m.set(g.name,g);do{let g=!0;r.maxPredictionRounds!==void 0&&p+1>=r.maxPredictionRounds&&(g=!1);let y=!1,b=!1,D=[],v=[],S=[],C=[],x=0,_=[],B=[],{promise:w,resolve:E,reject:P}=re(),{promise:q,resolve:W,reject:V}=re(),pe=async(N,se,we)=>{let Ft;try{Ft=await(r.handleInvalidToolRequest??oC)(N,se)}catch(Pt){throw c.signal.aborted?c.signal.reason:(c.abort(),Pt)}if(Ft===void 0)return;let Jt;try{Jt=JSON.stringify(Ft)}catch{throw c.abort(),Ee("handleInvalidToolRequest returned a value that cannot be converted to JSON.",n)}se===void 0?i.warnText`
433
433
  The "handleInvalidToolRequest" callback has returned a result, but the tool request has
434
434
  completely failed to parse, thus LM Studio cannot provide the result to the tool call.
435
435
  Please avoid returning a result when the second parameter of the callback is undefined.
436
436
  See the documentation for "handleInvalidToolRequest" for more information.
437
- `:(_.push({index:we,data:{type:"toolCallResult",toolCallId:se.id,content:Jt}}),x++)};c.signal.throwIfAborted(),L(i,"onRoundStart",r.onRoundStart,[p]);let me=!1,ve=new AbortController,J=r.allowParallelToolExecution?new vl:new Dl,De=!1,kt=!1;a({allowTools:g,history:u._internalGetData(),signal:ve.signal,handleFragment:N=>{b||(b=!0,L(i,"onFirstToken",r.onFirstToken,[p])),L(i,"onFragment",r.onPredictionFragment,[{roundIndex:p,...N}]),D.push(N.content),N.isStructural||(N.reasoningType==="reasoning"?v.push(N.content):S.push(N.content))},handlePromptProcessingProgress:N=>{L(i,"onPromptProcessingProgress",r.onPromptProcessingProgress,[p,N])},handleToolCallGenerationStart:N=>{h=iC.next(),De=!1,kt=!1,me=!0,L(i,"onToolCallRequestStart",r.onToolCallRequestStart,[p,h,{toolCallId:N}])},handleToolCallGenerationNameReceived:N=>{De=!0,L(i,"onToolCallRequestNameReceived",r.onToolCallRequestNameReceived,[p,h,N])},handleToolCallGenerationArgumentFragmentGenerated:N=>{kt=!0,L(i,"onToolCallRequestArgumentFragmentGenerated",r.onToolCallRequestArgumentFragmentGenerated,[p,h,N])},handleToolCallGenerationEnd:(N,se)=>{let we=h;me=!1;let Ft=x;x++,De||L(i,"onToolCallRequestNameReceived",r.onToolCallRequestNameReceived,[p,we,N.name]),kt||L(i,"onToolCallRequestArgumentFragmentGenerated",r.onToolCallRequestArgumentFragmentGenerated,[p,we,JSON.stringify(N.arguments??{},null,2)]);let Jt={...N};C.push(Jt);let Pt=m.get(N.name);if(Pt===void 0){let Tt=new xr(`Cannot find tool with name ${N.name}.`,se);B.push(pe(Tt,N,Ft).catch(V)),L(i,"onToolCallRequestFailure",r.onToolCallRequestFailure,[p,we,Tt]);return}try{Pt.checkParameters(Jt.arguments)}catch(Tt){let Ur=new xr(Tt.message,se);B.push(pe(Ur,N,Ft).catch(V)),L(i,"onToolCallRequestFailure",r.onToolCallRequestFailure,[p,we,Ur]);return}let Qg=new Xa(new Y(`Tool(${N.name})`,i),c.signal,we),Vc=J.needsQueueing();L(i,"onToolCallRequestEnd",r.onToolCallRequestEnd,[p,we,{isQueued:Vc,toolCallRequest:N,rawContent:se}]),B.push(J.runInQueue(async()=>{if(Vc&&L(i,"onToolCallRequestDequeued",r.onToolCallRequestDequeued,[p,we]),r.guardToolCall!==void 0){let Qt=[null];if(await r.guardToolCall(p,we,new wl(N,Pt,Qt)),Qt[0]===null)throw Ir("Tool call guard did not allow or deny the tool call.",j`
437
+ `:(_.push({index:we,data:{type:"toolCallResult",toolCallId:se.id,content:Jt}}),x++)};c.signal.throwIfAborted(),L(i,"onRoundStart",r.onRoundStart,[p]);let me=!1,ve=new AbortController,J=r.allowParallelToolExecution?new Dl:new wl,De=!1,kt=!1;a({allowTools:g,history:u._internalGetData(),signal:ve.signal,handleFragment:N=>{b||(b=!0,L(i,"onFirstToken",r.onFirstToken,[p])),L(i,"onFragment",r.onPredictionFragment,[{roundIndex:p,...N}]),D.push(N.content),N.isStructural||(N.reasoningType==="reasoning"?v.push(N.content):S.push(N.content))},handlePromptProcessingProgress:N=>{L(i,"onPromptProcessingProgress",r.onPromptProcessingProgress,[p,N])},handleToolCallGenerationStart:N=>{h=sC.next(),De=!1,kt=!1,me=!0,L(i,"onToolCallRequestStart",r.onToolCallRequestStart,[p,h,{toolCallId:N}])},handleToolCallGenerationNameReceived:N=>{De=!0,L(i,"onToolCallRequestNameReceived",r.onToolCallRequestNameReceived,[p,h,N])},handleToolCallGenerationArgumentFragmentGenerated:N=>{kt=!0,L(i,"onToolCallRequestArgumentFragmentGenerated",r.onToolCallRequestArgumentFragmentGenerated,[p,h,N])},handleToolCallGenerationEnd:(N,se)=>{let we=h;me=!1;let Ft=x;x++,De||L(i,"onToolCallRequestNameReceived",r.onToolCallRequestNameReceived,[p,we,N.name]),kt||L(i,"onToolCallRequestArgumentFragmentGenerated",r.onToolCallRequestArgumentFragmentGenerated,[p,we,JSON.stringify(N.arguments??{},null,2)]);let Jt={...N};C.push(Jt);let Pt=m.get(N.name);if(Pt===void 0){let Tt=new xr(`Cannot find tool with name ${N.name}.`,se);B.push(pe(Tt,N,Ft).catch(V)),L(i,"onToolCallRequestFailure",r.onToolCallRequestFailure,[p,we,Tt]);return}try{Pt.checkParameters(Jt.arguments)}catch(Tt){let Ur=new xr(Tt.message,se);B.push(pe(Ur,N,Ft).catch(V)),L(i,"onToolCallRequestFailure",r.onToolCallRequestFailure,[p,we,Ur]);return}let Xg=new el(new Y(`Tool(${N.name})`,i),c.signal,we),Wc=J.needsQueueing();L(i,"onToolCallRequestEnd",r.onToolCallRequestEnd,[p,we,{isQueued:Wc,toolCallRequest:N,rawContent:se}]),B.push(J.runInQueue(async()=>{if(Wc&&L(i,"onToolCallRequestDequeued",r.onToolCallRequestDequeued,[p,we]),r.guardToolCall!==void 0){let Qt=[null];if(await r.guardToolCall(p,we,new Sl(N,Pt,Qt)),Qt[0]===null)throw Ir("Tool call guard did not allow or deny the tool call.",j`
438
438
  The \`guardToolCall\` handler must call one of the methods on the controller
439
439
  to allow or deny the tool call.
440
- `,n);let mo=Qt[0];switch(mo.type){case"allow":break;case"allowAndOverrideParameters":{Jt.arguments=mo.parameters;break}case"deny":{_.push({index:Ft,data:{type:"toolCallResult",toolCallId:N.id,content:JSON.stringify({error:mo.reason})}});return}}}L(i,"onToolCallRequestFinalized",r.onToolCallRequestFinalized,[p,we,{toolCallRequest:N,rawContent:se}]);let Tt;try{Tt=await Pt.implementation(Jt.arguments??{},Qg)}catch(Qt){if(!(Qt instanceof el))throw Qt;f=!0}let Ur;if(Tt===void 0)Ur="undefined";else try{Ur=JSON.stringify(Tt)}catch{throw Ee(`Return value of tool ${Pt.name} cannot be converted to JSON.`,n)}_.push({index:Ft,data:{type:"toolCallResult",toolCallId:N.id,content:Ur}})},c.signal).catch(V))},handleToolCallGenerationFailed:(N,se)=>{me=!1;let we=new xr(N.message,se);B.push(pe(we,void 0,0).catch(V)),L(i,"onToolCallRequestFailure",r.onToolCallRequestFailure,[p,h,we])},handlePredictionEnd:N=>{let se=l({endPacket:N,content:D.join(""),reasoningContent:v.join(""),nonReasoningContent:S.join(""),predictionsPerformed:p});L(i,"onPredictionCompleted",r.onPredictionCompleted,[se]),E()},handleError:N=>{if(me){let se=new xr(`Generation failed: ${N.message}`,void 0);me=!1,L(i,"onToolCallRequestFailure",r.onToolCallRequestFailure,[p,h,se])}y=!0,P(N)}});let ge=()=>{y||(y=!0,ve.abort(c.signal.reason))};if(c.signal.addEventListener("abort",ge),w.then(()=>{let N=he.from({role:"assistant",content:[{type:"text",text:D.join("")},...C.map(se=>({type:"toolCallRequest",toolCallRequest:se}))]});u.append(N.asMutableCopy()),L(i,"onMessage",r.onMessage,[N])}).then(()=>Promise.all(B)).then(()=>W(),V),await q,d=!1,_.length>0){_.sort((se,we)=>se.index-we.index);let N=he.from({role:"tool",content:_.map(se=>se.data)});u.append(N.asMutableCopy()),L(i,"onMessage",r.onMessage,[N]),d=!0}L(i,"onRoundEnd",r.onRoundEnd,[p]),p++,r.maxPredictionRounds!==void 0&&p>=r.maxPredictionRounds&&(d=!1),d&&=!f}while(d);return new bl(p,(performance.now()-s)/1e3)}var fi=class{constructor(e,r,n,i,s,a,l,c){this.content=e,this.reasoningContent=r,this.nonReasoningContent=n,this.stats=i,this.modelInfo=s,this.roundIndex=a,this.loadConfig=l,this.predictionConfig=c}},Sl=class extends fi{constructor(e,r,n,i,s,a,l,c,u){super(e,r,n,i,s,a,l,c),this.parsed=u}},Us=class t extends Rs{async collect(e){let r=e.map(({content:s})=>s).join(""),n=e.filter(({isStructural:s})=>!s).filter(({reasoningType:s})=>s==="reasoning").map(({content:s})=>s).join(""),i=e.filter(({isStructural:s})=>!s).filter(({reasoningType:s})=>s==="none").map(({content:s})=>s).join("");if(this.stats===null)throw new Error("Stats should not be null");if(this.modelInfo===null)throw new Error("Model info should not be null");if(this.loadModelConfig===null)throw new Error("Load model config should not be null");if(this.predictionConfig===null)throw new Error("Prediction config should not be null");return this.parser===null?new fi(r,n,i,this.stats,this.modelInfo,0,this.loadModelConfig,this.predictionConfig):new Sl(r,n,i,this.stats,this.modelInfo,0,this.loadModelConfig,this.predictionConfig,this.parser(r))}constructor(e,r){super(),this.onCancel=e,this.parser=r,this.stats=null,this.modelInfo=null,this.loadModelConfig=null,this.predictionConfig=null}static create(e,r){let n=new t(e,r);return{ongoingPrediction:n,finished:(l,c,u,h)=>{n.stats=l,n.modelInfo=c,n.loadModelConfig=u,n.predictionConfig=h,n.finished()},failed:l=>n.finished(l),push:l=>n.push(l)}}async result(){return await this}async cancel(){this.onCancel()}},rm=Jl.extend({onPromptProcessingProgress:o.function().optional(),onFirstToken:o.function().optional(),onPredictionFragment:o.function().optional(),onToolCallRequestStart:o.function().optional(),onToolCallRequestNameReceived:o.function().optional(),onToolCallRequestArgumentFragmentGenerated:o.function().optional(),onToolCallRequestEnd:o.function().optional(),onToolCallRequestFailure:o.function().optional(),signal:o.instanceof(AbortSignal).optional(),preset:o.string().optional()});function nm(t){let{onPromptProcessingProgress:e,onFirstToken:r,onPredictionFragment:n,onToolCallRequestStart:i,onToolCallRequestNameReceived:s,onToolCallRequestArgumentFragmentGenerated:a,onToolCallRequestEnd:l,onToolCallRequestFailure:c,signal:u,preset:h,...f}=t;return[f,{onPromptProcessingProgress:e,onFirstToken:r,onPredictionFragment:n,onToolCallRequestStart:i,onToolCallRequestNameReceived:s,onToolCallRequestArgumentFragmentGenerated:a,onToolCallRequestEnd:l,onToolCallRequestFailure:c,signal:u,preset:h}]}var oC=rm.extend({onMessage:o.function().optional(),onToolCallRequestStart:o.function().optional(),onToolCallRequestNameReceived:o.function().optional(),onToolCallRequestArgumentFragmentGenerated:o.function().optional(),onToolCallRequestEnd:o.function().optional(),onToolCallRequestFailure:o.function().optional()});function aC(t){let{onMessage:e,...r}=t,[n,i]=nm(r);return[n,i,{onMessage:e}]}var lC=Jl.extend(em.shape).extend({preset:o.string().optional()});function cC(t){let{onFirstToken:e,onPredictionFragment:r,onMessage:n,onRoundStart:i,onRoundEnd:s,onPredictionCompleted:a,onPromptProcessingProgress:l,onToolCallRequestStart:c,onToolCallRequestNameReceived:u,onToolCallRequestArgumentFragmentGenerated:h,onToolCallRequestEnd:f,onToolCallRequestFinalized:d,onToolCallRequestFailure:p,onToolCallRequestDequeued:m,guardToolCall:g,handleInvalidToolRequest:y,maxPredictionRounds:b,signal:D,preset:v,allowParallelToolExecution:S,...C}=t;return[C,{onFirstToken:e,onPredictionFragment:r,onMessage:n,onRoundStart:i,onRoundEnd:s,onPredictionCompleted:a,onPromptProcessingProgress:l,onToolCallRequestStart:c,onToolCallRequestNameReceived:u,onToolCallRequestArgumentFragmentGenerated:h,onToolCallRequestEnd:f,onToolCallRequestFinalized:d,onToolCallRequestFailure:p,onToolCallRequestDequeued:m,guardToolCall:g,handleInvalidToolRequest:y,maxPredictionRounds:b,signal:D,preset:v,allowParallelToolExecution:S}]}var uC=j`
440
+ `,n);let go=Qt[0];switch(go.type){case"allow":break;case"allowAndOverrideParameters":{Jt.arguments=go.parameters;break}case"deny":{_.push({index:Ft,data:{type:"toolCallResult",toolCallId:N.id,content:JSON.stringify({error:go.reason})}});return}}}L(i,"onToolCallRequestFinalized",r.onToolCallRequestFinalized,[p,we,{toolCallRequest:N,rawContent:se}]);let Tt;try{Tt=await Pt.implementation(Jt.arguments??{},Xg)}catch(Qt){if(!(Qt instanceof tl))throw Qt;f=!0}let Ur;if(Tt===void 0)Ur="undefined";else try{Ur=JSON.stringify(Tt)}catch{throw Ee(`Return value of tool ${Pt.name} cannot be converted to JSON.`,n)}_.push({index:Ft,data:{type:"toolCallResult",toolCallId:N.id,content:Ur}})},c.signal).catch(V))},handleToolCallGenerationFailed:(N,se)=>{me=!1;let we=new xr(N.message,se);B.push(pe(we,void 0,0).catch(V)),L(i,"onToolCallRequestFailure",r.onToolCallRequestFailure,[p,h,we])},handlePredictionEnd:N=>{let se=l({endPacket:N,content:D.join(""),reasoningContent:v.join(""),nonReasoningContent:S.join(""),predictionsPerformed:p});L(i,"onPredictionCompleted",r.onPredictionCompleted,[se]),E()},handleError:N=>{if(me){let se=new xr(`Generation failed: ${N.message}`,void 0);me=!1,L(i,"onToolCallRequestFailure",r.onToolCallRequestFailure,[p,h,se])}y=!0,P(N)}});let ge=()=>{y||(y=!0,ve.abort(c.signal.reason))};if(c.signal.addEventListener("abort",ge),w.then(()=>{let N=he.from({role:"assistant",content:[{type:"text",text:D.join("")},...C.map(se=>({type:"toolCallRequest",toolCallRequest:se}))]});u.append(N.asMutableCopy()),L(i,"onMessage",r.onMessage,[N])}).then(()=>Promise.all(B)).then(()=>W(),V),await q,d=!1,_.length>0){_.sort((se,we)=>se.index-we.index);let N=he.from({role:"tool",content:_.map(se=>se.data)});u.append(N.asMutableCopy()),L(i,"onMessage",r.onMessage,[N]),d=!0}L(i,"onRoundEnd",r.onRoundEnd,[p]),p++,r.maxPredictionRounds!==void 0&&p>=r.maxPredictionRounds&&(d=!1),d&&=!f}while(d);return new vl(p,(performance.now()-s)/1e3)}var fi=class{constructor(e,r,n,i,s,a,l,c){this.content=e,this.reasoningContent=r,this.nonReasoningContent=n,this.stats=i,this.modelInfo=s,this.roundIndex=a,this.loadConfig=l,this.predictionConfig=c}},Cl=class extends fi{constructor(e,r,n,i,s,a,l,c,u){super(e,r,n,i,s,a,l,c),this.parsed=u}},Us=class t extends Rs{async collect(e){let r=e.map(({content:s})=>s).join(""),n=e.filter(({isStructural:s})=>!s).filter(({reasoningType:s})=>s==="reasoning").map(({content:s})=>s).join(""),i=e.filter(({isStructural:s})=>!s).filter(({reasoningType:s})=>s==="none").map(({content:s})=>s).join("");if(this.stats===null)throw new Error("Stats should not be null");if(this.modelInfo===null)throw new Error("Model info should not be null");if(this.loadModelConfig===null)throw new Error("Load model config should not be null");if(this.predictionConfig===null)throw new Error("Prediction config should not be null");return this.parser===null?new fi(r,n,i,this.stats,this.modelInfo,0,this.loadModelConfig,this.predictionConfig):new Cl(r,n,i,this.stats,this.modelInfo,0,this.loadModelConfig,this.predictionConfig,this.parser(r))}constructor(e,r){super(),this.onCancel=e,this.parser=r,this.stats=null,this.modelInfo=null,this.loadModelConfig=null,this.predictionConfig=null}static create(e,r){let n=new t(e,r);return{ongoingPrediction:n,finished:(l,c,u,h)=>{n.stats=l,n.modelInfo=c,n.loadModelConfig=u,n.predictionConfig=h,n.finished()},failed:l=>n.finished(l),push:l=>n.push(l)}}async result(){return await this}async cancel(){this.onCancel()}},nm=Ql.extend({onPromptProcessingProgress:o.function().optional(),onFirstToken:o.function().optional(),onPredictionFragment:o.function().optional(),onToolCallRequestStart:o.function().optional(),onToolCallRequestNameReceived:o.function().optional(),onToolCallRequestArgumentFragmentGenerated:o.function().optional(),onToolCallRequestEnd:o.function().optional(),onToolCallRequestFailure:o.function().optional(),signal:o.instanceof(AbortSignal).optional(),preset:o.string().optional()});function im(t){let{onPromptProcessingProgress:e,onFirstToken:r,onPredictionFragment:n,onToolCallRequestStart:i,onToolCallRequestNameReceived:s,onToolCallRequestArgumentFragmentGenerated:a,onToolCallRequestEnd:l,onToolCallRequestFailure:c,signal:u,preset:h,...f}=t;return[f,{onPromptProcessingProgress:e,onFirstToken:r,onPredictionFragment:n,onToolCallRequestStart:i,onToolCallRequestNameReceived:s,onToolCallRequestArgumentFragmentGenerated:a,onToolCallRequestEnd:l,onToolCallRequestFailure:c,signal:u,preset:h}]}var aC=nm.extend({onMessage:o.function().optional(),onToolCallRequestStart:o.function().optional(),onToolCallRequestNameReceived:o.function().optional(),onToolCallRequestArgumentFragmentGenerated:o.function().optional(),onToolCallRequestEnd:o.function().optional(),onToolCallRequestFailure:o.function().optional()});function lC(t){let{onMessage:e,...r}=t,[n,i]=im(r);return[n,i,{onMessage:e}]}var cC=Ql.extend(tm.shape).extend({preset:o.string().optional()});function uC(t){let{onFirstToken:e,onPredictionFragment:r,onMessage:n,onRoundStart:i,onRoundEnd:s,onPredictionCompleted:a,onPromptProcessingProgress:l,onToolCallRequestStart:c,onToolCallRequestNameReceived:u,onToolCallRequestArgumentFragmentGenerated:h,onToolCallRequestEnd:f,onToolCallRequestFinalized:d,onToolCallRequestFailure:p,onToolCallRequestDequeued:m,guardToolCall:g,handleInvalidToolRequest:y,maxPredictionRounds:b,signal:D,preset:v,allowParallelToolExecution:S,...C}=t;return[C,{onFirstToken:e,onPredictionFragment:r,onMessage:n,onRoundStart:i,onRoundEnd:s,onPredictionCompleted:a,onPromptProcessingProgress:l,onToolCallRequestStart:c,onToolCallRequestNameReceived:u,onToolCallRequestArgumentFragmentGenerated:h,onToolCallRequestEnd:f,onToolCallRequestFinalized:d,onToolCallRequestFailure:p,onToolCallRequestDequeued:m,guardToolCall:g,handleInvalidToolRequest:y,maxPredictionRounds:b,signal:D,preset:v,allowParallelToolExecution:S}]}var dC=j`
441
441
  {% for message in messages %}{{ message['content'] }}{% endfor %}
442
- `,qs=class extends $s{constructor(e,r,n,i=new Y("LLMModel")){super(e,r),this.validator=n,this.logger=i,this.internalKVConfigStack={layers:[]},this.internalIgnoreServerSessionConfig=void 0}internalPredict(e,r,n,i,s,a,l){let c=!1,u=!1,h=null,f=!1,d=!1,p=this.port.createChannel("predict",{modelSpecifier:this.specifier,history:e,predictionConfigStack:r,fuzzyPresetIdentifier:i.preset,ignoreServerSessionConfig:this.internalIgnoreServerSessionConfig},m=>{switch(m.type){case"fragment":{u||(u=!0,L(this.logger,"onFirstToken",i.onFirstToken,[])),L(this.logger,"onFragment",i.onPredictionFragment,[m.fragment]),s(m.fragment);break}case"promptProcessingProgress":{L(this.logger,"onPromptProcessingProgress",i.onPromptProcessingProgress,[m.progress]);break}case"toolCallGenerationStart":{h===null?h=0:h++,f=!1,d=!1,L(this.logger,"onToolCallGenerationStart",i.onToolCallRequestStart,[h,{toolCallId:m.toolCallId}]);break}case"toolCallGenerationNameReceived":{f=!0,L(this.logger,"onToolCallGenerationNameReceived",i.onToolCallRequestNameReceived,[h??-1,m.name]);break}case"toolCallGenerationArgumentFragmentGenerated":{d=!0,L(this.logger,"onToolCallGenerationArgumentFragmentGenerated",i.onToolCallRequestArgumentFragmentGenerated,[h??-1,m.content]);break}case"toolCallGenerationEnd":{f||L(this.logger,"onToolCallGenerationNameReceived",i.onToolCallRequestNameReceived,[h??-1,m.toolCallRequest.name]),d||L(this.logger,"onToolCallGenerationArgumentFragmentGenerated",i.onToolCallRequestArgumentFragmentGenerated,[h??-1,JSON.stringify(m.toolCallRequest.arguments??{},null,2)]),L(this.logger,"onToolCallGenerationEnd",i.onToolCallRequestEnd,[h??-1,{toolCallRequest:m.toolCallRequest,rawContent:m.rawContent}]);break}case"toolCallGenerationFailed":{let g=new xr(Os(m.error).message,m.rawContent);L(this.logger,"onToolCallGenerationFailed",i.onToolCallRequestFailure,[h??-1,g]);break}case"success":{c=!0,a(m.stats,m.modelInfo,m.loadModelConfig,m.predictionConfig);break}}},{stack:A(2)});n.subscribeOnce(()=>{c||p.send({type:"cancel"})}),p.onError.subscribeOnce(l)}predictionConfigInputToKVConfig(e){let r;typeof e.structured?.parse=="function"?r={type:"json",jsonSchema:ds(e.structured)}:r=e.structured;let n={...e,structured:r};return $1(n)}createZodParser(e){return r=>{try{return e.parse(JSON.parse(r))}catch(n){throw new Error("Failed to parse structured output: "+JSON.stringify(r),{cause:n})}}}complete(e,r={}){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow("model","complete",["prompt","opts"],[o.string(),rm],[e,r],n);let[i,s]=nm(r),[a,l]=Ct.create();s.signal!==void 0&&(s.signal.aborted?l():s.signal.addEventListener("abort",()=>{l()},{once:!0}));let c=Rr.safeParse(i.structured),{ongoingPrediction:u,finished:h,failed:f,push:d}=Us.create(l,c.success?this.createZodParser(c.data):null);return this.internalPredict(this.resolveCompletionContext(e),{layers:[...this.internalKVConfigStack.layers,{layerName:"apiOverride",config:this.predictionConfigInputToKVConfig({stopStrings:[],...i})},{layerName:"completeModeFormatting",config:gi.buildPartialConfig({promptTemplate:{type:"jinja",jinjaPromptTemplate:{template:uC},stopStrings:[]}})}]},a,s,p=>d(p),(p,m,g,y)=>h(p,m,g,y),p=>f(p)),u}resolveCompletionContext(e){return{messages:[{role:"user",content:[{type:"text",text:e}]}]}}respond(e,r={}){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow("model","respond",["chat","opts"],[gn,oC],[e,r],n);let[i,s]=Ct.create(),[a,l,c]=aC(r);l.signal!==void 0&&(l.signal.aborted?s():l.signal.addEventListener("abort",()=>{s()},{once:!0}));let u=Rr.safeParse(a.structured),{ongoingPrediction:h,finished:f,failed:d,push:p}=Us.create(s,u.success?this.createZodParser(u.data):null);return this.internalPredict(Et.from(e)._internalGetData(),Aa(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig(a)),i,l,m=>p(m),(m,g,y,b)=>f(m,g,y,b),m=>d(m)),h.then(m=>{L(this.logger,"onMessage",c.onMessage,[he.create("assistant",m.content)])},()=>{}),h}async act(e,r,n={}){let i=performance.now(),s=A(1);[e,n]=this.validator.validateMethodParamsOrThrow("model","act",["chat","opts"],[gn,lC],[e,n],s);let[a,{preset:l,...c}]=cC(n);if(a.structured!==void 0&&a.structured.type!=="none"&&r.length>0)throw Ee("Structured output is currently not supported in .act() when there are tools.",s);if(a.structured!==void 0&&a.structured.parse!==void 0)throw Ee("zod schema is not supported in .act().",s);if(a.rawTools!==void 0)throw Ee("`rawTools` is not supported in act. Use `tools` instead",s);let u;r.length===0?u={type:"none"}:u={type:"toolArray",tools:r.map(ac)};let h=Aa(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig({...a,rawTools:u})),f=Aa(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig({...a,rawTools:{type:"none"}}));return await tm(e,r,c,s,this.logger,i,async({allowTools:d,history:p,signal:m,handleFragment:g,handlePromptProcessingProgress:y,handleToolCallGenerationStart:b,handleToolCallGenerationNameReceived:D,handleToolCallGenerationArgumentFragmentGenerated:v,handleToolCallGenerationEnd:S,handleToolCallGenerationFailed:C,handlePredictionEnd:x,handleError:_})=>{let B=this.port.createChannel("predict",{modelSpecifier:this.specifier,history:p,predictionConfigStack:d?h:f,fuzzyPresetIdentifier:l,ignoreServerSessionConfig:this.internalIgnoreServerSessionConfig},w=>{switch(w.type){case"fragment":{g(w.fragment);break}case"promptProcessingProgress":{y(w.progress);break}case"toolCallGenerationStart":{b(w.toolCallId);break}case"toolCallGenerationNameReceived":{D(w.name);break}case"toolCallGenerationArgumentFragmentGenerated":{v(w.content);break}case"toolCallGenerationEnd":{S(w.toolCallRequest,w.rawContent);break}case"toolCallGenerationFailed":{C(Os(w.error),w.rawContent);break}case"success":{x({stats:w.stats,modelInfo:w.modelInfo,loadModelConfig:w.loadModelConfig,predictionConfig:w.predictionConfig});break}}},{stack:s});m.aborted?B.send({type:"cancel"}):m.addEventListener("abort",()=>{B.send({type:"cancel"})},{once:!0}),B.onError.subscribeOnce(_)},({endPacket:d,content:p,nonReasoningContent:m,reasoningContent:g,predictionsPerformed:y})=>new fi(p,g,m,d.stats,d.modelInfo,y,d.loadModelConfig,d.predictionConfig))}async getContextLength(){let e=A(1),r=await this.getLoadConfig(e);return yi.access(r,"contextLength")}async applyPromptTemplate(e,r={}){let n=A(1);return[e,r]=this.validator.validateMethodParamsOrThrow("model","applyPromptTemplate",["history","opts"],[gn,Xh],[e,r],n),(await this.port.callRpc("applyPromptTemplate",{specifier:this.specifier,history:Et.from(e)._internalGetData(),predictionConfigStack:this.internalKVConfigStack,opts:r},{stack:n})).formatted}async tokenize(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("model","tokenize","inputString",o.string().or(o.array(o.string())),e,r),Array.isArray(e)?(await Promise.all(e.map(n=>this.port.callRpc("tokenize",{specifier:this.specifier,inputString:n},{stack:r})))).map(n=>n.tokens):(await this.port.callRpc("tokenize",{specifier:this.specifier,inputString:e},{stack:r})).tokens}async countTokens(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("model","countTokens","inputString",o.string(),e,r),(await this.port.callRpc("countTokens",{specifier:this.specifier,inputString:e},{stack:r})).tokenCount}async unstable_preloadDraftModel(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("model","unstable_preloadDraftModel","draftModelKey",o.string(),e,r),await this.port.callRpc("preloadDraftModel",{specifier:this.specifier,draftModelKey:e},{stack:r})}},Cl=class extends qs{constructor(e,r,n,i=new Y("LLM")){let s={type:"instanceReference",instanceReference:r.instanceReference};super(e,s,n,i),this.identifier=r.identifier,this.path=r.path,this.modelKey=r.modelKey,this.format=r.format,this.displayName=r.displayName,this.sizeBytes=r.sizeBytes,this.vision=r.vision,this.trainedForToolUse=r.trainedForToolUse}async unload(){let e=A(1);await this.port.callRpc("unloadModel",{identifier:this.identifier},{stack:e})}async getModelInfo(){let e=await super.getModelInfo();if(e===void 0){let r=A(1);throw Ee("This model has already been unloaded",r)}return e}},El=class extends Ns{constructor(){super(...arguments),this.namespace="llm",this.defaultLoadConfig={},this.loadModelConfigSchema=gw}loadConfigToKVConfig(e){return B1.buildPartialConfig({contextLength:e.contextLength,"llama.evalBatchSize":e.evalBatchSize,"llama.acceleration.offloadRatio":e.gpu?.ratio,numCpuExpertLayersRatio:e.gpu?.numCpuExpertLayersRatio,"load.gpuSplitConfig":Hh(e.gpu),"llama.flashAttention":e.flashAttention,"llama.ropeFrequencyBase":Hn(e.ropeFrequencyBase,0,0),"llama.ropeFrequencyScale":Hn(e.ropeFrequencyScale,0,0),"llama.keepModelInMemory":e.keepModelInMemory,seed:Hn(e.seed,-1,0),"llama.useFp16ForKVCache":e.useFp16ForKVCache,"llama.tryMmap":e.tryMmap,numExperts:e.numExperts,"llama.kCacheQuantizationType":xh({value:e.llamaKCacheQuantizationType,falseDefault:"f16"}),"llama.vCacheQuantizationType":xh({value:e.llamaVCacheQuantizationType,falseDefault:"f16"})})}createDomainSpecificModel(e,r,n,i){return new Cl(e,r,n,i)}createDomainDynamicHandle(e,r,n,i){return new qs(e,r,n,i)}},zs=class{constructor(e,r,n,i){this.content=e,this.reasoningContent=r,this.nonReasoningContent=n,this.pluginIdentifier=i}},_l=class t extends Rs{async collect(e){let r=e.map(({content:s})=>s).join(""),n=e.filter(({isStructural:s})=>!s).filter(({reasoningType:s})=>s==="reasoning").map(({content:s})=>s).join(""),i=e.filter(({isStructural:s})=>!s).filter(({reasoningType:s})=>s==="none").map(({content:s})=>s).join("");return new zs(r,n,i,this.pluginIdentifier)}constructor(e,r){super(),this.pluginIdentifier=e,this.onCancel=r}static create(e,r){let n=new t(e,r);return{ongoingPrediction:n,finished:()=>n.finished(),failed:l=>n.finished(l),push:l=>n.push(l)}}async result(){return await this}async cancel(){this.onCancel()}},dC=o.object({onFirstToken:o.function().optional(),onPredictionFragment:o.function().optional(),onMessage:o.function().optional(),signal:o.instanceof(AbortSignal).optional(),pluginConfig:te.optional(),workingDirectory:o.string().optional()}),fC=em.extend({pluginConfig:te.optional(),workingDirectory:o.string().optional()}),Vs=class{constructor(e,r,n,i,s=new Y("LLMGeneratorHandle")){this.port=e,this.pluginIdentifier=r,this.validator=n,this.associatedPredictionProcess=i,this.logger=s,this.identifier=this.pluginIdentifier}getPluginConfigSpecifier(e,r,n){if(this.associatedPredictionProcess===null)return{type:"direct",config:e??Pp,workingDirectoryPath:r??void 0};if(e!==void 0)throw Ir("Cannot use plugin config with prediction process",j`
442
+ `,qs=class extends $s{constructor(e,r,n,i=new Y("LLMModel")){super(e,r),this.validator=n,this.logger=i,this.internalKVConfigStack={layers:[]},this.internalIgnoreServerSessionConfig=void 0}internalPredict(e,r,n,i,s,a,l){let c=!1,u=!1,h=null,f=!1,d=!1,p=this.port.createChannel("predict",{modelSpecifier:this.specifier,history:e,predictionConfigStack:r,fuzzyPresetIdentifier:i.preset,ignoreServerSessionConfig:this.internalIgnoreServerSessionConfig},m=>{switch(m.type){case"fragment":{u||(u=!0,L(this.logger,"onFirstToken",i.onFirstToken,[])),L(this.logger,"onFragment",i.onPredictionFragment,[m.fragment]),s(m.fragment);break}case"promptProcessingProgress":{L(this.logger,"onPromptProcessingProgress",i.onPromptProcessingProgress,[m.progress]);break}case"toolCallGenerationStart":{h===null?h=0:h++,f=!1,d=!1,L(this.logger,"onToolCallGenerationStart",i.onToolCallRequestStart,[h,{toolCallId:m.toolCallId}]);break}case"toolCallGenerationNameReceived":{f=!0,L(this.logger,"onToolCallGenerationNameReceived",i.onToolCallRequestNameReceived,[h??-1,m.name]);break}case"toolCallGenerationArgumentFragmentGenerated":{d=!0,L(this.logger,"onToolCallGenerationArgumentFragmentGenerated",i.onToolCallRequestArgumentFragmentGenerated,[h??-1,m.content]);break}case"toolCallGenerationEnd":{f||L(this.logger,"onToolCallGenerationNameReceived",i.onToolCallRequestNameReceived,[h??-1,m.toolCallRequest.name]),d||L(this.logger,"onToolCallGenerationArgumentFragmentGenerated",i.onToolCallRequestArgumentFragmentGenerated,[h??-1,JSON.stringify(m.toolCallRequest.arguments??{},null,2)]),L(this.logger,"onToolCallGenerationEnd",i.onToolCallRequestEnd,[h??-1,{toolCallRequest:m.toolCallRequest,rawContent:m.rawContent}]);break}case"toolCallGenerationFailed":{let g=new xr(Os(m.error).message,m.rawContent);L(this.logger,"onToolCallGenerationFailed",i.onToolCallRequestFailure,[h??-1,g]);break}case"success":{c=!0,a(m.stats,m.modelInfo,m.loadModelConfig,m.predictionConfig);break}}},{stack:A(2)});n.subscribeOnce(()=>{c||p.send({type:"cancel"})}),p.onError.subscribeOnce(l)}predictionConfigInputToKVConfig(e){let r;typeof e.structured?.parse=="function"?r={type:"json",jsonSchema:ds(e.structured)}:r=e.structured;let n={...e,structured:r};return U1(n)}createZodParser(e){return r=>{try{return e.parse(JSON.parse(r))}catch(n){throw new Error("Failed to parse structured output: "+JSON.stringify(r),{cause:n})}}}complete(e,r={}){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow("model","complete",["prompt","opts"],[o.string(),nm],[e,r],n);let[i,s]=im(r),[a,l]=Et.create();s.signal!==void 0&&(s.signal.aborted?l():s.signal.addEventListener("abort",()=>{l()},{once:!0}));let c=Rr.safeParse(i.structured),{ongoingPrediction:u,finished:h,failed:f,push:d}=Us.create(l,c.success?this.createZodParser(c.data):null);return this.internalPredict(this.resolveCompletionContext(e),{layers:[...this.internalKVConfigStack.layers,{layerName:"apiOverride",config:this.predictionConfigInputToKVConfig({stopStrings:[],...i})},{layerName:"completeModeFormatting",config:gi.buildPartialConfig({promptTemplate:{type:"jinja",jinjaPromptTemplate:{template:dC},stopStrings:[]}})}]},a,s,p=>d(p),(p,m,g,y)=>h(p,m,g,y),p=>f(p)),u}resolveCompletionContext(e){return{messages:[{role:"user",content:[{type:"text",text:e}]}]}}respond(e,r={}){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow("model","respond",["chat","opts"],[gn,aC],[e,r],n);let[i,s]=Et.create(),[a,l,c]=lC(r);l.signal!==void 0&&(l.signal.aborted?s():l.signal.addEventListener("abort",()=>{s()},{once:!0}));let u=Rr.safeParse(a.structured),{ongoingPrediction:h,finished:f,failed:d,push:p}=Us.create(s,u.success?this.createZodParser(u.data):null);return this.internalPredict(_t.from(e)._internalGetData(),Oa(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig(a)),i,l,m=>p(m),(m,g,y,b)=>f(m,g,y,b),m=>d(m)),h.then(m=>{L(this.logger,"onMessage",c.onMessage,[he.create("assistant",m.content)])},()=>{}),h}async act(e,r,n={}){let i=performance.now(),s=A(1);[e,n]=this.validator.validateMethodParamsOrThrow("model","act",["chat","opts"],[gn,cC],[e,n],s);let[a,{preset:l,...c}]=uC(n);if(a.structured!==void 0&&a.structured.type!=="none"&&r.length>0)throw Ee("Structured output is currently not supported in .act() when there are tools.",s);if(a.structured!==void 0&&a.structured.parse!==void 0)throw Ee("zod schema is not supported in .act().",s);if(a.rawTools!==void 0)throw Ee("`rawTools` is not supported in act. Use `tools` instead",s);let u;r.length===0?u={type:"none"}:u={type:"toolArray",tools:r.map(lc)};let h=Oa(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig({...a,rawTools:u})),f=Oa(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig({...a,rawTools:{type:"none"}}));return await rm(e,r,c,s,this.logger,i,async({allowTools:d,history:p,signal:m,handleFragment:g,handlePromptProcessingProgress:y,handleToolCallGenerationStart:b,handleToolCallGenerationNameReceived:D,handleToolCallGenerationArgumentFragmentGenerated:v,handleToolCallGenerationEnd:S,handleToolCallGenerationFailed:C,handlePredictionEnd:x,handleError:_})=>{let B=this.port.createChannel("predict",{modelSpecifier:this.specifier,history:p,predictionConfigStack:d?h:f,fuzzyPresetIdentifier:l,ignoreServerSessionConfig:this.internalIgnoreServerSessionConfig},w=>{switch(w.type){case"fragment":{g(w.fragment);break}case"promptProcessingProgress":{y(w.progress);break}case"toolCallGenerationStart":{b(w.toolCallId);break}case"toolCallGenerationNameReceived":{D(w.name);break}case"toolCallGenerationArgumentFragmentGenerated":{v(w.content);break}case"toolCallGenerationEnd":{S(w.toolCallRequest,w.rawContent);break}case"toolCallGenerationFailed":{C(Os(w.error),w.rawContent);break}case"success":{x({stats:w.stats,modelInfo:w.modelInfo,loadModelConfig:w.loadModelConfig,predictionConfig:w.predictionConfig});break}}},{stack:s});m.aborted?B.send({type:"cancel"}):m.addEventListener("abort",()=>{B.send({type:"cancel"})},{once:!0}),B.onError.subscribeOnce(_)},({endPacket:d,content:p,nonReasoningContent:m,reasoningContent:g,predictionsPerformed:y})=>new fi(p,g,m,d.stats,d.modelInfo,y,d.loadModelConfig,d.predictionConfig))}async getContextLength(){let e=A(1),r=await this.getLoadConfig(e);return yi.access(r,"contextLength")}async applyPromptTemplate(e,r={}){let n=A(1);return[e,r]=this.validator.validateMethodParamsOrThrow("model","applyPromptTemplate",["history","opts"],[gn,ep],[e,r],n),(await this.port.callRpc("applyPromptTemplate",{specifier:this.specifier,history:_t.from(e)._internalGetData(),predictionConfigStack:this.internalKVConfigStack,opts:r},{stack:n})).formatted}async tokenize(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("model","tokenize","inputString",o.string().or(o.array(o.string())),e,r),Array.isArray(e)?(await Promise.all(e.map(n=>this.port.callRpc("tokenize",{specifier:this.specifier,inputString:n},{stack:r})))).map(n=>n.tokens):(await this.port.callRpc("tokenize",{specifier:this.specifier,inputString:e},{stack:r})).tokens}async countTokens(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("model","countTokens","inputString",o.string(),e,r),(await this.port.callRpc("countTokens",{specifier:this.specifier,inputString:e},{stack:r})).tokenCount}async unstable_preloadDraftModel(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("model","unstable_preloadDraftModel","draftModelKey",o.string(),e,r),await this.port.callRpc("preloadDraftModel",{specifier:this.specifier,draftModelKey:e},{stack:r})}},El=class extends qs{constructor(e,r,n,i=new Y("LLM")){let s={type:"instanceReference",instanceReference:r.instanceReference};super(e,s,n,i),this.identifier=r.identifier,this.path=r.path,this.modelKey=r.modelKey,this.format=r.format,this.displayName=r.displayName,this.sizeBytes=r.sizeBytes,this.vision=r.vision,this.trainedForToolUse=r.trainedForToolUse}async unload(){let e=A(1);await this.port.callRpc("unloadModel",{identifier:this.identifier},{stack:e})}async getModelInfo(){let e=await super.getModelInfo();if(e===void 0){let r=A(1);throw Ee("This model has already been unloaded",r)}return e}},_l=class extends Ns{constructor(){super(...arguments),this.namespace="llm",this.defaultLoadConfig={},this.loadModelConfigSchema=yw}loadConfigToKVConfig(e){return L1.buildPartialConfig({contextLength:e.contextLength,"llama.evalBatchSize":e.evalBatchSize,"llama.acceleration.offloadRatio":e.gpu?.ratio,numCpuExpertLayersRatio:e.gpu?.numCpuExpertLayersRatio,"load.gpuSplitConfig":Yh(e.gpu),"llama.flashAttention":e.flashAttention,"llama.ropeFrequencyBase":Hn(e.ropeFrequencyBase,0,0),"llama.ropeFrequencyScale":Hn(e.ropeFrequencyScale,0,0),"llama.keepModelInMemory":e.keepModelInMemory,seed:Hn(e.seed,-1,0),"llama.useFp16ForKVCache":e.useFp16ForKVCache,"llama.tryMmap":e.tryMmap,numExperts:e.numExperts,"llama.kCacheQuantizationType":kh({value:e.llamaKCacheQuantizationType,falseDefault:"f16"}),"llama.vCacheQuantizationType":kh({value:e.llamaVCacheQuantizationType,falseDefault:"f16"})})}createDomainSpecificModel(e,r,n,i){return new El(e,r,n,i)}createDomainDynamicHandle(e,r,n,i){return new qs(e,r,n,i)}},zs=class{constructor(e,r,n,i){this.content=e,this.reasoningContent=r,this.nonReasoningContent=n,this.pluginIdentifier=i}},xl=class t extends Rs{async collect(e){let r=e.map(({content:s})=>s).join(""),n=e.filter(({isStructural:s})=>!s).filter(({reasoningType:s})=>s==="reasoning").map(({content:s})=>s).join(""),i=e.filter(({isStructural:s})=>!s).filter(({reasoningType:s})=>s==="none").map(({content:s})=>s).join("");return new zs(r,n,i,this.pluginIdentifier)}constructor(e,r){super(),this.pluginIdentifier=e,this.onCancel=r}static create(e,r){let n=new t(e,r);return{ongoingPrediction:n,finished:()=>n.finished(),failed:l=>n.finished(l),push:l=>n.push(l)}}async result(){return await this}async cancel(){this.onCancel()}},fC=o.object({onFirstToken:o.function().optional(),onPredictionFragment:o.function().optional(),onMessage:o.function().optional(),signal:o.instanceof(AbortSignal).optional(),pluginConfig:te.optional(),workingDirectory:o.string().optional()}),hC=tm.extend({pluginConfig:te.optional(),workingDirectory:o.string().optional()}),Vs=class{constructor(e,r,n,i,s=new Y("LLMGeneratorHandle")){this.port=e,this.pluginIdentifier=r,this.validator=n,this.associatedPredictionProcess=i,this.logger=s,this.identifier=this.pluginIdentifier}getPluginConfigSpecifier(e,r,n){if(this.associatedPredictionProcess===null)return{type:"direct",config:e??Tp,workingDirectoryPath:r??void 0};if(e!==void 0)throw Ir("Cannot use plugin config with prediction process",j`
443
443
  You cannot provide a plugin config to the generator handle when it is associated with a
444
444
  prediction process. The plugin config that was configured for the prediction process will
445
445
  be used instead.
@@ -453,7 +453,7 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
453
453
 
454
454
  If you want to use a different working directory, you will need to create a separate
455
455
  GeneratorHandle instead.
456
- `,n);return{type:"predictionProcess",pci:this.associatedPredictionProcess.pci,token:this.associatedPredictionProcess.token}}respond(e,r={}){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle","respond",["chat","opts"],[gn,dC],[e,r],n);let{onFirstToken:i,onPredictionFragment:s,onMessage:a,signal:l,pluginConfig:c,workingDirectory:u}=r,h=!1,f=!1,d=new $a;l!==void 0&&(l.aborted?d.cancel():l.addEventListener("abort",()=>d.cancel(),{once:!0}));let{ongoingPrediction:p,finished:m,failed:g,push:y}=_l.create(this.pluginIdentifier,()=>{d.cancel()}),b=this.port.createChannel("generateWithGenerator",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.getPluginConfigSpecifier(c,u,n),tools:[],history:Et.from(e)._internalGetData()},D=>{switch(D.type){case"fragment":{f||(f=!0,L(this.logger,"onFirstToken",i,[])),L(this.logger,"onPredictionFragment",s,[D.fragment]),y(D.fragment);break}case"success":{h=!0,m();break}}},{stack:n});return b.onError.subscribeOnce(D=>{h||(h=!0,g(D))}),d.subscribeOnce(()=>{h||b.send({type:"cancel"})}),p.then(D=>{L(this.logger,"onMessage",a,[he.create("assistant",D.content)])},()=>{}),p}async act(e,r,n={}){let i=performance.now(),s=A(1);[e,n]=this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle","act",["chat","opts"],[gn,fC],[e,n],s);let{pluginConfig:a,workingDirectory:l,...c}=n,u=r.map(ac);return await tm(e,r,c,s,this.logger,i,async({allowTools:h,history:f,signal:d,handleFragment:p,handlePromptProcessingProgress:m,handleToolCallGenerationStart:g,handleToolCallGenerationNameReceived:y,handleToolCallGenerationArgumentFragmentGenerated:b,handleToolCallGenerationEnd:D,handleToolCallGenerationFailed:v,handlePredictionEnd:S,handleError:C})=>{let x=this.port.createChannel("generateWithGenerator",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.getPluginConfigSpecifier(a,l,s),tools:h?u:[],history:f},_=>{switch(_.type){case"fragment":{p(_.fragment);break}case"promptProcessingProgress":{m(_.progress);break}case"toolCallGenerationStart":{g(_.toolCallId);break}case"toolCallGenerationNameReceived":{y(_.name);break}case"toolCallGenerationArgumentFragmentGenerated":{b(_.content);break}case"toolCallGenerationEnd":{D(_.toolCallRequest,void 0);break}case"toolCallGenerationFailed":{v(new Error("Tool call generation failed"),void 0);break}case"success":{S(void 0);break}}},{stack:s});d.aborted?x.send({type:"cancel"}):d.addEventListener("abort",()=>{x.send({type:"cancel"})},{once:!0}),x.onError.subscribeOnce(C)},({content:h,nonReasoningContent:f,reasoningContent:d})=>new zs(h,d,f,this.pluginIdentifier))}},hC=o.function(),hi=class{constructor(e,r,n,i,s){this.client=e,this.abortSignal=r,this.pluginConfig=n,this.globalPluginConfig=i,this.workingDirectoryPath=s}getWorkingDirectory(){if(this.workingDirectoryPath===null)throw new Error("This prediction process is not attached to a working directory.");return this.workingDirectoryPath}getPluginConfig(e){return e.parse(this.pluginConfig)}getGlobalPluginConfig(e){return e.parse(this.globalPluginConfig)}onAborted(e){this.abortSignal.aborted?e():this.abortSignal.addEventListener("abort",e,{once:!0})}},xl=class extends hi{constructor(e,r,n,i,s,a,l,c){super(e,s,r,n,i),this.toolDefinitions=a,this.connector=l,this.validator=c}getToolDefinitions(){return this.toolDefinitions}fragmentGenerated(e,r={}){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow("GeneratorController","fragmentGenerated",["content","opts"],[o.string(),lp],[e,r],n),this.connector.fragmentGenerated(e,r)}toolCallGenerationStarted({toolCallId:e}={}){this.connector.toolCallGenerationStarted(e)}toolCallGenerationNameReceived(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationNameReceived","toolName",o.string(),e,r),this.connector.toolCallGenerationNameReceived(e)}toolCallGenerationArgumentFragmentGenerated(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationArgumentFragmentGenerated","content",o.string(),e,r),this.connector.toolCallGenerationArgumentFragmentGenerated(e)}toolCallGenerationEnded(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationEnded","toolCallRequest",si,e,r),this.connector.toolCallGenerationEnded(e)}toolCallGenerationFailed(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationFailed","error",o.instanceof(Error),e,r),this.connector.toolCallGenerationFailed(e)}},pC=globalThis&&globalThis.__addDisposableResource||function(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],r&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e},mC=globalThis&&globalThis.__disposeResources||(function(t){return function(e){function r(a){e.error=e.hasError?new t(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(l){return r(l),s()})}else i|=1}catch(l){r(l)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n});function gC(t){switch(typeof t){case"string":return t;case"number":return t.toString();case"boolean":return t?"true":"false";case"undefined":return"undefined";case"object":return t===null?"null":t instanceof Error?t.stack:JSON.stringify(t,null,2);case"bigint":return t.toString();case"symbol":return t.toString();case"function":return t.toString();default:return"unknown"}}function yC(...t){return t.map(gC).join(" ")}function hn(){return`${Date.now()}-${Math.random()}`}var Ws=class{constructor(e,r,n,i,s){this.pluginsPort=e,this.abortSignal=r,this.processingContextIdentifier=n,this.token=i,this.logger=s}handleUpdate(e){this.pluginsPort.callRpc("processingHandleUpdate",{pci:this.processingContextIdentifier,token:this.token,update:e}).catch(r=>{this.logger.error("Failed to send update",r)})}async handleRequest(e){let{response:r}=await this.pluginsPort.callRpc("processingHandleRequest",{pci:this.processingContextIdentifier,token:this.token,request:e});return r}async pullHistory(e){let r=await this.pluginsPort.callRpc("processingPullHistory",{pci:this.processingContextIdentifier,token:this.token,includeCurrent:e});return Et.createRaw(r,!1).asMutableCopy()}async getOrLoadTokenSource(){return(await this.pluginsPort.callRpc("processingGetOrLoadTokenSource",{pci:this.processingContextIdentifier,token:this.token})).tokenSourceIdentifier}async hasStatus(){return await this.pluginsPort.callRpc("processingHasStatus",{pci:this.processingContextIdentifier,token:this.token})}async needsNaming(){return await this.pluginsPort.callRpc("processingNeedsNaming",{pci:this.processingContextIdentifier,token:this.token})}async suggestName(e){await this.pluginsPort.callRpc("processingSuggestName",{pci:this.processingContextIdentifier,token:this.token,name:e})}},Gs=class extends hi{constructor(e,r,n,i,s,a,l,c){super(e,a.abortSignal,r,n,i),this.enabledPluginInfos=s,this.connector=a,this.config=l,this.shouldIncludeCurrentInHistory=c,this.processingControllerHandle={abortSignal:a.abortSignal,sendUpdate:u=>{a.handleUpdate(u)},sendRequest:async u=>{let h=u.type,f=await a.handleRequest(u);if(f.type!==h)throw new Error(`Expected response type ${h}, but got ${f.type}. This is a bug.`);return f}}}sendUpdate(e){this.processingControllerHandle.sendUpdate(e)}async pullHistory(){return await this.connector.pullHistory(this.shouldIncludeCurrentInHistory)}createStatus(e){let r=hn();return this.sendUpdate({type:"status.create",id:r,state:e}),new kl(this.processingControllerHandle,e,r)}addCitations(e){if(Array.isArray(e))for(let r of e)this.createCitationBlock(r.content,{fileName:r.source.name,fileIdentifier:r.source.identifier});else for(let r of e.entries)this.createCitationBlock(r.content,{fileName:r.source.name,fileIdentifier:r.source.identifier})}createCitationBlock(e,r){let n=hn();return this.sendUpdate({type:"citationBlock.create",id:n,citedText:e,...r}),new Fl(this.processingControllerHandle,n)}createDebugInfoBlock(e){let r=hn();return this.sendUpdate({type:"debugInfoBlock.create",id:r,debugInfo:e}),new Pl(this.processingControllerHandle,r)}createContentBlock({roleOverride:e,includeInContext:r=!0,style:n,prefix:i,suffix:s}={}){let a=hn();return this.sendUpdate({type:"contentBlock.create",id:a,roleOverride:e,includeInContext:r,style:n,prefix:i,suffix:s}),new Tl(this.processingControllerHandle,a,e??"assistant")}debug(...e){this.createDebugInfoBlock(yC(...e))}async tokenSource(){let e=await this.connector.getOrLoadTokenSource();switch(e.type){case"model":{let n=await this.client.llm.model(e.identifier);return n.internalIgnoreServerSessionConfig=!0,n.internalKVConfigStack={layers:[{layerName:"conversationSpecific",config:this.config}]},n}case"generator":return this.client.plugins.createGeneratorHandleAssociatedWithPredictionProcess(e.pluginIdentifier,this.connector.processingContextIdentifier,this.connector.token)}}async setSenderName(e){this.sendUpdate({type:"setSenderName",name:e})}guardAbort(){this.abortSignal.throwIfAborted()}async hasStatus(){return await this.connector.hasStatus()}async needsNaming(){return await this.connector.needsNaming()}async suggestName(e){await this.connector.suggestName(e)}async requestConfirmToolCall({callId:e,pluginIdentifier:r,name:n,parameters:i}){let{result:s}=await $D(this.processingControllerHandle.sendRequest({type:"confirmToolCall",callId:e,pluginIdentifier:r,name:n,parameters:i}),this.abortSignal),a=s.type;switch(a){case"allow":return{type:"allow",toolArgsOverride:s.toolArgsOverride};case"deny":return{type:"deny",denyReason:s.denyReason};default:{let l=a;throw new Error(`Unexpected result type ${l}. This is a bug. Please report it.`)}}}createToolStatus(e,r){let n=hn();return this.sendUpdate({type:"toolStatus.create",id:n,callId:e,state:{status:r,customStatus:"",customWarnings:[]}}),new Al(this.processingControllerHandle,n,r)}async startToolUseSession(){let e=this.enabledPluginInfos.filter(({hasToolsProvider:r})=>r).map(({identifier:r})=>r);return await this.client.plugins.startToolUseSessionUsingPredictionProcess(e,this.connector.processingContextIdentifier,this.connector.token)}},kl=class t{constructor(e,r,n,i=0){this.handle=e,this.id=n,this.indentation=i,this.lastSubStatus=this,this.lastState=r}setText(e){this.lastState.text=e,this.handle.sendUpdate({type:"status.update",id:this.id,state:this.lastState})}setState(e){this.lastState=e,this.handle.sendUpdate({type:"status.update",id:this.id,state:e})}remove(){this.handle.sendUpdate({type:"status.remove",id:this.id})}getNestedLastSubStatusBlockId(){let e=this.lastSubStatus;for(;e!==e.lastSubStatus;)e=e.lastSubStatus;return e.id}addSubStatus(e){let r=hn();this.handle.sendUpdate({type:"status.create",id:r,state:e,location:{type:"afterId",id:this.getNestedLastSubStatusBlockId()},indentation:this.indentation+1});let n=new t(this.handle,e,r,this.indentation+1);return this.lastSubStatus=n,n}},Fl=class{constructor(e,r){this.handle=e,this.id=r}},Pl=class{constructor(e,r){this.handle=e,this.id=r}},Tl=class{constructor(e,r,n){this.handle=e,this.id=r,this.role=n}appendText(e,{tokensCount:r,fromDraftModel:n,isStructural:i}={}){if(this.role==="tool")throw new Error("Text cannot be appended to tool blocks.");this.handle.sendUpdate({type:"contentBlock.appendText",id:this.id,text:e,tokensCount:r,fromDraftModel:n,isStructural:i})}appendToolRequest({callId:e,toolCallRequestId:r,name:n,parameters:i,pluginIdentifier:s}){if(this.role!=="assistant")throw new Error(`Tool requests can only be appended to assistant blocks. This is a ${this.role} block.`);this.handle.sendUpdate({type:"contentBlock.appendToolRequest",id:this.id,callId:e,toolCallRequestId:r,name:n,parameters:i,pluginIdentifier:s})}replaceToolRequest({callId:e,toolCallRequestId:r,name:n,parameters:i,pluginIdentifier:s}){if(this.role!=="assistant")throw new Error(`Tool requests can only be replaced in assistant blocks. This is a ${this.role} block.`);this.handle.sendUpdate({type:"contentBlock.replaceToolRequest",id:this.id,callId:e,toolCallRequestId:r,name:n,parameters:i,pluginIdentifier:s})}appendToolResult({callId:e,toolCallRequestId:r,content:n}){if(this.role!=="tool")throw new Error(`Tool results can only be appended to tool blocks. This is a ${this.role} block.`);this.handle.sendUpdate({type:"contentBlock.appendToolResult",id:this.id,callId:e,toolCallRequestId:r,content:n})}replaceText(e){if(this.role==="tool")throw new Error("Text cannot be set in tool blocks.");this.handle.sendUpdate({type:"contentBlock.replaceText",id:this.id,text:e})}setStyle(e){this.handle.sendUpdate({type:"contentBlock.setStyle",id:this.id,style:e})}setPrefix(e){this.handle.sendUpdate({type:"contentBlock.setPrefix",id:this.id,prefix:e})}setSuffix(e){this.handle.sendUpdate({type:"contentBlock.setSuffix",id:this.id,suffix:e})}attachGenInfo(e){this.handle.sendUpdate({type:"contentBlock.attachGenInfo",id:this.id,genInfo:e})}async pipeFrom(e){let r={stack:[],error:void 0,hasError:!1};try{let n=pC(r,new Ps,!1),i=()=>{e.cancel()};this.handle.abortSignal.addEventListener("abort",i),n.register(()=>{this.handle.abortSignal.removeEventListener("abort",i)});for await(let{content:a}of e)this.appendText(a);let s=await e;return this.attachGenInfo({indexedModelIdentifier:s.modelInfo.path,identifier:s.modelInfo.identifier,loadModelConfig:s.loadConfig,predictionConfig:s.predictionConfig,stats:s.stats}),this.handle.abortSignal.throwIfAborted(),s}catch(n){r.error=n,r.hasError=!0}finally{mC(r)}}},Al=class{constructor(e,r,n){this.handle=e,this.id=r,this.customStatus="",this.customWarnings=[],this.status=n}updateState(){this.handle.sendUpdate({type:"toolStatus.update",id:this.id,state:{status:this.status,customStatus:this.customStatus,customWarnings:this.customWarnings}})}setCustomStatusText(e){this.customStatus=e,this.updateState()}addWarning(e){this.customWarnings.push(e),this.updateState()}setStatus(e){this.status=e,this.updateState()}appendArgumentFragment(e){this.handle.sendUpdate({type:"toolStatus.argumentFragment",id:this.id,content:e})}},Ol=class extends hi{constructor(e,r,n,i,s){super(e,r,n,i,s)}},Il=class{constructor(e,r){this.channel=e,this.taskId=r}fragmentGenerated(e,r){this.channel.send({type:"fragmentGenerated",taskId:this.taskId,content:e,opts:r})}toolCallGenerationStarted(e){this.channel.send({type:"toolCallGenerationStarted",taskId:this.taskId,toolCallId:e})}toolCallGenerationNameReceived(e){this.channel.send({type:"toolCallGenerationNameReceived",taskId:this.taskId,toolName:e})}toolCallGenerationArgumentFragmentGenerated(e){this.channel.send({type:"toolCallGenerationArgumentFragmentGenerated",taskId:this.taskId,content:e})}toolCallGenerationEnded(e){this.channel.send({type:"toolCallGenerationEnded",taskId:this.taskId,toolCallRequest:e})}toolCallGenerationFailed(e){this.channel.send({type:"toolCallGenerationFailed",taskId:this.taskId,error:Sr(e)})}},Rl=class{constructor(e,r,n,i){this.port=e,this.client=r,this.rootLogger=n,this.validator=i}setPromptPreprocessor(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","registerPromptPreprocessor","promptPreprocessor",o.function(),e,r);let n=new Y("PromptPreprocessor",this.rootLogger);n.info("Register with LM Studio");let i=new Map,s=this.port.createChannel("setPromptPreprocessor",void 0,a=>{switch(a.type){case"preprocess":{let l=new Y(`Request (${a.taskId.substring(0,6)})`,n);l.info("New preprocess request received.");let c=new AbortController,u=new Ws(this.port,c.signal,a.pci,a.token,l),h=he.createRaw(a.input,!1),f=new Gs(this.client,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath,a.enabledPluginInfos,u,a.config,!1);i.set(a.taskId,{cancel:()=>{c.abort()},taskLogger:l}),e(f,h.asMutableCopy()).then(d=>{l.info("Preprocess request completed.");let p=o.union([o.string(),o.custom(y=>y instanceof he)]).safeParse(d);if(!p.success)throw new Error("PromptPreprocessor returned an invalid value:"+it.prettyPrintZod("result",p.error));let m=p.data,g;if(typeof m=="string"){let y=h.asMutableCopy();y.replaceText(m),g=y.getRaw()}else g=m.getRaw();s.send({type:"complete",taskId:a.taskId,processed:g})}).catch(d=>{if(d.name==="AbortError"){n.info("Request successfully aborted."),s.send({type:"aborted",taskId:a.taskId});return}n.warn("Preprocessing failed.",d),s.send({type:"error",taskId:a.taskId,error:Sr(d)})}).finally(()=>{i.delete(a.taskId)});break}case"abort":{let l=i.get(a.taskId);l!==void 0&&(l.taskLogger.info("Received abort request."),l.cancel(),i.delete(a.taskId));break}}},{stack:r})}setPredictionLoopHandler(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","setPredictionLoopHandler","predictionLoopHandler",o.function(),e,r);let n=new Y(" PredictionLoopHandler",this.rootLogger);n.info("Register with LM Studio");let i=new Map,s=this.port.createChannel("setPredictionLoopHandler",void 0,a=>{switch(a.type){case"handlePredictionLoop":{let l=new Y(`Request (${a.taskId.substring(0,6)})`,n);l.info("New prediction loop handling request received.");let c=new AbortController,u=new Ws(this.port,c.signal,a.pci,a.token,l),h=new Gs(this.client,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath,a.enabledPluginInfos,u,a.config,!0);i.set(a.taskId,{cancel:()=>{c.abort()},taskLogger:l}),e(h).then(()=>{s.send({type:"complete",taskId:a.taskId})}).catch(f=>{if(f.name==="AbortError"){n.info("Request successfully aborted."),s.send({type:"aborted",taskId:a.taskId});return}n.warn("Generation failed.",f),s.send({type:"error",taskId:a.taskId,error:Sr(f)})}).finally(()=>{i.delete(a.taskId)});break}case"abort":{let l=i.get(a.taskId);l!==void 0&&(l.taskLogger.info("Received abort request."),l.cancel(),i.delete(a.taskId));break}}},{stack:r})}async setConfigSchematics(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","setConfigSchematics","configSchematics",o.instanceof(ai),e,r),await this.port.callRpc("setConfigSchematics",{schematics:e.serialize()},{stack:r})}async setGlobalConfigSchematics(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","setGlobalConfigSchematics","globalConfigSchematics",o.instanceof(ai),e,r),await this.port.callRpc("setGlobalConfigSchematics",{schematics:e.serialize()},{stack:r})}setToolsProvider(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","setToolsProvider","toolsProvider",o.function(),e,r),new Y("Tools Prvdr.",this.rootLogger).info("Register with LM Studio");let i=new Map,s=this.port.createChannel("setToolsProvider",void 0,a=>{let l=a.type;switch(l){case"initSession":{let c=a.sessionId,u=new AbortController,h={tools:null,ongoingToolCalls:new Map,discarded:!1,abortController:u};i.set(c,h);let f=new Ol(this.client,u.signal,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath);e(f).then(d=>{let p=d.map(ac);h.discarded||(s.send({type:"sessionInitialized",sessionId:c,toolDefinitions:p}),h.tools=new Map(d.map(m=>[m.name,m])))},d=>{h.discarded||(s.send({type:"sessionInitializationFailed",sessionId:c,error:Sr(d)}),h.discarded=!0,i.delete(c))});break}case"discardSession":{let c=a.sessionId,u=i.get(c);if(u===void 0)return;u.discarded=!0,u.abortController.abort(),i.delete(c);break}case"callTool":{let c=a.sessionId,u=i.get(c);if(u===void 0)return;if(u.tools===null)throw new Error("Tool called before initialization completed. This is unexpected.");let h=u.tools.get(a.toolName);if(h===void 0)throw new Error(`Tool ${a.toolName} not found.`);let f=a.callId,d={settled:!1,abortController:new AbortController};u.ongoingToolCalls.set(f,d),new Y(`Tool (${a.toolName})`,this.rootLogger);let p={status(m){s.send({type:"toolCallStatus",sessionId:c,callId:f,statusText:m})},warn(m){s.send({type:"toolCallWarn",sessionId:c,callId:f,warnText:m})},signal:d.abortController.signal,callId:0};(async()=>await h.implementation(a.parameters,p))().then(m=>{if(!u.discarded&&!d.settled&&!d.abortController.signal.aborted){m===void 0&&(m="undefined",s.send({type:"toolCallWarn",sessionId:c,callId:f,warnText:j`
456
+ `,n);return{type:"predictionProcess",pci:this.associatedPredictionProcess.pci,token:this.associatedPredictionProcess.token}}respond(e,r={}){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle","respond",["chat","opts"],[gn,fC],[e,r],n);let{onFirstToken:i,onPredictionFragment:s,onMessage:a,signal:l,pluginConfig:c,workingDirectory:u}=r,h=!1,f=!1,d=new Ua;l!==void 0&&(l.aborted?d.cancel():l.addEventListener("abort",()=>d.cancel(),{once:!0}));let{ongoingPrediction:p,finished:m,failed:g,push:y}=xl.create(this.pluginIdentifier,()=>{d.cancel()}),b=this.port.createChannel("generateWithGenerator",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.getPluginConfigSpecifier(c,u,n),tools:[],history:_t.from(e)._internalGetData()},D=>{switch(D.type){case"fragment":{f||(f=!0,L(this.logger,"onFirstToken",i,[])),L(this.logger,"onPredictionFragment",s,[D.fragment]),y(D.fragment);break}case"success":{h=!0,m();break}}},{stack:n});return b.onError.subscribeOnce(D=>{h||(h=!0,g(D))}),d.subscribeOnce(()=>{h||b.send({type:"cancel"})}),p.then(D=>{L(this.logger,"onMessage",a,[he.create("assistant",D.content)])},()=>{}),p}async act(e,r,n={}){let i=performance.now(),s=A(1);[e,n]=this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle","act",["chat","opts"],[gn,hC],[e,n],s);let{pluginConfig:a,workingDirectory:l,...c}=n,u=r.map(lc);return await rm(e,r,c,s,this.logger,i,async({allowTools:h,history:f,signal:d,handleFragment:p,handlePromptProcessingProgress:m,handleToolCallGenerationStart:g,handleToolCallGenerationNameReceived:y,handleToolCallGenerationArgumentFragmentGenerated:b,handleToolCallGenerationEnd:D,handleToolCallGenerationFailed:v,handlePredictionEnd:S,handleError:C})=>{let x=this.port.createChannel("generateWithGenerator",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.getPluginConfigSpecifier(a,l,s),tools:h?u:[],history:f},_=>{switch(_.type){case"fragment":{p(_.fragment);break}case"promptProcessingProgress":{m(_.progress);break}case"toolCallGenerationStart":{g(_.toolCallId);break}case"toolCallGenerationNameReceived":{y(_.name);break}case"toolCallGenerationArgumentFragmentGenerated":{b(_.content);break}case"toolCallGenerationEnd":{D(_.toolCallRequest,void 0);break}case"toolCallGenerationFailed":{v(new Error("Tool call generation failed"),void 0);break}case"success":{S(void 0);break}}},{stack:s});d.aborted?x.send({type:"cancel"}):d.addEventListener("abort",()=>{x.send({type:"cancel"})},{once:!0}),x.onError.subscribeOnce(C)},({content:h,nonReasoningContent:f,reasoningContent:d})=>new zs(h,d,f,this.pluginIdentifier))}},pC=o.function(),hi=class{constructor(e,r,n,i,s){this.client=e,this.abortSignal=r,this.pluginConfig=n,this.globalPluginConfig=i,this.workingDirectoryPath=s}getWorkingDirectory(){if(this.workingDirectoryPath===null)throw new Error("This prediction process is not attached to a working directory.");return this.workingDirectoryPath}getPluginConfig(e){return e.parse(this.pluginConfig)}getGlobalPluginConfig(e){return e.parse(this.globalPluginConfig)}onAborted(e){this.abortSignal.aborted?e():this.abortSignal.addEventListener("abort",e,{once:!0})}},kl=class extends hi{constructor(e,r,n,i,s,a,l,c){super(e,s,r,n,i),this.toolDefinitions=a,this.connector=l,this.validator=c}getToolDefinitions(){return this.toolDefinitions}fragmentGenerated(e,r={}){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow("GeneratorController","fragmentGenerated",["content","opts"],[o.string(),cp],[e,r],n),this.connector.fragmentGenerated(e,r)}toolCallGenerationStarted({toolCallId:e}={}){this.connector.toolCallGenerationStarted(e)}toolCallGenerationNameReceived(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationNameReceived","toolName",o.string(),e,r),this.connector.toolCallGenerationNameReceived(e)}toolCallGenerationArgumentFragmentGenerated(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationArgumentFragmentGenerated","content",o.string(),e,r),this.connector.toolCallGenerationArgumentFragmentGenerated(e)}toolCallGenerationEnded(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationEnded","toolCallRequest",si,e,r),this.connector.toolCallGenerationEnded(e)}toolCallGenerationFailed(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationFailed","error",o.instanceof(Error),e,r),this.connector.toolCallGenerationFailed(e)}},mC=globalThis&&globalThis.__addDisposableResource||function(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],r&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e},gC=globalThis&&globalThis.__disposeResources||(function(t){return function(e){function r(a){e.error=e.hasError?new t(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(l){return r(l),s()})}else i|=1}catch(l){r(l)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n});function yC(t){switch(typeof t){case"string":return t;case"number":return t.toString();case"boolean":return t?"true":"false";case"undefined":return"undefined";case"object":return t===null?"null":t instanceof Error?t.stack:JSON.stringify(t,null,2);case"bigint":return t.toString();case"symbol":return t.toString();case"function":return t.toString();default:return"unknown"}}function bC(...t){return t.map(yC).join(" ")}function hn(){return`${Date.now()}-${Math.random()}`}var Ws=class{constructor(e,r,n,i,s){this.pluginsPort=e,this.abortSignal=r,this.processingContextIdentifier=n,this.token=i,this.logger=s}handleUpdate(e){this.pluginsPort.callRpc("processingHandleUpdate",{pci:this.processingContextIdentifier,token:this.token,update:e}).catch(r=>{this.logger.error("Failed to send update",r)})}async handleRequest(e){let{response:r}=await this.pluginsPort.callRpc("processingHandleRequest",{pci:this.processingContextIdentifier,token:this.token,request:e});return r}async pullHistory(e){let r=await this.pluginsPort.callRpc("processingPullHistory",{pci:this.processingContextIdentifier,token:this.token,includeCurrent:e});return _t.createRaw(r,!1).asMutableCopy()}async getOrLoadTokenSource(){return(await this.pluginsPort.callRpc("processingGetOrLoadTokenSource",{pci:this.processingContextIdentifier,token:this.token})).tokenSourceIdentifier}async hasStatus(){return await this.pluginsPort.callRpc("processingHasStatus",{pci:this.processingContextIdentifier,token:this.token})}async needsNaming(){return await this.pluginsPort.callRpc("processingNeedsNaming",{pci:this.processingContextIdentifier,token:this.token})}async suggestName(e){await this.pluginsPort.callRpc("processingSuggestName",{pci:this.processingContextIdentifier,token:this.token,name:e})}},Gs=class extends hi{constructor(e,r,n,i,s,a,l,c){super(e,a.abortSignal,r,n,i),this.enabledPluginInfos=s,this.connector=a,this.config=l,this.shouldIncludeCurrentInHistory=c,this.processingControllerHandle={abortSignal:a.abortSignal,sendUpdate:u=>{a.handleUpdate(u)},sendRequest:async u=>{let h=u.type,f=await a.handleRequest(u);if(f.type!==h)throw new Error(`Expected response type ${h}, but got ${f.type}. This is a bug.`);return f}}}sendUpdate(e){this.processingControllerHandle.sendUpdate(e)}async pullHistory(){return await this.connector.pullHistory(this.shouldIncludeCurrentInHistory)}createStatus(e){let r=hn();return this.sendUpdate({type:"status.create",id:r,state:e}),new Fl(this.processingControllerHandle,e,r)}addCitations(e){if(Array.isArray(e))for(let r of e)this.createCitationBlock(r.content,{fileName:r.source.name,fileIdentifier:r.source.identifier});else for(let r of e.entries)this.createCitationBlock(r.content,{fileName:r.source.name,fileIdentifier:r.source.identifier})}createCitationBlock(e,r){let n=hn();return this.sendUpdate({type:"citationBlock.create",id:n,citedText:e,...r}),new Pl(this.processingControllerHandle,n)}createDebugInfoBlock(e){let r=hn();return this.sendUpdate({type:"debugInfoBlock.create",id:r,debugInfo:e}),new Tl(this.processingControllerHandle,r)}createContentBlock({roleOverride:e,includeInContext:r=!0,style:n,prefix:i,suffix:s}={}){let a=hn();return this.sendUpdate({type:"contentBlock.create",id:a,roleOverride:e,includeInContext:r,style:n,prefix:i,suffix:s}),new Al(this.processingControllerHandle,a,e??"assistant")}debug(...e){this.createDebugInfoBlock(bC(...e))}async tokenSource(){let e=await this.connector.getOrLoadTokenSource();switch(e.type){case"model":{let n=await this.client.llm.model(e.identifier);return n.internalIgnoreServerSessionConfig=!0,n.internalKVConfigStack={layers:[{layerName:"conversationSpecific",config:this.config}]},n}case"generator":return this.client.plugins.createGeneratorHandleAssociatedWithPredictionProcess(e.pluginIdentifier,this.connector.processingContextIdentifier,this.connector.token)}}async setSenderName(e){this.sendUpdate({type:"setSenderName",name:e})}guardAbort(){this.abortSignal.throwIfAborted()}async hasStatus(){return await this.connector.hasStatus()}async needsNaming(){return await this.connector.needsNaming()}async suggestName(e){await this.connector.suggestName(e)}async requestConfirmToolCall({callId:e,pluginIdentifier:r,name:n,parameters:i}){let{result:s}=await UD(this.processingControllerHandle.sendRequest({type:"confirmToolCall",callId:e,pluginIdentifier:r,name:n,parameters:i}),this.abortSignal),a=s.type;switch(a){case"allow":return{type:"allow",toolArgsOverride:s.toolArgsOverride};case"deny":return{type:"deny",denyReason:s.denyReason};default:{let l=a;throw new Error(`Unexpected result type ${l}. This is a bug. Please report it.`)}}}createToolStatus(e,r){let n=hn();return this.sendUpdate({type:"toolStatus.create",id:n,callId:e,state:{status:r,customStatus:"",customWarnings:[]}}),new Ol(this.processingControllerHandle,n,r)}async startToolUseSession(){let e=this.enabledPluginInfos.filter(({hasToolsProvider:r})=>r).map(({identifier:r})=>r);return await this.client.plugins.startToolUseSessionUsingPredictionProcess(e,this.connector.processingContextIdentifier,this.connector.token)}},Fl=class t{constructor(e,r,n,i=0){this.handle=e,this.id=n,this.indentation=i,this.lastSubStatus=this,this.lastState=r}setText(e){this.lastState.text=e,this.handle.sendUpdate({type:"status.update",id:this.id,state:this.lastState})}setState(e){this.lastState=e,this.handle.sendUpdate({type:"status.update",id:this.id,state:e})}remove(){this.handle.sendUpdate({type:"status.remove",id:this.id})}getNestedLastSubStatusBlockId(){let e=this.lastSubStatus;for(;e!==e.lastSubStatus;)e=e.lastSubStatus;return e.id}addSubStatus(e){let r=hn();this.handle.sendUpdate({type:"status.create",id:r,state:e,location:{type:"afterId",id:this.getNestedLastSubStatusBlockId()},indentation:this.indentation+1});let n=new t(this.handle,e,r,this.indentation+1);return this.lastSubStatus=n,n}},Pl=class{constructor(e,r){this.handle=e,this.id=r}},Tl=class{constructor(e,r){this.handle=e,this.id=r}},Al=class{constructor(e,r,n){this.handle=e,this.id=r,this.role=n}appendText(e,{tokensCount:r,fromDraftModel:n,isStructural:i}={}){if(this.role==="tool")throw new Error("Text cannot be appended to tool blocks.");this.handle.sendUpdate({type:"contentBlock.appendText",id:this.id,text:e,tokensCount:r,fromDraftModel:n,isStructural:i})}appendToolRequest({callId:e,toolCallRequestId:r,name:n,parameters:i,pluginIdentifier:s}){if(this.role!=="assistant")throw new Error(`Tool requests can only be appended to assistant blocks. This is a ${this.role} block.`);this.handle.sendUpdate({type:"contentBlock.appendToolRequest",id:this.id,callId:e,toolCallRequestId:r,name:n,parameters:i,pluginIdentifier:s})}replaceToolRequest({callId:e,toolCallRequestId:r,name:n,parameters:i,pluginIdentifier:s}){if(this.role!=="assistant")throw new Error(`Tool requests can only be replaced in assistant blocks. This is a ${this.role} block.`);this.handle.sendUpdate({type:"contentBlock.replaceToolRequest",id:this.id,callId:e,toolCallRequestId:r,name:n,parameters:i,pluginIdentifier:s})}appendToolResult({callId:e,toolCallRequestId:r,content:n}){if(this.role!=="tool")throw new Error(`Tool results can only be appended to tool blocks. This is a ${this.role} block.`);this.handle.sendUpdate({type:"contentBlock.appendToolResult",id:this.id,callId:e,toolCallRequestId:r,content:n})}replaceText(e){if(this.role==="tool")throw new Error("Text cannot be set in tool blocks.");this.handle.sendUpdate({type:"contentBlock.replaceText",id:this.id,text:e})}setStyle(e){this.handle.sendUpdate({type:"contentBlock.setStyle",id:this.id,style:e})}setPrefix(e){this.handle.sendUpdate({type:"contentBlock.setPrefix",id:this.id,prefix:e})}setSuffix(e){this.handle.sendUpdate({type:"contentBlock.setSuffix",id:this.id,suffix:e})}attachGenInfo(e){this.handle.sendUpdate({type:"contentBlock.attachGenInfo",id:this.id,genInfo:e})}async pipeFrom(e){let r={stack:[],error:void 0,hasError:!1};try{let n=mC(r,new Ps,!1),i=()=>{e.cancel()};this.handle.abortSignal.addEventListener("abort",i),n.register(()=>{this.handle.abortSignal.removeEventListener("abort",i)});for await(let{content:a}of e)this.appendText(a);let s=await e;return this.attachGenInfo({indexedModelIdentifier:s.modelInfo.path,identifier:s.modelInfo.identifier,loadModelConfig:s.loadConfig,predictionConfig:s.predictionConfig,stats:s.stats}),this.handle.abortSignal.throwIfAborted(),s}catch(n){r.error=n,r.hasError=!0}finally{gC(r)}}},Ol=class{constructor(e,r,n){this.handle=e,this.id=r,this.customStatus="",this.customWarnings=[],this.status=n}updateState(){this.handle.sendUpdate({type:"toolStatus.update",id:this.id,state:{status:this.status,customStatus:this.customStatus,customWarnings:this.customWarnings}})}setCustomStatusText(e){this.customStatus=e,this.updateState()}addWarning(e){this.customWarnings.push(e),this.updateState()}setStatus(e){this.status=e,this.updateState()}appendArgumentFragment(e){this.handle.sendUpdate({type:"toolStatus.argumentFragment",id:this.id,content:e})}},Il=class extends hi{constructor(e,r,n,i,s){super(e,r,n,i,s)}},Rl=class{constructor(e,r){this.channel=e,this.taskId=r}fragmentGenerated(e,r){this.channel.send({type:"fragmentGenerated",taskId:this.taskId,content:e,opts:r})}toolCallGenerationStarted(e){this.channel.send({type:"toolCallGenerationStarted",taskId:this.taskId,toolCallId:e})}toolCallGenerationNameReceived(e){this.channel.send({type:"toolCallGenerationNameReceived",taskId:this.taskId,toolName:e})}toolCallGenerationArgumentFragmentGenerated(e){this.channel.send({type:"toolCallGenerationArgumentFragmentGenerated",taskId:this.taskId,content:e})}toolCallGenerationEnded(e){this.channel.send({type:"toolCallGenerationEnded",taskId:this.taskId,toolCallRequest:e})}toolCallGenerationFailed(e){this.channel.send({type:"toolCallGenerationFailed",taskId:this.taskId,error:Sr(e)})}},Ml=class{constructor(e,r,n,i){this.port=e,this.client=r,this.rootLogger=n,this.validator=i}setPromptPreprocessor(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","registerPromptPreprocessor","promptPreprocessor",o.function(),e,r);let n=new Y("PromptPreprocessor",this.rootLogger);n.info("Register with LM Studio");let i=new Map,s=this.port.createChannel("setPromptPreprocessor",void 0,a=>{switch(a.type){case"preprocess":{let l=new Y(`Request (${a.taskId.substring(0,6)})`,n);l.info("New preprocess request received.");let c=new AbortController,u=new Ws(this.port,c.signal,a.pci,a.token,l),h=he.createRaw(a.input,!1),f=new Gs(this.client,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath,a.enabledPluginInfos,u,a.config,!1);i.set(a.taskId,{cancel:()=>{c.abort()},taskLogger:l}),e(f,h.asMutableCopy()).then(d=>{l.info("Preprocess request completed.");let p=o.union([o.string(),o.custom(y=>y instanceof he)]).safeParse(d);if(!p.success)throw new Error("PromptPreprocessor returned an invalid value:"+ot.prettyPrintZod("result",p.error));let m=p.data,g;if(typeof m=="string"){let y=h.asMutableCopy();y.replaceText(m),g=y.getRaw()}else g=m.getRaw();s.send({type:"complete",taskId:a.taskId,processed:g})}).catch(d=>{if(d.name==="AbortError"){n.info("Request successfully aborted."),s.send({type:"aborted",taskId:a.taskId});return}n.warn("Preprocessing failed.",d),s.send({type:"error",taskId:a.taskId,error:Sr(d)})}).finally(()=>{i.delete(a.taskId)});break}case"abort":{let l=i.get(a.taskId);l!==void 0&&(l.taskLogger.info("Received abort request."),l.cancel(),i.delete(a.taskId));break}}},{stack:r})}setPredictionLoopHandler(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","setPredictionLoopHandler","predictionLoopHandler",o.function(),e,r);let n=new Y(" PredictionLoopHandler",this.rootLogger);n.info("Register with LM Studio");let i=new Map,s=this.port.createChannel("setPredictionLoopHandler",void 0,a=>{switch(a.type){case"handlePredictionLoop":{let l=new Y(`Request (${a.taskId.substring(0,6)})`,n);l.info("New prediction loop handling request received.");let c=new AbortController,u=new Ws(this.port,c.signal,a.pci,a.token,l),h=new Gs(this.client,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath,a.enabledPluginInfos,u,a.config,!0);i.set(a.taskId,{cancel:()=>{c.abort()},taskLogger:l}),e(h).then(()=>{s.send({type:"complete",taskId:a.taskId})}).catch(f=>{if(f.name==="AbortError"){n.info("Request successfully aborted."),s.send({type:"aborted",taskId:a.taskId});return}n.warn("Generation failed.",f),s.send({type:"error",taskId:a.taskId,error:Sr(f)})}).finally(()=>{i.delete(a.taskId)});break}case"abort":{let l=i.get(a.taskId);l!==void 0&&(l.taskLogger.info("Received abort request."),l.cancel(),i.delete(a.taskId));break}}},{stack:r})}async setConfigSchematics(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","setConfigSchematics","configSchematics",o.instanceof(ai),e,r),await this.port.callRpc("setConfigSchematics",{schematics:e.serialize()},{stack:r})}async setGlobalConfigSchematics(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","setGlobalConfigSchematics","globalConfigSchematics",o.instanceof(ai),e,r),await this.port.callRpc("setGlobalConfigSchematics",{schematics:e.serialize()},{stack:r})}setToolsProvider(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","setToolsProvider","toolsProvider",o.function(),e,r),new Y("Tools Prvdr.",this.rootLogger).info("Register with LM Studio");let i=new Map,s=this.port.createChannel("setToolsProvider",void 0,a=>{let l=a.type;switch(l){case"initSession":{let c=a.sessionId,u=new AbortController,h={tools:null,ongoingToolCalls:new Map,discarded:!1,abortController:u};i.set(c,h);let f=new Il(this.client,u.signal,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath);e(f).then(d=>{let p=d.map(lc);h.discarded||(s.send({type:"sessionInitialized",sessionId:c,toolDefinitions:p}),h.tools=new Map(d.map(m=>[m.name,m])))},d=>{h.discarded||(s.send({type:"sessionInitializationFailed",sessionId:c,error:Sr(d)}),h.discarded=!0,i.delete(c))});break}case"discardSession":{let c=a.sessionId,u=i.get(c);if(u===void 0)return;u.discarded=!0,u.abortController.abort(),i.delete(c);break}case"callTool":{let c=a.sessionId,u=i.get(c);if(u===void 0)return;if(u.tools===null)throw new Error("Tool called before initialization completed. This is unexpected.");let h=u.tools.get(a.toolName);if(h===void 0)throw new Error(`Tool ${a.toolName} not found.`);let f=a.callId,d={settled:!1,abortController:new AbortController};u.ongoingToolCalls.set(f,d),new Y(`Tool (${a.toolName})`,this.rootLogger);let p={status(m){s.send({type:"toolCallStatus",sessionId:c,callId:f,statusText:m})},warn(m){s.send({type:"toolCallWarn",sessionId:c,callId:f,warnText:m})},signal:d.abortController.signal,callId:0};(async()=>await h.implementation(a.parameters,p))().then(m=>{if(!u.discarded&&!d.settled&&!d.abortController.signal.aborted){m===void 0&&(m="undefined",s.send({type:"toolCallWarn",sessionId:c,callId:f,warnText:j`
457
457
  Tool call returned undefined. This is not expected as the model always expects
458
458
  a result. If you don't want to return anything, you can just return a string
459
459
  reporting that the tool call was successful. For example: "operation
@@ -464,16 +464,16 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
464
464
  Tool call succeeded, but returned a value that is not JSON serializable. In
465
465
  order to provide the result to the model, return values of tools must be JSON
466
466
  serializable. In this case, we will give the model string "${m}".
467
- `})}s.send({type:"toolCallComplete",sessionId:c,callId:f,result:m}),d.settled=!0,u.ongoingToolCalls.delete(f)}},m=>{u.discarded||d.settled||d.abortController.signal.aborted||(s.send({type:"toolCallError",sessionId:c,callId:f,error:Sr(m)}),d.settled=!0,u.ongoingToolCalls.delete(f))});break}case"abortToolCall":{let c=a.sessionId,u=a.callId,h=i.get(c);if(h===void 0)return;let f=h.ongoingToolCalls.get(u);if(f===void 0)return;f.settled=!0,f.abortController.abort(),h.ongoingToolCalls.delete(u);break}default:{let c=l;throw new Error(`Unexpected message type: ${c}`)}}})}setGenerator(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","setGenerator","generator",hC,e,r);let n=new Y("Generator",this.rootLogger);n.info("Register with LM Studio");let i=new Map,s=this.port.createChannel("setGenerator",void 0,a=>{let l=a.type;switch(l){case"generate":{let c=new Y(`Request (${a.taskId.substring(0,6)})`,n);c.info("New generate request received.");let u=new AbortController,h=new Il(s,a.taskId),f=new xl(this.client,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath,u.signal,a.toolDefinitions,h,this.validator);i.set(a.taskId,{cancel:()=>{u.abort()},taskLogger:c});let d=Et.createRaw(a.input,!1);e(f,d).then(p=>{p!==void 0&&c.warnText`
467
+ `})}s.send({type:"toolCallComplete",sessionId:c,callId:f,result:m}),d.settled=!0,u.ongoingToolCalls.delete(f)}},m=>{u.discarded||d.settled||d.abortController.signal.aborted||(s.send({type:"toolCallError",sessionId:c,callId:f,error:Sr(m)}),d.settled=!0,u.ongoingToolCalls.delete(f))});break}case"abortToolCall":{let c=a.sessionId,u=a.callId,h=i.get(c);if(h===void 0)return;let f=h.ongoingToolCalls.get(u);if(f===void 0)return;f.settled=!0,f.abortController.abort(),h.ongoingToolCalls.delete(u);break}default:{let c=l;throw new Error(`Unexpected message type: ${c}`)}}})}setGenerator(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","setGenerator","generator",pC,e,r);let n=new Y("Generator",this.rootLogger);n.info("Register with LM Studio");let i=new Map,s=this.port.createChannel("setGenerator",void 0,a=>{let l=a.type;switch(l){case"generate":{let c=new Y(`Request (${a.taskId.substring(0,6)})`,n);c.info("New generate request received.");let u=new AbortController,h=new Rl(s,a.taskId),f=new kl(this.client,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath,u.signal,a.toolDefinitions,h,this.validator);i.set(a.taskId,{cancel:()=>{u.abort()},taskLogger:c});let d=_t.createRaw(a.input,!1);e(f,d).then(p=>{p!==void 0&&c.warnText`
468
468
  The generator has returned a value. This it not expected. You should report
469
469
  generated content using method on the controller. The returned value will be
470
470
  ignored.
471
- `,s.send({type:"complete",taskId:a.taskId})},p=>{p.name==="AbortError"?(c.info("Request successfully aborted."),s.send({type:"aborted",taskId:a.taskId})):(s.send({type:"error",taskId:a.taskId,error:Sr(p)}),c.warn("Generation failed.",p))}).finally(()=>{i.delete(a.taskId)});break}case"abort":{let c=i.get(a.taskId);c!==void 0&&(c.taskLogger.info("Received abort request."),c.cancel(),i.delete(a.taskId));break}default:{let c=l;throw new Error(`Unexpected message type: ${c}`)}}})}async initCompleted(){let e=A(1);await this.port.callRpc("pluginInitCompleted",void 0,{stack:e})}},bC=globalThis&&globalThis.__addDisposableResource||function(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],r&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e},vC=globalThis&&globalThis.__disposeResources||(function(t){return function(e){function r(a){e.error=e.hasError?new t(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(l){return r(l),s()})}else i|=1}catch(l){r(l)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n}),Zs=class t{static async create(e,r,n,i,s){let a=new t(e,r,n,i);return await a.init(s),a}constructor(e,r,n,i){this.pluginsPort=e,this.pluginIdentifier=r,this.pluginConfigSpecifier=n,this.logger=i,this.status="initializing",this.poison=null,this.ongoingToolCalls=new Map,this.callIdGiver=new Ts(0)}async init(e){let{promise:r,resolve:n,reject:i}=re(),s=this.pluginsPort.createChannel("startToolUseSession",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.pluginConfigSpecifier},a=>{let l=a.type;switch(l){case"sessionReady":{if(this.status!=="initializing"){this.logger.error("Received sessionReady message while not initializing");return}this.status="ready",n(),this.tools=a.toolDefinitions.map(c=>this.makeTool(c));break}case"toolCallComplete":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.resolve(a.result);break}case"toolCallError":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.reject(Os(a.error));break}case"toolCallStatus":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.reportStatus(a.statusText);break}case"toolCallWarn":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.reportWarning(a.warnText);break}default:{let c=l;this.logger.warn(`Received unexpected message type in tool use session: ${c}`)}}},{stack:e});s.onError.subscribeOnce(a=>{this.status==="initializing"?i(a):(this.logger.error("Tool use session error.",a),this.poison=a);for(let l of this.ongoingToolCalls.values())l.reject(a);this.status="disposed"}),s.onClose.subscribeOnce(()=>{let a;this.status==="initializing"?(a=new Error("Tool use session channel closed unexpectedly during initialization."),i(a)):(a=new Error("Tool use session has already ended."),this.poison=a);for(let l of this.ongoingToolCalls.values())l.reject(a);this.status="disposed"}),this.channel=s,await r}[Symbol.dispose](){if(this.status!=="disposed"){this.channel.send({type:"discardSession"}),this.status="disposed";let e=new Error("Session disposed by client.");for(let r of this.ongoingToolCalls.values())r.reject(e);this.poison=e}}makeTool(e){return Y1({name:e.function.name,description:e.function.description??"",pluginIdentifier:this.pluginIdentifier,parametersJsonSchema:e.function.parameters??{},implementation:async(r,n)=>{let i={stack:[],error:void 0,hasError:!1};try{if(this.poison!==null)throw this.poison;if(n.signal.aborted)throw n.signal.reason;let s=this.callIdGiver.next(),{promise:a,resolve:l,reject:c}=re(),u=bC(i,new Ps,!1);return this.ongoingToolCalls.set(s,{callId:s,resolve:l,reject:c,reportStatus:h=>n.status(h),reportWarning:h=>n.warn(h)}),u.register(()=>{this.ongoingToolCalls.delete(s)}),this.channel.send({type:"callTool",callId:s,name:e.function.name,arguments:r}),n.signal.addEventListener("abort",()=>{this.status!=="disposed"&&(this.channel.send({type:"abortToolCall",callId:s}),c(n.signal.reason))},{once:!0}),await a}catch(s){i.error=s,i.hasError=!0}finally{vC(i)}}})}},Ml=class t{static async createUsingPredictionProcess(e,r,n,i,s,a){let l=await Promise.allSettled(r.map(u=>Zs.create(e,u,{type:"predictionProcess",pci:n,token:i},s,a))),c=l.filter(u=>u.status==="rejected");if(c.length>0){for(let u of l)if(u.status==="fulfilled")try{u.value[Symbol.dispose]()}catch(h){s.error("Failed to dispose a session after initialization failure.",h)}throw new AggregateError(c.map(u=>u.reason),"Failed to initialize some tool use sessions.")}return new t(l.map(u=>u.value),s)}constructor(e,r){this.sessions=e,this.logger=r,this.tools=[],this.tools=e.flatMap(n=>n.tools)}[Symbol.dispose](){for(let e of this.sessions)try{e[Symbol.dispose]()}catch(r){this.logger.error("Failed to dispose a session.",r)}}},DC=o.object({pluginConfig:te.optional(),workingDirectory:o.string().optional()}),wC=o.object({manifest:Zl}),jl=class{constructor(e,r,n,i,s){this.port=e,this.client=r,this.validator=n,this.rootLogger=s,this.logger=new Y("Plugins",i)}async registerDevelopmentPlugin(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","registerDevelopmentPlugin","opts",wC,e,r);let{promise:n,resolve:i}=re(),s=this.port.createChannel("registerDevelopmentPlugin",e,u=>{u.type==="ready"&&i({clientIdentifier:u.clientIdentifier,clientPasskey:u.clientPasskey})},{stack:r}),a=!1,l=async()=>{if(a)return;a=!0,s.send({type:"end"});let{promise:u,resolve:h}=re();s.onClose.subscribeOnce(h),await u};return{...await n,unregister:l}}async reindexPlugins(){let e=A(1);await this.port.callRpc("reindexPlugins",void 0,{stack:e})}getSelfRegistrationHost(){return new Rl(this.port,this.client,this.rootLogger,this.validator)}async internalStartToolUseSession(e,r,n){return await Zs.create(this.port,e,r,this.logger)}async pluginTools(e,r={}){let n=A(1);return[e,r]=this.validator.validateMethodParamsOrThrow("plugins","pluginTools",["pluginIdentifier","opts"],[ew,DC],[e,r],n),await this.internalStartToolUseSession(e,{type:"direct",config:r.pluginConfig??Pp,workingDirectoryPath:r.workingDirectory})}async startToolUseSessionUsingPredictionProcess(e,r,n,i){return await Ml.createUsingPredictionProcess(this.port,e,r,n,this.logger,i)}createGeneratorHandle(e){return new Vs(this.port,e,this.validator,null,this.logger)}createGeneratorHandleAssociatedWithPredictionProcess(e,r,n){return new Vs(this.port,e,this.validator,{pci:r,token:n},this.logger)}},SC=o.object({onStartFinalizing:o.function().optional(),onProgress:o.function().optional(),signal:o.instanceof(AbortSignal).optional()}),Bl=class{constructor(e,r,n,i,s,a){this.owner=e,this.name=r,this.onPlanUpdated=n,this.channel=i,this.validator=s,this.onDisposed=a,this.readyDeferredPromise=re(),this.isReadyBoolean=!1,this.currentDownload=null,this.errorReceivedBeforeDownloadStart=null,this.logger=new Y(`ArtifactDownloadPlanner(${e}/${r})`),this.readyDeferredPromise.promise.catch(()=>{}),this.planValue={nodes:[{type:"artifact",owner:e,name:r,state:"pending",dependencyNodes:[]}],downloadSizeBytes:0},this.channel.onMessage.subscribe(l=>{switch(l.type){case"planReady":{this.isReadyBoolean=!0,this.readyDeferredPromise.resolve(),this.planValue=l.plan;break}case"planUpdated":{this.planValue=l.plan,L(this.logger,"onPlanUpdated",this.onPlanUpdated,[l.plan]);break}case"success":{if(this.currentDownload===null)throw new Error("Unexpected: received success message without a download.");this.currentDownload.downloadFinished();break}case"downloadProgress":{if(this.currentDownload===null)throw new Error("Unexpected: received progress message without a download.");this.currentDownload.progressUpdate(l.update);break}case"startFinalizing":{if(this.currentDownload===null)throw new Error("Unexpected: received startFinalizing message without a download.");this.currentDownload.startFinalizing();break}}}),this.channel.onError.subscribeOnce(l=>{this.currentDownload===null?(this.errorReceivedBeforeDownloadStart=l,this.readyDeferredPromise.reject(l)):this.currentDownload.downloadFailed(l)})}[Symbol.dispose](){this.channel.send({type:"cancel"}),this.onDisposed()}isReady(){return this.isReadyBoolean}async untilReady(){return await this.readyDeferredPromise.promise}getPlan(){return this.planValue}async download(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("ArtifactDownloadPlanner","download","opts",SC,e,r);let{onProgress:n,onStartFinalizing:i,signal:s=new AbortController().signal}=e;if(this.currentDownload!==null)throw new Error("You can only call `download` once for each planner.");if(this.errorReceivedBeforeDownloadStart!==null){let u=this.errorReceivedBeforeDownloadStart;throw this.errorReceivedBeforeDownloadStart=null,u}let{promise:a,resolve:l,reject:c}=re();return this.currentDownload={downloadFinished:()=>{l()},startFinalizing:()=>{L(this.logger,"onStartFinalizing",i,[])},progressUpdate:u=>{L(this.logger,"onProgress",n,[u])},downloadFailed:u=>{c(u)}},this.channel.send({type:"commit"}),s.aborted?this.channel.send({type:"cancel"}):s.addEventListener("abort",()=>{this.channel.send({type:"cancel"})}),await a.catch(u=>{throw s.aborted?s.reason:u})}},CC=o.object({onProgress:o.function().optional(),onStartFinalizing:o.function().optional(),signal:o.instanceof(AbortSignal).optional()}),Ll=class{constructor(e,r,n,i){this.repositoryPort=e,this.validator=r,this.logger=n,this.data=i,this.quantization=i.quantization,this.name=i.name,this.sizeBytes=i.sizeBytes,this.fitEstimation=this.data.fitEstimation,this.indexedModelIdentifier=this.data.indexedModelIdentifier}isRecommended(){return this.data.recommended??!1}async download(e={}){let r=A(1);this.validator.validateMethodParamOrThrow("ModelSearchResultDownloadOption","download","opts",CC,e,r);let{promise:n,resolve:i,reject:s}=re(),a=this.repositoryPort.createChannel("downloadModel",{downloadIdentifier:this.data.downloadIdentifier},c=>{switch(c.type){case"downloadProgress":{L(this.logger,"onProgress",e.onProgress,[c.update]);break}case"startFinalizing":{L(this.logger,"onStartFinalizing",e.onStartFinalizing,[]);break}case"success":{i(c.defaultIdentifier);break}default:{let u=c;throw new Error(`Unexpected message type: ${u}`)}}},{stack:r});a.onError.subscribeOnce(c=>{e.signal?.aborted?s(e.signal.reason):s(c)}),a.onClose.subscribeOnce(()=>{e.signal?.aborted?s(e.signal.reason):s(new Error("Channel closed unexpectedly."))});let l=()=>{a.send({type:"cancel"})};return e.signal?.addEventListener("abort",l),n.finally(()=>{e.signal?.removeEventListener("abort",l)}),await n}},Nl=class{constructor(e,r,n,i){this.repositoryPort=e,this.validator=r,this.logger=n,this.data=i,this.name=i.name}isExactMatch(){return this.data.exact??!1}isStaffPick(){return this.data.staffPick??!1}async getDownloadOptions(){let{results:e}=await this.repositoryPort.callRpc("getModelDownloadOptions",{modelSearchResultIdentifier:this.data.identifier});return e.map(r=>new Ll(this.repositoryPort,this.validator,this.logger,r))}},EC=o.object({owner:o.string(),name:o.string(),revisionNumber:o.number(),path:o.string(),onProgress:o.function().optional(),onStartFinalizing:o.function().optional(),signal:o.instanceof(AbortSignal).optional()}),_C=o.object({path:o.string(),description:o.string().optional(),makePrivate:o.boolean().optional(),writeRevision:o.boolean().optional(),overrides:Pe.optional(),onMessage:o.function().optional()}),xC=o.object({onAuthenticationUrl:o.function()}),kC=o.object({keyId:o.string(),publicKey:o.string(),privateKey:o.string()});o.object({userName:o.string()});var FC=o.object({owner:o.string(),name:o.string(),onPlanUpdated:o.function().optional()}),$l=class{constructor(e,r,n){this.repositoryPort=e,this.validator=r,this.downloadPlanFinalizationRegistry=new FinalizationRegistry(({owner:i,name:s})=>{this.logger.warn(`
471
+ `,s.send({type:"complete",taskId:a.taskId})},p=>{p.name==="AbortError"?(c.info("Request successfully aborted."),s.send({type:"aborted",taskId:a.taskId})):(s.send({type:"error",taskId:a.taskId,error:Sr(p)}),c.warn("Generation failed.",p))}).finally(()=>{i.delete(a.taskId)});break}case"abort":{let c=i.get(a.taskId);c!==void 0&&(c.taskLogger.info("Received abort request."),c.cancel(),i.delete(a.taskId));break}default:{let c=l;throw new Error(`Unexpected message type: ${c}`)}}})}async initCompleted(){let e=A(1);await this.port.callRpc("pluginInitCompleted",void 0,{stack:e})}},vC=globalThis&&globalThis.__addDisposableResource||function(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],r&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(s){return Promise.reject(s)}}),t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e},DC=globalThis&&globalThis.__disposeResources||(function(t){return function(e){function r(a){e.error=e.hasError?new t(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function s(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(s);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(s,function(l){return r(l),s()})}else i|=1}catch(l){r(l)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return s()}})(typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n}),Zs=class t{static async create(e,r,n,i,s){let a=new t(e,r,n,i);return await a.init(s),a}constructor(e,r,n,i){this.pluginsPort=e,this.pluginIdentifier=r,this.pluginConfigSpecifier=n,this.logger=i,this.status="initializing",this.poison=null,this.ongoingToolCalls=new Map,this.callIdGiver=new Ts(0)}async init(e){let{promise:r,resolve:n,reject:i}=re(),s=this.pluginsPort.createChannel("startToolUseSession",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.pluginConfigSpecifier},a=>{let l=a.type;switch(l){case"sessionReady":{if(this.status!=="initializing"){this.logger.error("Received sessionReady message while not initializing");return}this.status="ready",n(),this.tools=a.toolDefinitions.map(c=>this.makeTool(c));break}case"toolCallComplete":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.resolve(a.result);break}case"toolCallError":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.reject(Os(a.error));break}case"toolCallStatus":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.reportStatus(a.statusText);break}case"toolCallWarn":{let c=this.ongoingToolCalls.get(a.callId);if(c===void 0)return;c.reportWarning(a.warnText);break}default:{let c=l;this.logger.warn(`Received unexpected message type in tool use session: ${c}`)}}},{stack:e});s.onError.subscribeOnce(a=>{this.status==="initializing"?i(a):(this.logger.error("Tool use session error.",a),this.poison=a);for(let l of this.ongoingToolCalls.values())l.reject(a);this.status="disposed"}),s.onClose.subscribeOnce(()=>{let a;this.status==="initializing"?(a=new Error("Tool use session channel closed unexpectedly during initialization."),i(a)):(a=new Error("Tool use session has already ended."),this.poison=a);for(let l of this.ongoingToolCalls.values())l.reject(a);this.status="disposed"}),this.channel=s,await r}[Symbol.dispose](){if(this.status!=="disposed"){this.channel.send({type:"discardSession"}),this.status="disposed";let e=new Error("Session disposed by client.");for(let r of this.ongoingToolCalls.values())r.reject(e);this.poison=e}}makeTool(e){return J1({name:e.function.name,description:e.function.description??"",pluginIdentifier:this.pluginIdentifier,parametersJsonSchema:e.function.parameters??{},implementation:async(r,n)=>{let i={stack:[],error:void 0,hasError:!1};try{if(this.poison!==null)throw this.poison;if(n.signal.aborted)throw n.signal.reason;let s=this.callIdGiver.next(),{promise:a,resolve:l,reject:c}=re(),u=vC(i,new Ps,!1);return this.ongoingToolCalls.set(s,{callId:s,resolve:l,reject:c,reportStatus:h=>n.status(h),reportWarning:h=>n.warn(h)}),u.register(()=>{this.ongoingToolCalls.delete(s)}),this.channel.send({type:"callTool",callId:s,name:e.function.name,arguments:r}),n.signal.addEventListener("abort",()=>{this.status!=="disposed"&&(this.channel.send({type:"abortToolCall",callId:s}),c(n.signal.reason))},{once:!0}),await a}catch(s){i.error=s,i.hasError=!0}finally{DC(i)}}})}},jl=class t{static async createUsingPredictionProcess(e,r,n,i,s,a){let l=await Promise.allSettled(r.map(u=>Zs.create(e,u,{type:"predictionProcess",pci:n,token:i},s,a))),c=l.filter(u=>u.status==="rejected");if(c.length>0){for(let u of l)if(u.status==="fulfilled")try{u.value[Symbol.dispose]()}catch(h){s.error("Failed to dispose a session after initialization failure.",h)}throw new AggregateError(c.map(u=>u.reason),"Failed to initialize some tool use sessions.")}return new t(l.map(u=>u.value),s)}constructor(e,r){this.sessions=e,this.logger=r,this.tools=[],this.tools=e.flatMap(n=>n.tools)}[Symbol.dispose](){for(let e of this.sessions)try{e[Symbol.dispose]()}catch(r){this.logger.error("Failed to dispose a session.",r)}}},wC=o.object({pluginConfig:te.optional(),workingDirectory:o.string().optional()}),SC=o.object({manifest:Kl}),Bl=class{constructor(e,r,n,i,s){this.port=e,this.client=r,this.validator=n,this.rootLogger=s,this.logger=new Y("Plugins",i)}async registerDevelopmentPlugin(e){let r=A(1);this.validator.validateMethodParamOrThrow("plugins","registerDevelopmentPlugin","opts",SC,e,r);let{promise:n,resolve:i}=re(),s=this.port.createChannel("registerDevelopmentPlugin",e,u=>{u.type==="ready"&&i({clientIdentifier:u.clientIdentifier,clientPasskey:u.clientPasskey})},{stack:r}),a=!1,l=async()=>{if(a)return;a=!0,s.send({type:"end"});let{promise:u,resolve:h}=re();s.onClose.subscribeOnce(h),await u};return{...await n,unregister:l}}async reindexPlugins(){let e=A(1);await this.port.callRpc("reindexPlugins",void 0,{stack:e})}getSelfRegistrationHost(){return new Ml(this.port,this.client,this.rootLogger,this.validator)}async internalStartToolUseSession(e,r,n){return await Zs.create(this.port,e,r,this.logger)}async pluginTools(e,r={}){let n=A(1);return[e,r]=this.validator.validateMethodParamsOrThrow("plugins","pluginTools",["pluginIdentifier","opts"],[tw,wC],[e,r],n),await this.internalStartToolUseSession(e,{type:"direct",config:r.pluginConfig??Tp,workingDirectoryPath:r.workingDirectory})}async startToolUseSessionUsingPredictionProcess(e,r,n,i){return await jl.createUsingPredictionProcess(this.port,e,r,n,this.logger,i)}createGeneratorHandle(e){return new Vs(this.port,e,this.validator,null,this.logger)}createGeneratorHandleAssociatedWithPredictionProcess(e,r,n){return new Vs(this.port,e,this.validator,{pci:r,token:n},this.logger)}},CC=o.object({onStartFinalizing:o.function().optional(),onProgress:o.function().optional(),signal:o.instanceof(AbortSignal).optional()}),Ll=class{constructor(e,r,n,i,s,a){this.owner=e,this.name=r,this.onPlanUpdated=n,this.channel=i,this.validator=s,this.onDisposed=a,this.readyDeferredPromise=re(),this.isReadyBoolean=!1,this.currentDownload=null,this.errorReceivedBeforeDownloadStart=null,this.logger=new Y(`ArtifactDownloadPlanner(${e}/${r})`),this.readyDeferredPromise.promise.catch(()=>{}),this.planValue={nodes:[{type:"artifact",owner:e,name:r,state:"pending",dependencyNodes:[]}],downloadSizeBytes:0},this.channel.onMessage.subscribe(l=>{switch(l.type){case"planReady":{this.isReadyBoolean=!0,this.readyDeferredPromise.resolve(),this.planValue=l.plan;break}case"planUpdated":{this.planValue=l.plan,L(this.logger,"onPlanUpdated",this.onPlanUpdated,[l.plan]);break}case"success":{if(this.currentDownload===null)throw new Error("Unexpected: received success message without a download.");this.currentDownload.downloadFinished();break}case"downloadProgress":{if(this.currentDownload===null)throw new Error("Unexpected: received progress message without a download.");this.currentDownload.progressUpdate(l.update);break}case"startFinalizing":{if(this.currentDownload===null)throw new Error("Unexpected: received startFinalizing message without a download.");this.currentDownload.startFinalizing();break}}}),this.channel.onError.subscribeOnce(l=>{this.currentDownload===null?(this.errorReceivedBeforeDownloadStart=l,this.readyDeferredPromise.reject(l)):this.currentDownload.downloadFailed(l)})}[Symbol.dispose](){this.channel.send({type:"cancel"}),this.onDisposed()}isReady(){return this.isReadyBoolean}async untilReady(){return await this.readyDeferredPromise.promise}getPlan(){return this.planValue}async download(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("ArtifactDownloadPlanner","download","opts",CC,e,r);let{onProgress:n,onStartFinalizing:i,signal:s=new AbortController().signal}=e;if(this.currentDownload!==null)throw new Error("You can only call `download` once for each planner.");if(this.errorReceivedBeforeDownloadStart!==null){let u=this.errorReceivedBeforeDownloadStart;throw this.errorReceivedBeforeDownloadStart=null,u}let{promise:a,resolve:l,reject:c}=re();return this.currentDownload={downloadFinished:()=>{l()},startFinalizing:()=>{L(this.logger,"onStartFinalizing",i,[])},progressUpdate:u=>{L(this.logger,"onProgress",n,[u])},downloadFailed:u=>{c(u)}},this.channel.send({type:"commit"}),s.aborted?this.channel.send({type:"cancel"}):s.addEventListener("abort",()=>{this.channel.send({type:"cancel"})}),await a.catch(u=>{throw s.aborted?s.reason:u})}},EC=o.object({onProgress:o.function().optional(),onStartFinalizing:o.function().optional(),signal:o.instanceof(AbortSignal).optional()}),Nl=class{constructor(e,r,n,i){this.repositoryPort=e,this.validator=r,this.logger=n,this.data=i,this.quantization=i.quantization,this.name=i.name,this.sizeBytes=i.sizeBytes,this.fitEstimation=this.data.fitEstimation,this.indexedModelIdentifier=this.data.indexedModelIdentifier}isRecommended(){return this.data.recommended??!1}async download(e={}){let r=A(1);this.validator.validateMethodParamOrThrow("ModelSearchResultDownloadOption","download","opts",EC,e,r);let{promise:n,resolve:i,reject:s}=re(),a=this.repositoryPort.createChannel("downloadModel",{downloadIdentifier:this.data.downloadIdentifier},c=>{switch(c.type){case"downloadProgress":{L(this.logger,"onProgress",e.onProgress,[c.update]);break}case"startFinalizing":{L(this.logger,"onStartFinalizing",e.onStartFinalizing,[]);break}case"success":{i(c.defaultIdentifier);break}default:{let u=c;throw new Error(`Unexpected message type: ${u}`)}}},{stack:r});a.onError.subscribeOnce(c=>{e.signal?.aborted?s(e.signal.reason):s(c)}),a.onClose.subscribeOnce(()=>{e.signal?.aborted?s(e.signal.reason):s(new Error("Channel closed unexpectedly."))});let l=()=>{a.send({type:"cancel"})};return e.signal?.addEventListener("abort",l),n.finally(()=>{e.signal?.removeEventListener("abort",l)}),await n}},$l=class{constructor(e,r,n,i){this.repositoryPort=e,this.validator=r,this.logger=n,this.data=i,this.name=i.name}isExactMatch(){return this.data.exact??!1}isStaffPick(){return this.data.staffPick??!1}async getDownloadOptions(){let{results:e}=await this.repositoryPort.callRpc("getModelDownloadOptions",{modelSearchResultIdentifier:this.data.identifier});return e.map(r=>new Nl(this.repositoryPort,this.validator,this.logger,r))}},_C=o.object({owner:o.string(),name:o.string(),revisionNumber:o.number(),path:o.string(),onProgress:o.function().optional(),onStartFinalizing:o.function().optional(),signal:o.instanceof(AbortSignal).optional()}),xC=o.object({path:o.string(),description:o.string().optional(),makePrivate:o.boolean().optional(),writeRevision:o.boolean().optional(),overrides:Pe.optional(),onMessage:o.function().optional()}),kC=o.object({onAuthenticationUrl:o.function()}),FC=o.object({keyId:o.string(),publicKey:o.string(),privateKey:o.string()});o.object({userName:o.string()});var PC=o.object({owner:o.string(),name:o.string(),onPlanUpdated:o.function().optional()}),Ul=class{constructor(e,r,n){this.repositoryPort=e,this.validator=r,this.downloadPlanFinalizationRegistry=new FinalizationRegistry(({owner:i,name:s})=>{this.logger.warn(`
472
472
  A download plan for artifact ${i}/${s} has been garbage collected without being
473
473
  disposed. Please make sure you are creating the download plan with the "using" keyword.
474
474
 
475
475
  This is a memory leak and needs to be fixed.
476
- `)}),this.logger=new Y("Repository",n)}async searchModels(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("repository","search","opts",_p,e,r);let{results:n}=await this.repositoryPort.callRpc("searchModels",{opts:e},{stack:r});return n.map(i=>new Nl(this.repositoryPort,this.validator,this.logger,i))}async installPluginDependencies(e){let r=A(1);this.validator.validateMethodParamOrThrow("repository","installPluginDependencies","pluginFolder",o.string(),e,r),await this.repositoryPort.callRpc("installPluginDependencies",{pluginFolder:e},{stack:r})}async downloadArtifact(e){let r=A(1);this.validator.validateMethodParamOrThrow("client.repository","downloadArtifact","opts",EC,e,r);let{owner:n,name:i,revisionNumber:s,path:a,onProgress:l,onStartFinalizing:c,signal:u}=e,{promise:h,resolve:f,reject:d}=re(),p=this.repositoryPort.createChannel("downloadArtifact",{artifactOwner:n,artifactName:i,revisionNumber:s,path:a},g=>{switch(g.type){case"downloadProgress":{L(this.logger,"onProgress",l,[g.update]);break}case"startFinalizing":{L(this.logger,"onStartFinalizing",c,[]);break}case"success":{f();break}default:{let y=g;throw new Error(`Unexpected message type: ${y}`)}}},{stack:r});p.onError.subscribeOnce(d),p.onClose.subscribeOnce(()=>{u?.aborted?d(u.reason):d(new Error("Channel closed unexpectedly."))});let m=()=>{p.send({type:"cancel"})};return u?.addEventListener("abort",m),h.finally(()=>{u?.removeEventListener("abort",m)}),await h}async pushArtifact(e){let r=A(1),{path:n,description:i,makePrivate:s,writeRevision:a,overrides:l,onMessage:c}=this.validator.validateMethodParamOrThrow("repository","pushArtifact","opts",_C,e,r),u=this.repositoryPort.createChannel("pushArtifact",{path:n,description:i,makePrivate:s,writeRevision:a,overrides:l},p=>{let m=p.type;if(m==="message")L(this.logger,"onMessage",c,[p.message]);else{let g=m;throw new Error(`Unexpected message type: ${g}`)}},{stack:r}),{promise:h,resolve:f,reject:d}=re();u.onError.subscribeOnce(d),u.onClose.subscribeOnce(f),await h}async getLocalArtifactFileList(e){let r=A(1);this.validator.validateMethodParamOrThrow("repository","getLocalArtifactFileList","path",o.string(),e,r);let{fileList:n}=await this.repositoryPort.callRpc("getLocalArtifactFiles",{path:e},{stack:r});return n}async ensureAuthenticated(e){let r=A(1);this.validator.validateMethodParamOrThrow("repository","ensureAuthenticated","opts",xC,e,r);let{promise:n,resolve:i,reject:s}=re();this.repositoryPort.createChannel("ensureAuthenticated",void 0,l=>{let c=l.type;switch(c){case"authenticationUrl":{L(this.logger,"onAuthenticationUrl",e.onAuthenticationUrl,[l.url]);break}case"authenticated":{i();break}default:{let u=c;throw new Error(`Unexpected message type: ${u}`)}}}).onError.subscribeOnce(s),await n}async loginWithPreAuthenticatedKeys(e){let r=A(1);this.validator.validateMethodParamOrThrow("repository","loginWithPreAuthenticatedKeys","opts",kC,e,r);let{keyId:n,publicKey:i,privateKey:s}=e,{userName:a}=await this.repositoryPort.callRpc("loginWithPreAuthenticatedKeys",{keyId:n,publicKey:i,privateKey:s},{stack:r});return{userName:a}}createArtifactDownloadPlanner(e){let{owner:r,name:n,onPlanUpdated:i}=this.validator.validateMethodParamOrThrow("repository","createArtifactDownloadPlanner","opts",FC,e),s=A(1),a=this.repositoryPort.createChannel("createArtifactDownloadPlan",{owner:r,name:n},void 0,{stack:s}),l=new Bl(r,n,i,a,this.validator,()=>{this.downloadPlanFinalizationRegistry.unregister(l)});return this.downloadPlanFinalizationRegistry.register(l,{owner:r,name:n},l),l}},PC=o.object({port:o.number().int().min(1).max(65535).describe("Port to run the API server on. Must be between 1 and 65535."),cors:o.boolean().describe("Enable CORS on the API server. Allows any website to access the server.")}),Ul=class{constructor(e,r,n){this.systemPort=e,this.validator=r,this.logger=new Y("System",n)}async listDownloadedModels(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("client.system","listDownloadedModels","domain",o.union([o.literal("llm"),o.literal("embedding"),o.undefined()]),e,r);let n=await this.systemPort.callRpc("listDownloadedModels",void 0,{stack:A(1)});return e===void 0?n:n.filter(i=>i.type===e)}async whenDisconnected(){let e=A(1),r=this.systemPort.createChannel("alive",void 0,void 0,{stack:e}),{promise:n,resolve:i}=re();r.onError.subscribeOnce(i),r.onClose.subscribeOnce(i),await n}async notify(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("client.system","notify","notification",Bh,e,r),await this.systemPort.callRpc("notify",e,{stack:r})}async getLMStudioVersion(){let e=A(1);return await this.systemPort.callRpc("version",void 0,{stack:e})}async unstable_setExperimentFlag(e,r){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow("client.system","setExperimentFlag",["flag","value"],[o.string(),o.boolean()],[e,r],n),await this.systemPort.callRpc("setExperimentFlag",{code:e,value:r},{stack:n})}async unstable_getExperimentFlags(){let e=A(1);return await this.systemPort.callRpc("getExperimentFlags",void 0,{stack:e})}async startHttpServer(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("client.system","startHttpServer","args",PC,e),await this.systemPort.callRpc("startHttpServer",{port:e.port,cors:e.cors},{stack:r})}async stopHttpServer(){let e=A(1);return await this.systemPort.callRpc("stopHttpServer",void 0,{stack:e})}},TC=o.object({logger:o.any().optional(),baseUrl:o.string().optional(),verboseErrorMessages:o.boolean().optional(),clientIdentifier:o.string().optional(),clientPasskey:o.string().optional(),disableConnection:o.boolean().optional(),llmPort:o.any().optional(),embeddingPort:o.any().optional(),systemPort:o.any().optional(),diagnosticsPort:o.any().optional(),retrievalPort:o.any().optional(),filesPort:o.any().optional(),repositoryPort:o.any().optional(),pluginsPort:o.any().optional()}).strict(),Ks=class{validateBaseUrlOrThrow(e){let r;try{r=new URL(e)}catch{this.logger.throw(j`
476
+ `)}),this.logger=new Y("Repository",n)}async searchModels(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("repository","search","opts",xp,e,r);let{results:n}=await this.repositoryPort.callRpc("searchModels",{opts:e},{stack:r});return n.map(i=>new $l(this.repositoryPort,this.validator,this.logger,i))}async installPluginDependencies(e){let r=A(1);this.validator.validateMethodParamOrThrow("repository","installPluginDependencies","pluginFolder",o.string(),e,r),await this.repositoryPort.callRpc("installPluginDependencies",{pluginFolder:e},{stack:r})}async downloadArtifact(e){let r=A(1);this.validator.validateMethodParamOrThrow("client.repository","downloadArtifact","opts",_C,e,r);let{owner:n,name:i,revisionNumber:s,path:a,onProgress:l,onStartFinalizing:c,signal:u}=e,{promise:h,resolve:f,reject:d}=re(),p=this.repositoryPort.createChannel("downloadArtifact",{artifactOwner:n,artifactName:i,revisionNumber:s,path:a},g=>{switch(g.type){case"downloadProgress":{L(this.logger,"onProgress",l,[g.update]);break}case"startFinalizing":{L(this.logger,"onStartFinalizing",c,[]);break}case"success":{f();break}default:{let y=g;throw new Error(`Unexpected message type: ${y}`)}}},{stack:r});p.onError.subscribeOnce(d),p.onClose.subscribeOnce(()=>{u?.aborted?d(u.reason):d(new Error("Channel closed unexpectedly."))});let m=()=>{p.send({type:"cancel"})};return u?.addEventListener("abort",m),h.finally(()=>{u?.removeEventListener("abort",m)}),await h}async pushArtifact(e){let r=A(1),{path:n,description:i,makePrivate:s,writeRevision:a,overrides:l,onMessage:c}=this.validator.validateMethodParamOrThrow("repository","pushArtifact","opts",xC,e,r),u=this.repositoryPort.createChannel("pushArtifact",{path:n,description:i,makePrivate:s,writeRevision:a,overrides:l},p=>{let m=p.type;if(m==="message")L(this.logger,"onMessage",c,[p.message]);else{let g=m;throw new Error(`Unexpected message type: ${g}`)}},{stack:r}),{promise:h,resolve:f,reject:d}=re();u.onError.subscribeOnce(d),u.onClose.subscribeOnce(f),await h}async getLocalArtifactFileList(e){let r=A(1);this.validator.validateMethodParamOrThrow("repository","getLocalArtifactFileList","path",o.string(),e,r);let{fileList:n}=await this.repositoryPort.callRpc("getLocalArtifactFiles",{path:e},{stack:r});return n}async ensureAuthenticated(e){let r=A(1);this.validator.validateMethodParamOrThrow("repository","ensureAuthenticated","opts",kC,e,r);let{promise:n,resolve:i,reject:s}=re();this.repositoryPort.createChannel("ensureAuthenticated",void 0,l=>{let c=l.type;switch(c){case"authenticationUrl":{L(this.logger,"onAuthenticationUrl",e.onAuthenticationUrl,[l.url]);break}case"authenticated":{i();break}default:{let u=c;throw new Error(`Unexpected message type: ${u}`)}}}).onError.subscribeOnce(s),await n}async loginWithPreAuthenticatedKeys(e){let r=A(1);this.validator.validateMethodParamOrThrow("repository","loginWithPreAuthenticatedKeys","opts",FC,e,r);let{keyId:n,publicKey:i,privateKey:s}=e,{userName:a}=await this.repositoryPort.callRpc("loginWithPreAuthenticatedKeys",{keyId:n,publicKey:i,privateKey:s},{stack:r});return{userName:a}}createArtifactDownloadPlanner(e){let{owner:r,name:n,onPlanUpdated:i}=this.validator.validateMethodParamOrThrow("repository","createArtifactDownloadPlanner","opts",PC,e),s=A(1),a=this.repositoryPort.createChannel("createArtifactDownloadPlan",{owner:r,name:n},void 0,{stack:s}),l=new Ll(r,n,i,a,this.validator,()=>{this.downloadPlanFinalizationRegistry.unregister(l)});return this.downloadPlanFinalizationRegistry.register(l,{owner:r,name:n},l),l}},TC=o.object({port:o.number().int().min(1).max(65535).describe("Port to run the API server on. Must be between 1 and 65535."),cors:o.boolean().describe("Enable CORS on the API server. Allows any website to access the server.")}),ql=class{constructor(e,r,n){this.systemPort=e,this.validator=r,this.logger=new Y("System",n)}async listDownloadedModels(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("client.system","listDownloadedModels","domain",o.union([o.literal("llm"),o.literal("embedding"),o.undefined()]),e,r);let n=await this.systemPort.callRpc("listDownloadedModels",void 0,{stack:A(1)});return e===void 0?n:n.filter(i=>i.type===e)}async whenDisconnected(){let e=A(1),r=this.systemPort.createChannel("alive",void 0,void 0,{stack:e}),{promise:n,resolve:i}=re();r.onError.subscribeOnce(i),r.onClose.subscribeOnce(i),await n}async notify(e){let r=A(1);e=this.validator.validateMethodParamOrThrow("client.system","notify","notification",Lh,e,r),await this.systemPort.callRpc("notify",e,{stack:r})}async getLMStudioVersion(){let e=A(1);return await this.systemPort.callRpc("version",void 0,{stack:e})}async unstable_setExperimentFlag(e,r){let n=A(1);[e,r]=this.validator.validateMethodParamsOrThrow("client.system","setExperimentFlag",["flag","value"],[o.string(),o.boolean()],[e,r],n),await this.systemPort.callRpc("setExperimentFlag",{code:e,value:r},{stack:n})}async unstable_getExperimentFlags(){let e=A(1);return await this.systemPort.callRpc("getExperimentFlags",void 0,{stack:e})}async startHttpServer(e){let r=A(1);return e=this.validator.validateMethodParamOrThrow("client.system","startHttpServer","args",TC,e),await this.systemPort.callRpc("startHttpServer",{port:e.port,cors:e.cors},{stack:r})}async stopHttpServer(){let e=A(1);return await this.systemPort.callRpc("stopHttpServer",void 0,{stack:e})}},AC=o.object({logger:o.any().optional(),baseUrl:o.string().optional(),verboseErrorMessages:o.boolean().optional(),clientIdentifier:o.string().optional(),clientPasskey:o.string().optional(),disableConnection:o.boolean().optional(),llmPort:o.any().optional(),embeddingPort:o.any().optional(),systemPort:o.any().optional(),diagnosticsPort:o.any().optional(),retrievalPort:o.any().optional(),filesPort:o.any().optional(),repositoryPort:o.any().optional(),pluginsPort:o.any().optional()}).strict(),Ks=class{validateBaseUrlOrThrow(e){let r;try{r=new URL(e)}catch{this.logger.throw(j`
477
477
  Failed to construct LMStudioClient. The baseUrl passed in is invalid. Received: ${e}
478
478
  `)}["ws:","wss:"].includes(r.protocol)||this.logger.throw(j`
479
479
  Failed to construct LMStudioClient. The baseUrl passed in must have protocol "ws" or "wss".
@@ -490,7 +490,7 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
490
490
  Failed to construct LMStudioClient. The baseUrl passed in must not end with a "/". If you
491
491
  are reverse-proxying, you should remove the trailing slash from the baseUrl. Received:
492
492
  ${e}
493
- `)}async isLocalhostWithGivenPortLMStudioServer(e){let r=await fetch(`http://127.0.0.1:${e}/lmstudio-greeting`);if(r.status!==200)throw new Error("Status is not 200.");if((await r.json())?.lmstudio!==!0)throw new Error("Not an LM Studio server.");return e}async guessBaseUrl(e){if(Yp()!==null)return Promise.resolve("Using hosted env");if(Yn.default.browser)try{return this.isLocalhostWithGivenPortLMStudioServer(1234),"ws://127.0.0.1:1234"}catch{j`
493
+ `)}async isLocalhostWithGivenPortLMStudioServer(e){let r=await fetch(`http://127.0.0.1:${e}/lmstudio-greeting`);if(r.status!==200)throw new Error("Status is not 200.");if((await r.json())?.lmstudio!==!0)throw new Error("Not an LM Studio server.");return e}async guessBaseUrl(e){if(Jp()!==null)return Promise.resolve("Using hosted env");if(Yn.default.browser)try{return this.isLocalhostWithGivenPortLMStudioServer(1234),"ws://127.0.0.1:1234"}catch{j`
494
494
  ${I.default.redBright("Failed to connect to LM Studio.")}
495
495
 
496
496
  Is LM Studio running? If not, please start it by running:
@@ -507,7 +507,7 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
507
507
  ${I.default.white("(i) For more information, refer to the LM Studio documentation:")}
508
508
 
509
509
  ${I.default.gray("https://lmstudio.ai/docs/local-server")}
510
- `}return Promise.any(Qv.map(this.isLocalhostWithGivenPortLMStudioServer)).then(r=>`ws://127.0.0.1:${r}`,()=>{throw Ee(j`
510
+ `}return Promise.any(Xv.map(this.isLocalhostWithGivenPortLMStudioServer)).then(r=>`ws://127.0.0.1:${r}`,()=>{throw Ee(j`
511
511
  ${I.default.redBright("Failed to connect to LM Studio.")}
512
512
 
513
513
  Please make sure LM Studio is running on your machine.
@@ -522,7 +522,7 @@ ${r("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
522
522
  ${I.default.white("(i) For more information, refer to the LM Studio documentation:")}
523
523
 
524
524
  ${I.default.gray("https://lmstudio.ai/docs/local-server")}
525
- `,e)})}createPort(e,r,n){return KS(n,this.resolvingBaseUrl,e,this.clientIdentifier,this.clientPasskey,new Y(r,this.logger),{errorDeserializer:nC,verboseErrorMessage:this.verboseErrorMessages})}constructor(e={}){let{logger:r,baseUrl:n,verboseErrorMessages:i,clientIdentifier:s,clientPasskey:a,disableConnection:l,llmPort:c,embeddingPort:u,systemPort:h,diagnosticsPort:f,retrievalPort:d,filesPort:p,repositoryPort:m,pluginsPort:g}=new it().validateConstructorParamOrThrow("LMStudioClient","opts",TC,e);if(globalThis.__LMS_PLUGIN_CONTEXT&&e.baseUrl===void 0)throw new Error(j`
525
+ `,e)})}createPort(e,r,n){return HS(n,this.resolvingBaseUrl,e,this.clientIdentifier,this.clientPasskey,new Y(r,this.logger),{errorDeserializer:iC,verboseErrorMessage:this.verboseErrorMessages})}constructor(e={}){let{logger:r,baseUrl:n,verboseErrorMessages:i,clientIdentifier:s,clientPasskey:a,disableConnection:l,llmPort:c,embeddingPort:u,systemPort:h,diagnosticsPort:f,retrievalPort:d,filesPort:p,repositoryPort:m,pluginsPort:g}=new ot().validateConstructorParamOrThrow("LMStudioClient","opts",AC,e);if(globalThis.__LMS_PLUGIN_CONTEXT&&e.baseUrl===void 0)throw new Error(j`
526
526
  You cannot create a local LMStudioClient in a plugin context. To use LM Studio APIs, use
527
527
  the "client" property attached to the Controllers.
528
528
 
@@ -543,7 +543,7 @@ export async function generate(ctl: GeneratorController) {
543
543
  the LMStudioClient constructor:
544
544
 
545
545
  ${"const client = new LMStudioClient({ baseUrl: 'ws://<host_name>:<port>' });"}
546
- `);this.logger=new Y("LMStudioClient",r),this.clientIdentifier=s??(0,st.generateRandomBase64)(18),this.clientPasskey=a??(0,st.generateRandomBase64)(18);let y=A(1);l?this.resolvingBaseUrl=new Promise(()=>{}):n===void 0?this.resolvingBaseUrl=this.guessBaseUrl(i?y:void 0):(this.validateBaseUrlOrThrow(n),this.resolvingBaseUrl=n),this.verboseErrorMessages=i??!0,this.llmPort=c??this.createPort("llm","LLM",qS()),this.embeddingPort=u??this.createPort("embedding","Embedding",$S()),this.systemPort=h??this.createPort("system","System",WS()),this.diagnosticsPort=f??this.createPort("diagnostics","Diagnostics",NS()),this.filesPort=p??this.createPort("files","Files",US()),this.repositoryPort=m??this.createPort("repository","Repository",VS()),this.pluginsPort=g??this.createPort("plugins","Plugins",zS());let b=new it;this.llm=new El(this,this.llmPort,new Y("LLM",this.logger),b),this.embedding=new ml(this,this.embeddingPort,new Y("Embedding",this.logger),b),this.system=new Ul(this.systemPort,b,this.logger),this.diagnostics=new hl(this.diagnosticsPort,b,this.logger),this.files=new gl(this.filesPort,b,this.logger),this.repository=new $l(this.repositoryPort,b,this.logger),this.plugins=new jl(this.pluginsPort,this,b,this.logger,r)}async[Symbol.asyncDispose](){await Promise.all([this.llmPort[Symbol.asyncDispose](),this.embeddingPort[Symbol.asyncDispose](),this.systemPort[Symbol.asyncDispose](),this.diagnosticsPort[Symbol.asyncDispose](),this.filesPort[Symbol.asyncDispose](),this.repositoryPort[Symbol.asyncDispose](),this.pluginsPort[Symbol.asyncDispose]()])}};async function im(t,e,r,n,i){return(await new Tn({host:e}).generate({model:r,system:n,prompt:t,stream:!1,images:i})).response||"No response"}async function sm(t,e,r,n,i){try{let s=new Ks({baseUrl:e}),a=await s.llm.model(r),l={role:"user",content:t};if(i){let h=await s.files.prepareImageBase64("screenshot.png",i);l.images=[h]}let c=n?[{role:"system",content:n},l]:[l];return(await a.respond(c)).content||"No response"}catch(s){let a=s instanceof Error?s.message:"Unknown error";throw new Error(`LM Studio error: ${a}`)}}var xt=require("child_process"),qg=require("os"),zg=Me($g()),Vg=`You are a computer control assistant. You will receive a screenshot and must determine the next single action to take to complete the given instruction.
546
+ `);this.logger=new Y("LMStudioClient",r),this.clientIdentifier=s??(0,at.generateRandomBase64)(18),this.clientPasskey=a??(0,at.generateRandomBase64)(18);let y=A(1);l?this.resolvingBaseUrl=new Promise(()=>{}):n===void 0?this.resolvingBaseUrl=this.guessBaseUrl(i?y:void 0):(this.validateBaseUrlOrThrow(n),this.resolvingBaseUrl=n),this.verboseErrorMessages=i??!0,this.llmPort=c??this.createPort("llm","LLM",zS()),this.embeddingPort=u??this.createPort("embedding","Embedding",US()),this.systemPort=h??this.createPort("system","System",GS()),this.diagnosticsPort=f??this.createPort("diagnostics","Diagnostics",$S()),this.filesPort=p??this.createPort("files","Files",qS()),this.repositoryPort=m??this.createPort("repository","Repository",WS()),this.pluginsPort=g??this.createPort("plugins","Plugins",VS());let b=new ot;this.llm=new _l(this,this.llmPort,new Y("LLM",this.logger),b),this.embedding=new gl(this,this.embeddingPort,new Y("Embedding",this.logger),b),this.system=new ql(this.systemPort,b,this.logger),this.diagnostics=new pl(this.diagnosticsPort,b,this.logger),this.files=new yl(this.filesPort,b,this.logger),this.repository=new Ul(this.repositoryPort,b,this.logger),this.plugins=new Bl(this.pluginsPort,this,b,this.logger,r)}async[Symbol.asyncDispose](){await Promise.all([this.llmPort[Symbol.asyncDispose](),this.embeddingPort[Symbol.asyncDispose](),this.systemPort[Symbol.asyncDispose](),this.diagnosticsPort[Symbol.asyncDispose](),this.filesPort[Symbol.asyncDispose](),this.repositoryPort[Symbol.asyncDispose](),this.pluginsPort[Symbol.asyncDispose]()])}};async function sm(t,e,r,n,i){return(await new Tn({host:e}).generate({model:r,system:n,prompt:t,stream:!1,images:i})).response||"No response"}async function om(t,e,r,n,i){try{let s=new Ks({baseUrl:e}),a=await s.llm.model(r),l={role:"user",content:t};if(i){let h=await s.files.prepareImageBase64("screenshot.png",i);l.images=[h]}let c=n?[{role:"system",content:n},l]:[l];return(await a.respond(c)).content||"No response"}catch(s){let a=s instanceof Error?s.message:"Unknown error";throw new Error(`LM Studio error: ${a}`)}}var He=require("child_process"),zg=require("os"),Vg=je(Ug());function Wg(t,e){return`You are a computer control assistant. You will receive a screenshot (${t}x${e} pixels) and must determine the next single action to take to complete the given instruction.
547
547
 
548
548
  Respond with ONLY a valid JSON object (no markdown, no extra text) in one of these formats:
549
549
  {"action": "mouse_move", "x": number, "y": number, "reasoning": "explanation"}
@@ -552,10 +552,10 @@ Respond with ONLY a valid JSON object (no markdown, no extra text) in one of the
552
552
  {"action": "keyboard_input", "text": "text to type", "reasoning": "explanation"}
553
553
  {"action": "DONE", "reasoning": "explanation of what was accomplished"}
554
554
 
555
- x and y are screen coordinates in pixels from the top-left corner. Return DONE only when the instruction is fully completed.`;function Wg(t){try{let e=t.trim().replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,""),r=JSON.parse(e);if(r&&typeof r.action=="string")return r}catch{let e=t.match(/\{[\s\S]*?\}/);if(e)try{let r=JSON.parse(e[0]);if(r&&typeof r.action=="string")return r}catch{}}return null}async function Gg(){let t=await(0,zg.default)({format:"png"}),e=t.readUInt32BE(16),r=t.readUInt32BE(20);return{base64:t.toString("base64"),width:e,height:r}}function Zg(t){switch(t.action){case"mouse_move":return`Move mouse to (${t.x}, ${t.y})`;case"mouse_left_click":return`Left click at (${t.x}, ${t.y})`;case"mouse_right_click":return`Right click at (${t.x}, ${t.y})`;case"keyboard_input":return`Type: "${t.text}"`;case"DONE":return"DONE"}}function Kg(t){let e=Buffer.from(t,"utf16le").toString("base64");(0,xt.execSync)(`powershell -NonInteractive -NoProfile -EncodedCommand ${e}`,{stdio:"ignore"})}function Ug(t,e,r,n){let i=['$td = @"',"using System; using System.Runtime.InteropServices;","[StructLayout(LayoutKind.Sequential)]","public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }","[StructLayout(LayoutKind.Explicit, Size=40)]","public struct MINPUT { [FieldOffset(0)] public uint type; [FieldOffset(8)] public MOUSEINPUT mi; }","public class W32M {",' [DllImport("user32.dll")] public static extern uint SendInput(uint n, MINPUT[] i, int cb);'," public static void Do(int nx, int ny, uint df, uint uf) {"," int cnt = (df != 0) ? 3 : 1;"," MINPUT[] a = new MINPUT[cnt];"," a[0].mi = new MOUSEINPUT { dx=nx, dy=ny, dwFlags=0x8001 };"," if (cnt > 1) {"," a[1].mi = new MOUSEINPUT { dx=nx, dy=ny, dwFlags=df };"," a[2].mi = new MOUSEINPUT { dx=nx, dy=ny, dwFlags=uf };"," }"," SendInput((uint)cnt, a, System.Runtime.InteropServices.Marshal.SizeOf(typeof(MINPUT)));"," }","}",'"@',"Add-Type -TypeDefinition $td -ErrorAction SilentlyContinue",`[W32M]::Do(${t}, ${e}, ${r}, ${n})`];Kg(i.join(`
556
- `))}async function Hg(t,e,r){if(t.action==="DONE")return;let n=(0,qg.platform)();if(t.action==="mouse_move")if(n==="win32"){let i=Math.round(t.x*65535/Math.max((e??1)-1,1)),s=Math.round(t.y*65535/Math.max((r??1)-1,1));Ug(i,s,0,0)}else n==="darwin"?(0,xt.execSync)(`osascript -e 'tell application "System Events" to set cursor position to {${t.x}, ${t.y}}'`,{stdio:"ignore"}):(0,xt.execFileSync)("xdotool",["mousemove",String(t.x),String(t.y)]);else if(t.action==="mouse_left_click"||t.action==="mouse_right_click"){let i=t.action==="mouse_left_click";if(n==="win32"){let s=Math.round(t.x*65535/Math.max((e??1)-1,1)),a=Math.round(t.y*65535/Math.max((r??1)-1,1));Ug(s,a,i?32770:32776,i?32772:32784)}else if(n==="darwin")(0,xt.execSync)(`osascript -e 'tell application "System Events" to ${i?"leftClick":"rightClick"} at {${t.x}, ${t.y}}'`,{stdio:"ignore"});else{let s=i?"1":"3";(0,xt.execFileSync)("xdotool",["mousemove",String(t.x),String(t.y),"click",s])}}else if(t.action==="keyboard_input")if(n==="win32"){let s=['$typeDef = @"',"using System; using System.Runtime.InteropServices; using System.Threading;","[StructLayout(LayoutKind.Sequential)]","public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }","[StructLayout(LayoutKind.Explicit, Size=40)]","public struct INPUT { [FieldOffset(0)] public uint type; [FieldOffset(8)] public KEYBDINPUT ki; }","public class KeySender {",' [DllImport("user32.dll")] public static extern uint SendInput(uint n, INPUT[] i, int cb);'," public static void Type(string text, int delayMs) {"," foreach (char c in text) {"," INPUT[] inp = new INPUT[2];"," inp[0] = new INPUT { type=1 }; inp[0].ki = new KEYBDINPUT { wScan=(ushort)c, dwFlags=4 };"," inp[1] = new INPUT { type=1 }; inp[1].ki = new KEYBDINPUT { wScan=(ushort)c, dwFlags=6 };"," SendInput(2, inp, System.Runtime.InteropServices.Marshal.SizeOf(typeof(INPUT)));"," Thread.Sleep(delayMs);"," }"," }","}",'"@',"Add-Type -TypeDefinition $typeDef -ErrorAction SilentlyContinue",`$t = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${Buffer.from(t.text,"utf8").toString("base64")}'))`,"[KeySender]::Type($t, 50)"];Kg(s.join(`
555
+ x and y are pixel coordinates within the screenshot image: x ranges from 0 to ${t-1} (left to right), y ranges from 0 to ${e-1} (top to bottom). Be as precise as possible. Return DONE only when the instruction is fully completed.`}function Gg(t){try{let e=t.trim().replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,""),r=JSON.parse(e);if(r&&typeof r.action=="string")return r}catch{let e=t.match(/\{[\s\S]*?\}/);if(e)try{let r=JSON.parse(e[0]);if(r&&typeof r.action=="string")return r}catch{}}return null}async function Zg(){let t=await(0,Vg.default)({format:"png"}),e=t.readUInt32BE(16),r=t.readUInt32BE(20);return{base64:t.toString("base64"),width:e,height:r}}function Kg(t){switch(t.action){case"mouse_move":return`Move mouse to (${t.x}, ${t.y})`;case"mouse_left_click":return`Left click at (${t.x}, ${t.y})`;case"mouse_right_click":return`Right click at (${t.x}, ${t.y})`;case"keyboard_input":return`Type: "${t.text}"`;case"DONE":return"DONE"}}function mo(t){try{if(t==="darwin"){let r=(0,He.execSync)(`osascript -e 'tell application "Finder" to get bounds of window of desktop'`,{stdio:["ignore","pipe","ignore"]}).toString().trim().split(", ").map(Number);if(r.length===4&&r.every(n=>!isNaN(n)))return{width:r[2],height:r[3]}}else if(t==="linux"){let r=(0,He.execSync)("xdpyinfo | grep dimensions",{stdio:["ignore","pipe","ignore"]}).toString().match(/(\d+)x(\d+) pixels/);if(r)return{width:parseInt(r[1]),height:parseInt(r[2])}}}catch{}return null}function Hg(t){let e=Buffer.from(t,"utf16le").toString("base64");(0,He.execSync)(`powershell -NonInteractive -NoProfile -EncodedCommand ${e}`,{stdio:"ignore"})}function qg(t,e,r,n){let i=['$td = @"',"using System; using System.Runtime.InteropServices;","[StructLayout(LayoutKind.Sequential)]","public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }","[StructLayout(LayoutKind.Explicit, Size=40)]","public struct MINPUT { [FieldOffset(0)] public uint type; [FieldOffset(8)] public MOUSEINPUT mi; }","public class W32M {",' [DllImport("user32.dll")] public static extern uint SendInput(uint n, MINPUT[] i, int cb);'," public static void Do(int nx, int ny, uint df, uint uf) {"," int cnt = (df != 0) ? 3 : 1;"," MINPUT[] a = new MINPUT[cnt];"," a[0].mi = new MOUSEINPUT { dx=nx, dy=ny, dwFlags=0x8001 };"," if (cnt > 1) {"," a[1].mi = new MOUSEINPUT { dx=nx, dy=ny, dwFlags=df };"," a[2].mi = new MOUSEINPUT { dx=nx, dy=ny, dwFlags=uf };"," }"," SendInput((uint)cnt, a, System.Runtime.InteropServices.Marshal.SizeOf(typeof(MINPUT)));"," }","}",'"@',"Add-Type -TypeDefinition $td -ErrorAction SilentlyContinue",`[W32M]::Do(${t}, ${e}, ${r}, ${n})`];Hg(i.join(`
556
+ `))}async function Yg(t,e,r){if(t.action==="DONE")return;let n=(0,zg.platform)();if(t.action==="mouse_move")if(n==="win32"){let i=Math.min(65535,Math.round(t.x*65535/Math.max((e??1)-1,1))),s=Math.min(65535,Math.round(t.y*65535/Math.max((r??1)-1,1)));qg(i,s,0,0)}else if(n==="darwin"){let i=mo(n),s=i&&e?e/i.width:1,a=i&&r?r/i.height:1,l=Math.round(t.x/s),c=Math.round(t.y/a);(0,He.execSync)(`osascript -e 'tell application "System Events" to set cursor position to {${l}, ${c}}'`,{stdio:"ignore"})}else{let i=mo(n),s=i&&e?e/i.width:1,a=i&&r?r/i.height:1,l=Math.round(t.x/s),c=Math.round(t.y/a);(0,He.execFileSync)("xdotool",["mousemove",String(l),String(c)])}else if(t.action==="mouse_left_click"||t.action==="mouse_right_click"){let i=t.action==="mouse_left_click";if(n==="win32"){let s=Math.min(65535,Math.round(t.x*65535/Math.max((e??1)-1,1))),a=Math.min(65535,Math.round(t.y*65535/Math.max((r??1)-1,1)));qg(s,a,i?32770:32776,i?32772:32784)}else if(n==="darwin"){let s=mo(n),a=s&&e?e/s.width:1,l=s&&r?r/s.height:1,c=Math.round(t.x/a),u=Math.round(t.y/l);(0,He.execSync)(`osascript -e 'tell application "System Events" to ${i?"leftClick":"rightClick"} at {${c}, ${u}}'`,{stdio:"ignore"})}else{let s=mo(n),a=s&&e?e/s.width:1,l=s&&r?r/s.height:1,c=Math.round(t.x/a),u=Math.round(t.y/l),h=i?"1":"3";(0,He.execFileSync)("xdotool",["mousemove",String(c),String(u),"click",h])}}else if(t.action==="keyboard_input")if(n==="win32"){let s=['$typeDef = @"',"using System; using System.Runtime.InteropServices; using System.Threading;","[StructLayout(LayoutKind.Sequential)]","public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }","[StructLayout(LayoutKind.Explicit, Size=40)]","public struct INPUT { [FieldOffset(0)] public uint type; [FieldOffset(8)] public KEYBDINPUT ki; }","public class KeySender {",' [DllImport("user32.dll")] public static extern uint SendInput(uint n, INPUT[] i, int cb);'," public static void Type(string text, int delayMs) {"," foreach (char c in text) {"," INPUT[] inp = new INPUT[2];"," inp[0] = new INPUT { type=1 }; inp[0].ki = new KEYBDINPUT { wScan=(ushort)c, dwFlags=4 };"," inp[1] = new INPUT { type=1 }; inp[1].ki = new KEYBDINPUT { wScan=(ushort)c, dwFlags=6 };"," SendInput(2, inp, System.Runtime.InteropServices.Marshal.SizeOf(typeof(INPUT)));"," Thread.Sleep(delayMs);"," }"," }","}",'"@',"Add-Type -TypeDefinition $typeDef -ErrorAction SilentlyContinue",`$t = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${Buffer.from(t.text,"utf8").toString("base64")}'))`,"[KeySender]::Type($t, 50)"];Hg(s.join(`
557
557
  `))}else if(n==="darwin"){let s=['tell application "System Events"',` set t to "${t.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`," repeat with i from 1 to (count t)"," keystroke (character i of t)"," delay 0.05"," end repeat","end tell"].join(`
558
- `);(0,xt.execFileSync)("osascript",[],{input:s})}else(0,xt.execFileSync)("xdotool",["type","--delay","50","--clearmodifiers","--",t.text]);await new Promise(i=>setTimeout(i,5e3))}var zc=Me(require("readline")),le=Me(require("fs")),Yt=Me(require("path"));function ct(t,...e){for(let r of e){let n=t.indexOf(r);if(n!==-1&&t[n+1]&&!t[n+1].startsWith("-"))return t[n+1]}}function Jg(t,...e){return e.some(r=>t.includes(r))}function g_(t){let e=ct(t,"-p","--platform")||process.env.ASKII_PLATFORM||"ollama",r=ct(t,"--ollama-url")||process.env.ASKII_OLLAMA_URL||"http://localhost:11434",n=ct(t,"--lmstudio-url")||process.env.ASKII_LMSTUDIO_URL||"ws://localhost:1234",i=ct(t,"--ollama-model")||process.env.ASKII_OLLAMA_MODEL||"gemma3:270m",s=ct(t,"--lmstudio-model")||process.env.ASKII_LMSTUDIO_MODEL||"qwen/qwen3-coder-30b";return{platform:e,url:e==="lmstudio"?n:r,model:e==="lmstudio"?s:i,mode:ct(t,"--mode")||process.env.ASKII_MODE||"funny",maxRounds:parseInt(ct(t,"--max-rounds")||process.env.ASKII_MAX_ROUNDS||"5"),yes:Jg(t,"-y","--yes")}}async function Pi(t,e,r,n){return t.platform==="lmstudio"?sm(e,t.url,t.model,r,n):im(e,t.url,t.model,r,n?[n]:void 0)}async function qc(){return process.stdin.isTTY?null:new Promise(t=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",r=>e+=r),process.stdin.on("end",()=>t(e.trim()||null))})}async function Ti(t,e,r){return r?(console.error(`${e} (auto-confirmed)`),!0):new Promise(n=>{t.question(`${e} (y/N) `,i=>n(i.toLowerCase()==="y"))})}function Yg(){console.log(`ASKII CLI ( \u2022_\u2022)>\u2310\u25A0-\u25A0 (\u2310\u25A0_\u25A0)
558
+ `);(0,He.execFileSync)("osascript",[],{input:s})}else(0,He.execFileSync)("xdotool",["type","--delay","50","--clearmodifiers","--",t.text]);await new Promise(i=>setTimeout(i,5e3))}var Vc=je(require("readline")),le=je(require("fs")),Yt=je(require("path"));function Ae(t,...e){for(let r of e){let n=t.indexOf(r);if(n!==-1&&t[n+1]&&!t[n+1].startsWith("-"))return t[n+1]}}function Qg(t,...e){return e.some(r=>t.includes(r))}function y_(t){let e=Ae(t,"-p","--platform")||process.env.ASKII_PLATFORM||"ollama",r=Ae(t,"--ollama-url")||process.env.ASKII_OLLAMA_URL||"http://localhost:11434",n=Ae(t,"--lmstudio-url")||process.env.ASKII_LMSTUDIO_URL||"ws://localhost:1234",i=Ae(t,"--ollama-model")||process.env.ASKII_OLLAMA_MODEL||"gemma3:270m",s=Ae(t,"--lmstudio-model")||process.env.ASKII_LMSTUDIO_MODEL||"qwen/qwen3-coder-30b";return{platform:e,url:e==="lmstudio"?n:r,model:e==="lmstudio"?s:i,mode:Ae(t,"--mode")||process.env.ASKII_MODE||"funny",maxRounds:parseInt(Ae(t,"--max-rounds")||process.env.ASKII_MAX_ROUNDS||"5"),yes:Qg(t,"-y","--yes")}}async function Pi(t,e,r,n){return t.platform==="lmstudio"?om(e,t.url,t.model,r,n):sm(e,t.url,t.model,r,n?[n]:void 0)}async function zc(){return process.stdin.isTTY?null:new Promise(t=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",r=>e+=r),process.stdin.on("end",()=>t(e.trim()||null))})}async function Ti(t,e,r){return r?(console.error(`${e} (auto-confirmed)`),!0):new Promise(n=>{t.question(`${e} (y/N) `,i=>n(i.toLowerCase()==="y"))})}function Jg(){console.log(`ASKII CLI ( \u2022_\u2022)>\u2310\u25A0-\u25A0 (\u2310\u25A0_\u25A0)
559
559
  AI code assistant for your terminal
560
560
 
561
561
  Usage: askii <command> [options]
@@ -577,6 +577,8 @@ Options:
577
577
  --max-rounds <n> Max agent rounds for "do" / "control" (default: 5)
578
578
  --dir <path> Working directory for "do" (default: cwd)
579
579
  -c, --code <code> Code input (alternative to stdin)
580
+ --lang <language> Language of the code (e.g. typescript, python)
581
+ --file <filename> Filename of the code (e.g. src/utils.ts)
580
582
  -y, --yes Auto-confirm all actions
581
583
  -h, --help Show help
582
584
 
@@ -588,6 +590,7 @@ Environment variables:
588
590
 
589
591
  Examples:
590
592
  cat myfile.ts | askii ask "what does this do?"
593
+ cat myfile.ts | askii ask --lang typescript --file src/utils.ts "what does this do?"
591
594
  cat myfile.ts | askii edit "add error handling"
592
595
  askii explain "const x = arr.reduce((a, b) => a + b, 0)"
593
596
  askii do "create a Jest test file for src/utils.ts"
@@ -595,21 +598,25 @@ Examples:
595
598
  askii -p lmstudio --lmstudio-model "my-model" do "refactor index.ts"
596
599
  askii control --ollama-model llava "open Notepad and type hello world"
597
600
  askii control --yes --ollama-model llava "click the search bar and search for cats"
598
- `)}async function y_(){let t=process.argv.slice(2),e=t[0]||"help",r=t,n=t.filter(s=>!s.startsWith("-"));(Jg(r,"-h","--help")||e==="help")&&(Yg(),process.exit(0));let i=g_(r);if(e==="ask"){let s=await qc(),a=ct(r,"-c","--code")||s,l=n.slice(1).join(" ");l||(console.error("Error: provide a question as an argument"),process.exit(1));let c=a?`Code:
599
- \`\`\`
601
+ `)}async function b_(){let t=process.argv.slice(2),e=t[0]||"help",r=t,n=t.filter(s=>!s.startsWith("-"));(Qg(r,"-h","--help")||e==="help")&&(Jg(),process.exit(0));let i=y_(r);if(e==="ask"){let s=await zc(),a=Ae(r,"-c","--code")||s,l=n.slice(1).join(" "),c=Ae(r,"--lang"),u=Ae(r,"--file");l||(console.error("Error: provide a question as an argument"),process.exit(1));let h;if(a){let f=[u?`File: ${u}`:null,c?`Language: ${c}`:null].filter(Boolean).join(`
602
+ `),d=`\`\`\`${c??""}
600
603
  ${a}
601
- \`\`\`
604
+ \`\`\``;h=`${f?f+`
605
+ `:""}Code:
606
+ ${d}
602
607
 
603
- Question: ${l}`:`Question: ${l}`;console.error(`ASKII is thinking... ${Fn()}`);try{let u=await Pi(i,c);console.log(`
608
+ Question: ${l}`}else h=`Question: ${l}`;console.error(`ASKII is thinking... ${Fn()}`);try{let f=await Pi(i,h);console.log(`
604
609
  ASKII Says: ${Ii()}
605
- `),console.log(u)}catch(u){console.error(`Error: ${u instanceof Error?u.message:"Unknown error"}`),process.exit(1)}}else if(e==="edit"){let s=await qc(),a=ct(r,"-c","--code")||s,l=n.slice(1).join(" ");a||(console.error("Error: provide code via stdin or -c/--code"),process.exit(1)),l||(console.error("Error: provide an instruction as an argument"),process.exit(1));let c=`Update this code:
606
- \`\`\`
610
+ `),console.log(f)}catch(f){console.error(`Error: ${f instanceof Error?f.message:"Unknown error"}`),process.exit(1)}}else if(e==="edit"){let s=await zc(),a=Ae(r,"-c","--code")||s,l=n.slice(1).join(" "),c=Ae(r,"--lang"),u=Ae(r,"--file");a||(console.error("Error: provide code via stdin or -c/--code"),process.exit(1)),l||(console.error("Error: provide an instruction as an argument"),process.exit(1));let h=[u?`File: ${u}`:null,c?`Language: ${c}`:null].filter(Boolean).join(`
611
+ `),f=`${h?h+`
612
+ `:""}Update this code:
613
+ \`\`\`${c??""}
607
614
  ${a}
608
615
  \`\`\`
609
616
 
610
617
  Request: ${l}
611
618
 
612
- Return only the updated code without explanation.`;console.error("ASKII is editing... (\u2022_\u2022)>\u2310\u25A0-\u25A0");try{let u=await Pi(i,c);console.log(Kc(u))}catch(u){console.error(`Error: ${u instanceof Error?u.message:"Unknown error"}`),process.exit(1)}}else if(e==="explain"){let s=await qc(),a=n.slice(1).join(" ")||s;a||(console.error("Error: provide a line of code as an argument or via stdin"),process.exit(1));let l=i.mode==="helpful",c=l?"You are ASKII, a helpful coding assistant. Provide clear, concise explanations.":"You are ASKII, a witty coding assistant. Provide humorous comments.",u=l?`Explain this code in one sentence: ${a}`:`Make a funny comment about this code in one sentence: ${a}`;console.error(`ASKII is thinking... ${Fn()}`);try{let h=await Pi(i,u,c);console.log(h)}catch(h){console.error(`Error: ${h instanceof Error?h.message:"Unknown error"}`),process.exit(1)}}else if(e==="do"){let s=n.slice(1).join(" ");s||(console.error("Error: provide a task as an argument"),process.exit(1));let a=ct(r,"--dir")||process.cwd();console.error(`ASKII is working... ${Fn()}`);let l=zc.createInterface({input:process.stdin,output:process.stderr});try{let c=Gc(a);console.error(`
619
+ Return only the updated code without explanation.`;console.error("ASKII is editing... (\u2022_\u2022)>\u2310\u25A0-\u25A0");try{let d=await Pi(i,f);console.log(Hc(d))}catch(d){console.error(`Error: ${d instanceof Error?d.message:"Unknown error"}`),process.exit(1)}}else if(e==="explain"){let s=await zc(),a=n.slice(1).join(" ")||s;a||(console.error("Error: provide a line of code as an argument or via stdin"),process.exit(1));let l=i.mode==="helpful",c=l?"You are ASKII, a helpful coding assistant. Provide clear, concise explanations.":"You are ASKII, a witty coding assistant. Provide humorous comments.",u=l?`Explain this code in one sentence: ${a}`:`Make a funny comment about this code in one sentence: ${a}`;console.error(`ASKII is thinking... ${Fn()}`);try{let h=await Pi(i,u,c);console.log(h)}catch(h){console.error(`Error: ${h instanceof Error?h.message:"Unknown error"}`),process.exit(1)}}else if(e==="do"){let s=n.slice(1).join(" ");s||(console.error("Error: provide a task as an argument"),process.exit(1));let a=Ae(r,"--dir")||process.cwd();console.error(`ASKII is working... ${Fn()}`);let l=Vc.createInterface({input:process.stdin,output:process.stderr});try{let c=Zc(a);console.error(`
613
620
  Workspace: ${a}
614
621
  \`\`\`
615
622
  ${c}\`\`\`
@@ -632,17 +639,17 @@ Always respond with ONLY a valid JSON array containing the actions. You can requ
632
639
 
633
640
  User request: ${d}`:`${f}
634
641
 
635
- ${d}`,m=await Pi(i,p),g=Zc(m);if(g.length===0)break;let y=g.filter(v=>v.type==="view"||v.type==="list"),b=g.filter(v=>v.type!=="view"&&v.type!=="list"),D={};for(let v of y){let S=Yt.join(a,v.path);try{if(v.type==="list"){console.error(` \u2192 Listing: ${v.path}`);let C=le.readdirSync(S).map(x=>{let _=le.statSync(Yt.join(S,x));return`${x} [${_.isDirectory()?"folder":"file"}]`});D[v.path]=C.join(`
642
+ ${d}`,m=await Pi(i,p),g=Kc(m);if(g.length===0)break;let y=g.filter(v=>v.type==="view"||v.type==="list"),b=g.filter(v=>v.type!=="view"&&v.type!=="list"),D={};for(let v of y){let S=Yt.join(a,v.path);try{if(v.type==="list"){console.error(` \u2192 Listing: ${v.path}`);let C=le.readdirSync(S).map(x=>{let _=le.statSync(Yt.join(S,x));return`${x} [${_.isDirectory()?"folder":"file"}]`});D[v.path]=C.join(`
636
643
  `)}else console.error(` \u2192 Viewing: ${v.path}`),D[v.path]=le.readFileSync(S,"utf-8")}catch{D[v.path]="Error: Cannot read path"}}for(let v of b){let S=Yt.join(a,v.path);if(v.type==="create"){if(await Ti(l,`Create file: ${v.path}?`,i.yes)){let x=Yt.dirname(S);le.existsSync(x)||le.mkdirSync(x,{recursive:!0});let _=v.content?Oi(v.content):"";le.writeFileSync(S,_),u++,console.error(` \u2713 Created: ${v.path}`)}}else if(v.type==="modify"){if(await Ti(l,`Modify file: ${v.path}?`,i.yes))try{let x=le.readFileSync(S,"utf-8"),_=v.oldContent?Oi(v.oldContent):"",B=v.newContent?Oi(v.newContent):"";le.writeFileSync(S,x.replace(_,B)),u++,console.error(` \u2713 Modified: ${v.path}`)}catch{console.error(` \u2717 Cannot modify: ${v.path}`)}}else if(v.type==="delete"){if(await Ti(l,`Delete file: ${v.path}? This cannot be undone.`,i.yes))try{le.unlinkSync(S),u++,console.error(` \u2713 Deleted: ${v.path}`)}catch{console.error(` \u2717 Cannot delete: ${v.path}`)}}else if(v.type==="rename")if(!v.newPath)console.error(` \u2717 Rename missing newPath: ${v.path}`);else{let C=Yt.join(a,v.newPath);if(await Ti(l,`Rename: ${v.path} \u2192 ${v.newPath}?`,i.yes))try{let _=Yt.dirname(C);le.existsSync(_)||le.mkdirSync(_,{recursive:!0}),le.renameSync(S,C),u++,console.error(` \u2713 Renamed: ${v.path} \u2192 ${v.newPath}`)}catch{console.error(` \u2717 Cannot rename: ${v.path}`)}}}Object.keys(D).length>0?d=`File contents retrieved:
637
644
  ${JSON.stringify(D,null,2)}
638
645
 
639
646
  What would you like to do next? Respond with only a JSON array of actions or an empty array [] if done.`:d="Actions completed. What would you like to do next? Respond with only a JSON array of actions or an empty array [] if done.",h++}l.close(),console.error(`
640
- Completed ${u} actions! ${Ii()}`)}catch(c){l.close(),console.error(`Error: ${c instanceof Error?c.message:"Unknown error"}`),process.exit(1)}}else if(e==="control"){let s=n.slice(1).join(" ");s||(console.error("Error: provide an instruction as an argument"),process.exit(1));let a=zc.createInterface({input:process.stdin,output:process.stderr});try{console.error(`ASKII Control starting... ${Fn()}`),console.error(`Instruction: ${s}`),console.error(`(Make sure your model supports vision/images)
641
- `);let l=0;for(;l<i.maxRounds;){console.error(`Round ${l+1}/${i.maxRounds} \u2014 taking screenshot...`);let{base64:c,width:u,height:h}=await Gg(),f=l===0?`Instruction to complete: ${s}
647
+ Completed ${u} actions! ${Ii()}`)}catch(c){l.close(),console.error(`Error: ${c instanceof Error?c.message:"Unknown error"}`),process.exit(1)}}else if(e==="control"){let s=n.slice(1).join(" ");s||(console.error("Error: provide an instruction as an argument"),process.exit(1));let a=Vc.createInterface({input:process.stdin,output:process.stderr});try{console.error(`ASKII Control starting... ${Fn()}`),console.error(`Instruction: ${s}`),console.error(`(Make sure your model supports vision/images)
648
+ `);let l=0;for(;l<i.maxRounds;){console.error(`Round ${l+1}/${i.maxRounds} \u2014 taking screenshot...`);let{base64:c,width:u,height:h}=await Zg(),f=l===0?`Instruction to complete: ${s}
642
649
 
643
650
  Analyze the screenshot and determine the next action.`:`Continuing instruction: ${s}
644
651
 
645
- Analyze the updated screenshot and determine the next action, or return DONE if the instruction is complete.`;console.error("Asking AI...");let d=await Pi(i,f,Vg,c),p=Wg(d);if(!p){console.error("Error: could not parse action from AI response."),console.error(`Raw response: ${d}`);break}if(p.action==="DONE"){console.error(`
646
- Done! ${Ii()}`),console.error(`Reasoning: ${p.reasoning}`);break}let m=Zg(p);if(console.error(`
647
- Action: ${m}`),console.error(`Reasoning: ${p.reasoning}`),!await Ti(a,"Execute this action?",i.yes)){console.error("Stopped.");break}await Hg(p,u,h),console.error(`Executed.
648
- `),l++}l>=i.maxRounds&&console.error(`Max rounds (${i.maxRounds}) reached.`),a.close()}catch(l){a.close(),console.error(`Error: ${l instanceof Error?l.message:"Unknown error"}`),process.exit(1)}}else console.error(`Unknown command: ${e}`),Yg(),process.exit(1)}y_();
652
+ Analyze the updated screenshot and determine the next action, or return DONE if the instruction is complete.`;console.error("Asking AI...");let d=await Pi(i,f,Wg(u,h),c),p=Gg(d);if(!p){console.error("Error: could not parse action from AI response."),console.error(`Raw response: ${d}`);break}if(p.action==="DONE"){console.error(`
653
+ Done! ${Ii()}`),console.error(`Reasoning: ${p.reasoning}`);break}let m=Kg(p);if(console.error(`
654
+ Action: ${m}`),console.error(`Reasoning: ${p.reasoning}`),!await Ti(a,"Execute this action?",i.yes)){console.error("Stopped.");break}await Yg(p,u,h),console.error(`Executed.
655
+ `),l++}l>=i.maxRounds&&console.error(`Max rounds (${i.maxRounds}) reached.`),a.close()}catch(l){a.close(),console.error(`Error: ${l instanceof Error?l.message:"Unknown error"}`),process.exit(1)}}else console.error(`Unknown command: ${e}`),Jg(),process.exit(1)}b_();