askii-cli 0.2.1 → 0.2.3
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/README.md +18 -1
- package/dist/index.js +302 -173
- package/dist/index.js.map +3 -3
- package/package.json +1 -2
package/dist/index.js
CHANGED
|
@@ -1,116 +1,235 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`)===0?U.substr(1,U.length):U}).forEach(function(U){var Z=U.split(":"),q=Z.shift().trim();if(q){var _e=Z.join(":").trim();try{C.append(q,_e)}catch(ye){console.warn("Response "+ye.message)}}}),C}b.call(v.prototype);function k(w,C){if(!(this instanceof k))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(C||(C={}),this.type="default",this.status=C.status===void 0?200:C.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=C.statusText===void 0?"":""+C.statusText,this.headers=new u(C.headers),this.url=C.url||"",this._initBody(w)}b.call(k.prototype),k.prototype.clone=function(){return new k(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},k.error=function(){var w=new k(null,{status:200,statusText:""});return w.ok=!1,w.status=0,w.type="error",w};var x=[301,302,303,307,308];k.redirect=function(w,C){if(x.indexOf(C)===-1)throw new RangeError("Invalid status code");return new k(null,{status:C,headers:{location:w}})},r.DOMException=e.DOMException;try{new r.DOMException}catch{r.DOMException=function(C,P){this.message=C,this.name=P;var U=Error(C);this.stack=U.stack},r.DOMException.prototype=Object.create(Error.prototype),r.DOMException.prototype.constructor=r.DOMException}function z(w,C){return new Promise(function(P,U){var Z=new v(w,C);if(Z.signal&&Z.signal.aborted)return U(new r.DOMException("Aborted","AbortError"));var q=new XMLHttpRequest;function _e(){q.abort()}q.onload=function(){var Q={statusText:q.statusText,headers:_(q.getAllResponseHeaders()||"")};Z.url.indexOf("file://")===0&&(q.status<200||q.status>599)?Q.status=200:Q.status=q.status,Q.url="responseURL"in q?q.responseURL:Q.headers.get("X-Request-URL");var Fe="response"in q?q.response:q.responseText;setTimeout(function(){P(new k(Fe,Q))},0)},q.onerror=function(){setTimeout(function(){U(new TypeError("Network request failed"))},0)},q.ontimeout=function(){setTimeout(function(){U(new TypeError("Network request timed out"))},0)},q.onabort=function(){setTimeout(function(){U(new r.DOMException("Aborted","AbortError"))},0)};function ye(Q){try{return Q===""&&e.location.href?e.location.href:Q}catch{return Q}}if(q.open(Z.method,ye(Z.url),!0),Z.credentials==="include"?q.withCredentials=!0:Z.credentials==="omit"&&(q.withCredentials=!1),"responseType"in q&&(t.blob?q.responseType="blob":t.arrayBuffer&&(q.responseType="arraybuffer")),C&&typeof C.headers=="object"&&!(C.headers instanceof u||e.Headers&&C.headers instanceof e.Headers)){var be=[];Object.getOwnPropertyNames(C.headers).forEach(function(Q){be.push(a(Q)),q.setRequestHeader(Q,l(C.headers[Q]))}),Z.headers.forEach(function(Q,Fe){be.indexOf(Fe)===-1&&q.setRequestHeader(Fe,Q)})}else Z.headers.forEach(function(Q,Fe){q.setRequestHeader(Fe,Q)});Z.signal&&(Z.signal.addEventListener("abort",_e),q.onreadystatechange=function(){q.readyState===4&&Z.signal.removeEventListener("abort",_e)}),q.send(typeof Z._bodyInit>"u"?null:Z._bodyInit)})}z.polyfill=!0,e.fetch||(e.fetch=z,e.Headers=u,e.Request=v,e.Response=k),r.Headers=u,r.Request=v,r.Response=k,r.fetch=z,Object.defineProperty(r,"__esModule",{value:!0})}))});var Ol=J((r1,Il)=>{"use strict";Il.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 Rs=J((n1,jl)=>{var on=Ol(),Ml={};for(let r of Object.keys(on))Ml[on[r]]=r;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"]}};jl.exports=M;for(let r of Object.keys(M)){if(!("channels"in M[r]))throw new Error("missing channels property: "+r);if(!("labels"in M[r]))throw new Error("missing channel labels property: "+r);if(M[r].labels.length!==M[r].channels)throw new Error("channel and label counts mismatch: "+r);let{channels:e,labels:t}=M[r];delete M[r].channels,delete M[r].labels,Object.defineProperty(M[r],"channels",{value:e}),Object.defineProperty(M[r],"labels",{value:t})}M.rgb.hsl=function(r){let e=r[0]/255,t=r[1]/255,n=r[2]/255,i=Math.min(e,t,n),o=Math.max(e,t,n),a=o-i,l,c;o===i?l=0:e===o?l=(t-n)/a:t===o?l=2+(n-e)/a:n===o&&(l=4+(e-t)/a),l=Math.min(l*60,360),l<0&&(l+=360);let u=(i+o)/2;return o===i?c=0:u<=.5?c=a/(o+i):c=a/(2-o-i),[l,c*100,u*100]};M.rgb.hsv=function(r){let e,t,n,i,o,a=r[0]/255,l=r[1]/255,c=r[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,o=0):(o=h/u,e=f(a),t=f(l),n=f(c),a===u?i=n-t:l===u?i=1/3+e-n:c===u&&(i=2/3+t-e),i<0?i+=1:i>1&&(i-=1)),[i*360,o*100,u*100]};M.rgb.hwb=function(r){let e=r[0],t=r[1],n=r[2],i=M.rgb.hsl(r)[0],o=1/255*Math.min(e,Math.min(t,n));return n=1-1/255*Math.max(e,Math.max(t,n)),[i,o*100,n*100]};M.rgb.cmyk=function(r){let e=r[0]/255,t=r[1]/255,n=r[2]/255,i=Math.min(1-e,1-t,1-n),o=(1-e-i)/(1-i)||0,a=(1-t-i)/(1-i)||0,l=(1-n-i)/(1-i)||0;return[o*100,a*100,l*100,i*100]};function dm(r,e){return(r[0]-e[0])**2+(r[1]-e[1])**2+(r[2]-e[2])**2}M.rgb.keyword=function(r){let e=Ml[r];if(e)return e;let t=1/0,n;for(let i of Object.keys(on)){let o=on[i],a=dm(r,o);a<t&&(t=a,n=i)}return n};M.keyword.rgb=function(r){return on[r]};M.rgb.xyz=function(r){let e=r[0]/255,t=r[1]/255,n=r[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92;let i=e*.4124+t*.3576+n*.1805,o=e*.2126+t*.7152+n*.0722,a=e*.0193+t*.1192+n*.9505;return[i*100,o*100,a*100]};M.rgb.lab=function(r){let e=M.rgb.xyz(r),t=e[0],n=e[1],i=e[2];t/=95.047,n/=100,i/=108.883,t=t>.008856?t**(1/3):7.787*t+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 o=116*n-16,a=500*(t-n),l=200*(n-i);return[o,a,l]};M.hsl.rgb=function(r){let e=r[0]/360,t=r[1]/100,n=r[2]/100,i,o,a;if(t===0)return a=n*255,[a,a,a];n<.5?i=n*(1+t):i=n+t-n*t;let l=2*n-i,c=[0,0,0];for(let u=0;u<3;u++)o=e+1/3*-(u-1),o<0&&o++,o>1&&o--,6*o<1?a=l+(i-l)*6*o:2*o<1?a=i:3*o<2?a=l+(i-l)*(2/3-o)*6:a=l,c[u]=a*255;return c};M.hsl.hsv=function(r){let e=r[0],t=r[1]/100,n=r[2]/100,i=t,o=Math.max(n,.01);n*=2,t*=n<=1?n:2-n,i*=o<=1?o:2-o;let a=(n+t)/2,l=n===0?2*i/(o+i):2*t/(n+t);return[e,l*100,a*100]};M.hsv.rgb=function(r){let e=r[0]/60,t=r[1]/100,n=r[2]/100,i=Math.floor(e)%6,o=e-Math.floor(e),a=255*n*(1-t),l=255*n*(1-t*o),c=255*n*(1-t*(1-o));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(r){let e=r[0],t=r[1]/100,n=r[2]/100,i=Math.max(n,.01),o,a;a=(2-t)*n;let l=(2-t)*i;return o=t*i,o/=l<=1?l:2-l,o=o||0,a/=2,[e,o*100,a*100]};M.hwb.rgb=function(r){let e=r[0]/360,t=r[1]/100,n=r[2]/100,i=t+n,o;i>1&&(t/=i,n/=i);let a=Math.floor(6*e),l=1-n;o=6*e-a,(a&1)!==0&&(o=1-o);let c=t+o*(l-t),u,h,f;switch(a){default:case 6:case 0:u=l,h=c,f=t;break;case 1:u=c,h=l,f=t;break;case 2:u=t,h=l,f=c;break;case 3:u=t,h=c,f=l;break;case 4:u=c,h=t,f=l;break;case 5:u=l,h=t,f=c;break}return[u*255,h*255,f*255]};M.cmyk.rgb=function(r){let e=r[0]/100,t=r[1]/100,n=r[2]/100,i=r[3]/100,o=1-Math.min(1,e*(1-i)+i),a=1-Math.min(1,t*(1-i)+i),l=1-Math.min(1,n*(1-i)+i);return[o*255,a*255,l*255]};M.xyz.rgb=function(r){let e=r[0]/100,t=r[1]/100,n=r[2]/100,i,o,a;return i=e*3.2406+t*-1.5372+n*-.4986,o=e*-.9689+t*1.8758+n*.0415,a=e*.0557+t*-.204+n*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,i=Math.min(Math.max(0,i),1),o=Math.min(Math.max(0,o),1),a=Math.min(Math.max(0,a),1),[i*255,o*255,a*255]};M.xyz.lab=function(r){let e=r[0],t=r[1],n=r[2];e/=95.047,t/=100,n/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let i=116*t-16,o=500*(e-t),a=200*(t-n);return[i,o,a]};M.lab.xyz=function(r){let e=r[0],t=r[1],n=r[2],i,o,a;o=(e+16)/116,i=t/500+o,a=o-n/200;let l=o**3,c=i**3,u=a**3;return o=l>.008856?l:(o-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,o*=100,a*=108.883,[i,o,a]};M.lab.lch=function(r){let e=r[0],t=r[1],n=r[2],i;i=Math.atan2(n,t)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(t*t+n*n);return[e,a,i]};M.lch.lab=function(r){let e=r[0],t=r[1],i=r[2]/360*2*Math.PI,o=t*Math.cos(i),a=t*Math.sin(i);return[e,o,a]};M.rgb.ansi16=function(r,e=null){let[t,n,i]=r,o=e===null?M.rgb.hsv(r)[2]:e;if(o=Math.round(o/50),o===0)return 30;let a=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(t/255));return o===2&&(a+=60),a};M.hsv.ansi16=function(r){return M.rgb.ansi16(M.hsv.rgb(r),r[2])};M.rgb.ansi256=function(r){let e=r[0],t=r[1],n=r[2];return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)};M.ansi16.rgb=function(r){let e=r%10;if(e===0||e===7)return r>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let t=(~~(r>50)+1)*.5,n=(e&1)*t*255,i=(e>>1&1)*t*255,o=(e>>2&1)*t*255;return[n,i,o]};M.ansi256.rgb=function(r){if(r>=232){let o=(r-232)*10+8;return[o,o,o]}r-=16;let e,t=Math.floor(r/36)/5*255,n=Math.floor((e=r%36)/6)/5*255,i=e%6/5*255;return[t,n,i]};M.rgb.hex=function(r){let t=(((Math.round(r[0])&255)<<16)+((Math.round(r[1])&255)<<8)+(Math.round(r[2])&255)).toString(16).toUpperCase();return"000000".substring(t.length)+t};M.hex.rgb=function(r){let e=r.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let t=e[0];e[0].length===3&&(t=t.split("").map(l=>l+l).join(""));let n=parseInt(t,16),i=n>>16&255,o=n>>8&255,a=n&255;return[i,o,a]};M.rgb.hcg=function(r){let e=r[0]/255,t=r[1]/255,n=r[2]/255,i=Math.max(Math.max(e,t),n),o=Math.min(Math.min(e,t),n),a=i-o,l,c;return a<1?l=o/(1-a):l=0,a<=0?c=0:i===e?c=(t-n)/a%6:i===t?c=2+(n-e)/a:c=4+(e-t)/a,c/=6,c%=1,[c*360,a*100,l*100]};M.hsl.hcg=function(r){let e=r[1]/100,t=r[2]/100,n=t<.5?2*e*t:2*e*(1-t),i=0;return n<1&&(i=(t-.5*n)/(1-n)),[r[0],n*100,i*100]};M.hsv.hcg=function(r){let e=r[1]/100,t=r[2]/100,n=e*t,i=0;return n<1&&(i=(t-n)/(1-n)),[r[0],n*100,i*100]};M.hcg.rgb=function(r){let e=r[0]/360,t=r[1]/100,n=r[2]/100;if(t===0)return[n*255,n*255,n*255];let i=[0,0,0],o=e%1*6,a=o%1,l=1-a,c=0;switch(Math.floor(o)){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-t)*n,[(t*i[0]+c)*255,(t*i[1]+c)*255,(t*i[2]+c)*255]};M.hcg.hsv=function(r){let e=r[1]/100,t=r[2]/100,n=e+t*(1-e),i=0;return n>0&&(i=e/n),[r[0],i*100,n*100]};M.hcg.hsl=function(r){let e=r[1]/100,n=r[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))),[r[0],i*100,n*100]};M.hcg.hwb=function(r){let e=r[1]/100,t=r[2]/100,n=e+t*(1-e);return[r[0],(n-e)*100,(1-n)*100]};M.hwb.hcg=function(r){let e=r[1]/100,n=1-r[2]/100,i=n-e,o=0;return i<1&&(o=(n-i)/(1-i)),[r[0],i*100,o*100]};M.apple.rgb=function(r){return[r[0]/65535*255,r[1]/65535*255,r[2]/65535*255]};M.rgb.apple=function(r){return[r[0]/255*65535,r[1]/255*65535,r[2]/255*65535]};M.gray.rgb=function(r){return[r[0]/100*255,r[0]/100*255,r[0]/100*255]};M.gray.hsl=function(r){return[0,0,r[0]]};M.gray.hsv=M.gray.hsl;M.gray.hwb=function(r){return[0,100,r[0]]};M.gray.cmyk=function(r){return[0,0,0,r[0]]};M.gray.lab=function(r){return[r[0],0,0]};M.gray.hex=function(r){let e=Math.round(r[0]/100*255)&255,n=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(n.length)+n};M.rgb.gray=function(r){return[(r[0]+r[1]+r[2])/3/255*100]}});var Ll=J((i1,Bl)=>{var ti=Rs();function fm(){let r={},e=Object.keys(ti);for(let t=e.length,n=0;n<t;n++)r[e[n]]={distance:-1,parent:null};return r}function hm(r){let e=fm(),t=[r];for(e[r].distance=0;t.length;){let n=t.pop(),i=Object.keys(ti[n]);for(let o=i.length,a=0;a<o;a++){let l=i[a],c=e[l];c.distance===-1&&(c.distance=e[n].distance+1,c.parent=n,t.unshift(l))}}return e}function pm(r,e){return function(t){return e(r(t))}}function mm(r,e){let t=[e[r].parent,r],n=ti[e[r].parent][r],i=e[r].parent;for(;e[i].parent;)t.unshift(e[i].parent),n=pm(ti[e[i].parent][i],n),i=e[i].parent;return n.conversion=t,n}Bl.exports=function(r){let e=hm(r),t={},n=Object.keys(e);for(let i=n.length,o=0;o<i;o++){let a=n[o];e[a].parent!==null&&(t[a]=mm(a,e))}return t}});var $l=J((s1,Nl)=>{var Is=Rs(),gm=Ll(),kr={},ym=Object.keys(Is);function bm(r){let e=function(...t){let n=t[0];return n==null?n:(n.length>1&&(t=n),r(t))};return"conversion"in r&&(e.conversion=r.conversion),e}function vm(r){let e=function(...t){let n=t[0];if(n==null)return n;n.length>1&&(t=n);let i=r(t);if(typeof i=="object")for(let o=i.length,a=0;a<o;a++)i[a]=Math.round(i[a]);return i};return"conversion"in r&&(e.conversion=r.conversion),e}ym.forEach(r=>{kr[r]={},Object.defineProperty(kr[r],"channels",{value:Is[r].channels}),Object.defineProperty(kr[r],"labels",{value:Is[r].labels});let e=gm(r);Object.keys(e).forEach(n=>{let i=e[n];kr[r][n]=vm(i),kr[r][n].raw=bm(i)})});Nl.exports=kr});var Zl=J((o1,Wl)=>{"use strict";var Ul=(r,e)=>(...t)=>`\x1B[${r(...t)+e}m`,zl=(r,e)=>(...t)=>{let n=r(...t);return`\x1B[${38+e};5;${n}m`},ql=(r,e)=>(...t)=>{let n=r(...t);return`\x1B[${38+e};2;${n[0]};${n[1]};${n[2]}m`},ri=r=>r,Vl=(r,e,t)=>[r,e,t],Fr=(r,e,t)=>{Object.defineProperty(r,e,{get:()=>{let n=t();return Object.defineProperty(r,e,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})},Os,Pr=(r,e,t,n)=>{Os===void 0&&(Os=$l());let i=n?10:0,o={};for(let[a,l]of Object.entries(Os)){let c=a==="ansi16"?"ansi":a;a===e?o[c]=r(t,i):typeof l=="object"&&(o[c]=r(l[e],i))}return o};function Dm(){let r=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[t,n]of Object.entries(e)){for(let[i,o]of Object.entries(n))e[i]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[i]=e[i],r.set(o[0],o[1]);Object.defineProperty(e,t,{value:n,enumerable:!1})}return Object.defineProperty(e,"codes",{value:r,enumerable:!1}),e.color.close="\x1B[39m",e.bgColor.close="\x1B[49m",Fr(e.color,"ansi",()=>Pr(Ul,"ansi16",ri,!1)),Fr(e.color,"ansi256",()=>Pr(zl,"ansi256",ri,!1)),Fr(e.color,"ansi16m",()=>Pr(ql,"rgb",Vl,!1)),Fr(e.bgColor,"ansi",()=>Pr(Ul,"ansi16",ri,!0)),Fr(e.bgColor,"ansi256",()=>Pr(zl,"ansi256",ri,!0)),Fr(e.bgColor,"ansi16m",()=>Pr(ql,"rgb",Vl,!0)),e}Object.defineProperty(Wl,"exports",{enumerable:!0,get:Dm})});var Kl=J((a1,Gl)=>{"use strict";Gl.exports=(r,e=process.argv)=>{let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),i=e.indexOf("--");return n!==-1&&(i===-1||n<i)}});var Yl=J((l1,Jl)=>{"use strict";var wm=require("os"),Hl=require("tty"),Ie=Kl(),{env:se}=process,Et;Ie("no-color")||Ie("no-colors")||Ie("color=false")||Ie("color=never")?Et=0:(Ie("color")||Ie("colors")||Ie("color=true")||Ie("color=always"))&&(Et=1);"FORCE_COLOR"in se&&(se.FORCE_COLOR==="true"?Et=1:se.FORCE_COLOR==="false"?Et=0:Et=se.FORCE_COLOR.length===0?1:Math.min(parseInt(se.FORCE_COLOR,10),3));function Ms(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function js(r,e){if(Et===0)return 0;if(Ie("color=16m")||Ie("color=full")||Ie("color=truecolor"))return 3;if(Ie("color=256"))return 2;if(r&&!e&&Et===void 0)return 0;let t=Et||0;if(se.TERM==="dumb")return t;if(process.platform==="win32"){let n=wm.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in se)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in se)||se.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in se)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(se.TEAMCITY_VERSION)?1:0;if(se.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in se){let n=parseInt((se.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(se.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(se.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(se.TERM)||"COLORTERM"in se?1:t}function Sm(r){let e=js(r,r&&r.isTTY);return Ms(e)}Jl.exports={supportsColor:Sm,stdout:Ms(js(!0,Hl.isatty(1))),stderr:Ms(js(!0,Hl.isatty(2)))}});var Xl=J((c1,Ql)=>{"use strict";var Cm=(r,e,t)=>{let n=r.indexOf(e);if(n===-1)return r;let i=e.length,o=0,a="";do a+=r.substr(o,n-o)+e+t,o=n+i,n=r.indexOf(e,o);while(n!==-1);return a+=r.substr(o),a},_m=(r,e,t,n)=>{let i=0,o="";do{let a=r[n-1]==="\r";o+=r.substr(i,(a?n-1:n)-i)+e+(a?`\r
|
|
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
|
|
4
4
|
`:`
|
|
5
|
-
`)+
|
|
6
|
-
`,i)}while(n!==-1);return
|
|
7
|
-
`],["r","\r"],["t"," "],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e","\x1B"],["a","\x07"]]);function
|
|
8
|
-
`);return o!==-1&&(e=Rm(e,i,n,o)),n+e+i},Bs,cc=(r,...e)=>{let[t]=e;if(!ni(t)||!ni(t.raw))return e.join(" ");let n=e.slice(1),i=[t.raw[0]];for(let o=1;o<t.length;o++)i.push(String(n[o-1]).replace(/[{}\\]/g,"\\$&"),String(t.raw[o]));return Bs===void 0&&(Bs=ic()),Bs(r,i.join(""))};Object.defineProperties(ii.prototype,Tr);var oi=ii();oi.supportsColor=Ls;oi.stderr=ii({level:Ns?Ns.level:0});oi.stderr.supportsColor=Ns;uc.exports=oi});var fc=J(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.generateRandomBase64=jm;var Mm=require("crypto");function jm(r=18){return(0,Mm.randomBytes)(r).toString("base64")}});var hc=J(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.readFileAsBase64=Lm;var Bm=require("fs/promises");async function Lm(r){return{success:!0,base64:await(0,Bm.readFile)(r,"base64")}}});var bc=J(ln=>{"use strict";var Zs=ln&&ln.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ln,"__esModule",{value:!0});ln.terminalSize=Um;var Nm=require("child_process"),ai=Zs(require("fs")),Ar=Zs(require("process")),$m=Zs(require("tty")),mc=80,gc=24,Ws=(r,e,{shell:t,env:n}={})=>(0,Nm.execFileSync)(r,e,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:500,shell:t,env:n}).trim(),li=(r,e)=>({columns:Number.parseInt(r,10),rows:Number.parseInt(e,10)}),yc=(r,e)=>{let{columns:t,rows:n}=li(r,e);if(!(Number.isNaN(t)||Number.isNaN(n))&&!(t===mc&&n===gc))return{columns:t,rows:n}};function Um(){let{env:r,stdout:e,stderr:t}=Ar.default;if(e?.columns&&e?.rows)return li(e.columns,e.rows);if(t?.columns&&t?.rows)return li(t.columns,t.rows);if(r.COLUMNS&&r.LINES)return li(r.COLUMNS,r.LINES);let n={columns:mc,rows:gc};return Ar.default.platform==="win32"?Vs()??n:Ar.default.platform==="darwin"?pc()??Vs()??n:pc()??Vs()??zm()??n}var pc=()=>{try{let r=Ar.default.platform==="darwin"?ai.default.constants.O_EVTONLY|ai.default.constants.O_NONBLOCK:ai.default.constants.O_NONBLOCK,{columns:e,rows:t}=$m.default.WriteStream(ai.default.openSync("/dev/tty",r));return{columns:e,rows:t}}catch{}},Vs=()=>{try{let r=Ws("tput",["cols"],{env:{TERM:"dumb",...Ar.default.env}}),e=Ws("tput",["lines"],{env:{TERM:"dumb",...Ar.default.env}});if(r&&e)return yc(r,e)}catch{}},zm=()=>{try{let r=Ws("resize",["-u"]).match(/\d+/g);if(r.length===2)return yc(r[0],r[1])}catch{}}});var ot=J((m1,wc)=>{"use strict";var vc=["nodebuffer","arraybuffer","fragments"],Dc=typeof Blob<"u";Dc&&vc.push("blob");wc.exports={BINARY_TYPES:vc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Dc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var cn=J((g1,ci)=>{"use strict";var{EMPTY_BUFFER:qm}=ot(),Gs=Buffer[Symbol.species];function Vm(r,e){if(r.length===0)return qm;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let i=0;i<r.length;i++){let o=r[i];t.set(o,n),n+=o.length}return n<e?new Gs(t.buffer,t.byteOffset,n):t}function Sc(r,e,t,n,i){for(let o=0;o<i;o++)t[n+o]=r[o]^e[o&3]}function Cc(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Wm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Ks(r){if(Ks.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Gs(r):ArrayBuffer.isView(r)?e=new Gs(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Ks.readOnly=!1),e}ci.exports={concat:Vm,mask:Sc,toArrayBuffer:Wm,toBuffer:Ks,unmask:Cc};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");ci.exports.mask=function(e,t,n,i,o){o<48?Sc(e,t,n,i,o):r.mask(e,t,n,i,o)},ci.exports.unmask=function(e,t){e.length<32?Cc(e,t):r.unmask(e,t)}}catch{}});var xc=J((y1,Ec)=>{"use strict";var _c=Symbol("kDone"),Hs=Symbol("kRun"),Js=class{constructor(e){this[_c]=()=>{this.pending--,this[Hs]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Hs]()}[Hs](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[_c])}}};Ec.exports=Js});var dn=J((b1,Tc)=>{"use strict";var un=require("zlib"),kc=cn(),Zm=xc(),{kStatusCode:Fc}=ot(),Gm=Buffer[Symbol.species],Km=Buffer.from([0,0,255,255]),di=Symbol("permessage-deflate"),at=Symbol("total-length"),Rr=Symbol("callback"),xt=Symbol("buffers"),Ir=Symbol("error"),ui,Ys=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!ui){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ui=new Zm(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[Rr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(i=>!(t.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>i.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let i=t[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 o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=o}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}"`);t[n]=i})}),e}decompress(e,t,n){ui.add(i=>{this._decompress(e,t,(o,a)=>{i(),n(o,a)})})}compress(e,t,n){ui.add(i=>{this._compress(e,t,(o,a)=>{i(),n(o,a)})})}_decompress(e,t,n){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?un.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=un.createInflateRaw({...this._options.zlibInflateOptions,windowBits:a}),this._inflate[di]=this,this._inflate[at]=0,this._inflate[xt]=[],this._inflate.on("error",Jm),this._inflate.on("data",Pc)}this._inflate[Rr]=n,this._inflate.write(e),t&&this._inflate.write(Km),this._inflate.flush(()=>{let o=this._inflate[Ir];if(o){this._inflate.close(),this._inflate=null,n(o);return}let a=kc.concat(this._inflate[xt],this._inflate[at]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[at]=0,this._inflate[xt]=[],t&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,a)})}_compress(e,t,n){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,a=typeof this.params[o]!="number"?un.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=un.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:a}),this._deflate[at]=0,this._deflate[xt]=[],this._deflate.on("data",Hm)}this._deflate[Rr]=n,this._deflate.write(e),this._deflate.flush(un.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=kc.concat(this._deflate[xt],this._deflate[at]);t&&(o=new Gm(o.buffer,o.byteOffset,o.length-4)),this._deflate[Rr]=null,this._deflate[at]=0,this._deflate[xt]=[],t&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,o)})}};Tc.exports=Ys;function Hm(r){this[xt].push(r),this[at]+=r.length}function Pc(r){if(this[at]+=r.length,this[di]._maxPayload<1||this[at]<=this[di]._maxPayload){this[xt].push(r);return}this[Ir]=new RangeError("Max payload size exceeded"),this[Ir].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ir][Fc]=1009,this.removeListener("data",Pc),this.reset()}function Jm(r){if(this[di]._inflate=null,this[Ir]){this[Rr](this[Ir]);return}r[Fc]=1007,this[Rr](r)}});var Or=J((v1,fi)=>{"use strict";var{isUtf8:Ac}=require("buffer"),{hasBlob:Ym}=ot(),Qm=[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 Xm(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Qs(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function eg(r){return Ym&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}fi.exports={isBlob:eg,isValidStatusCode:Xm,isValidUTF8:Qs,tokenChars:Qm};if(Ac)fi.exports.isValidUTF8=function(r){return r.length<24?Qs(r):Ac(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");fi.exports.isValidUTF8=function(e){return e.length<32?Qs(e):r(e)}}catch{}});var no=J((D1,Lc)=>{"use strict";var{Writable:tg}=require("stream"),Rc=dn(),{BINARY_TYPES:rg,EMPTY_BUFFER:Ic,kStatusCode:ng,kWebSocket:ig}=ot(),{concat:Xs,toArrayBuffer:sg,unmask:og}=cn(),{isValidStatusCode:ag,isValidUTF8:Oc}=Or(),hi=Buffer[Symbol.species],Oe=0,Mc=1,jc=2,Bc=3,eo=4,to=5,pi=6,ro=class extends tg{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||rg[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ig]=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=Oe}_write(e,t,n){if(this._opcode===8&&this._state==Oe)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 hi(n.buffer,n.byteOffset+e,n.length-e),new hi(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=t.length-e;e>=n.length?t.set(this._buffers.shift(),i):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new hi(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Oe:this.getInfo(e);break;case Mc:this.getPayloadLength16(e);break;case jc:this.getPayloadLength64(e);break;case Bc:this.getMask();break;case eo:this.getData(e);break;case to:case pi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[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=(t[0]&64)===64;if(n&&!this._extensions[Rc.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[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=(t[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=Mc:this._payloadLength===127?this._state=jc: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 t=this.consume(8),n=t.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)+t.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 t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Bc:this._state=eo}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=eo}getData(e){let t=Ic;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&og(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=to,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Rc.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return t(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let a=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(a);return}this._fragments.push(o)}this.dataMessage(t),this._state===Oe&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Oe;return}let t=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=Xs(n,t):this._binaryType==="arraybuffer"?i=sg(Xs(n,t)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Oe):(this._state=pi,setImmediate(()=>{this.emit("message",i,!0),this._state=Oe,this.startLoop(e)}))}else{let i=Xs(n,t);if(!this._skipUTF8Validation&&!Oc(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===to||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Oe):(this._state=pi,setImmediate(()=>{this.emit("message",i,!1),this._state=Oe,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ic),this.end();else{let n=e.readUInt16BE(0);if(!ag(n)){let o=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(o);return}let i=new hi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Oc(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(o);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=Oe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Oe):(this._state=pi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Oe,this.startLoop(t)}))}createError(e,t,n,i,o){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=o,a[ng]=i,a}};Lc.exports=ro});var oo=J((S1,Uc)=>{"use strict";var{Duplex:w1}=require("stream"),{randomFillSync:lg}=require("crypto"),Nc=dn(),{EMPTY_BUFFER:cg,kWebSocket:ug,NOOP:dg}=ot(),{isBlob:Mr,isValidStatusCode:fg}=Or(),{mask:$c,toBuffer:Qt}=cn(),Me=Symbol("kByteLength"),hg=Buffer.alloc(4),mi=8*1024,Xt,jr=mi,Le=0,pg=1,mg=2,io=class r{constructor(e,t,n){this._extensions=t||{},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=Le,this.onerror=dg,this[ug]=void 0}static frame(e,t){let n,i=!1,o=2,a=!1;t.mask&&(n=t.maskBuffer||hg,t.generateMask?t.generateMask(n):(jr===mi&&(Xt===void 0&&(Xt=Buffer.alloc(mi)),lg(Xt,0,mi),jr=0),n[0]=Xt[jr++],n[1]=Xt[jr++],n[2]=Xt[jr++],n[3]=Xt[jr++]),a=(n[0]|n[1]|n[2]|n[3])===0,o=6);let l;typeof e=="string"?(!t.mask||a)&&t[Me]!==void 0?l=t[Me]:(e=Buffer.from(e),l=e.length):(l=e.length,i=t.mask&&t.readOnly&&!a);let c=l;l>=65536?(o+=8,c=127):l>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(i?l+o:o);return u[0]=t.fin?t.opcode|128:t.opcode,t.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)),t.mask?(u[1]|=128,u[o-4]=n[0],u[o-3]=n[1],u[o-2]=n[2],u[o-1]=n[3],a?[u,e]:i?($c(e,n,u,o,l),[u]):($c(e,n,e,0,l),[u,e])):[u,e]}close(e,t,n,i){let o;if(e===void 0)o=cg;else{if(typeof e!="number"||!fg(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let l=Buffer.byteLength(t);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+l),o.writeUInt16BE(e,0),typeof t=="string"?o.write(t,2):o.set(t,2)}}let a={[Me]:o.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Le?this.enqueue([this.dispatch,o,!1,a,i]):this.sendFrame(r.frame(o,a),i)}ping(e,t,n){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):Mr(e)?(i=e.size,o=!1):(e=Qt(e),i=e.length,o=Qt.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Me]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};Mr(e)?this._state!==Le?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Le?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}pong(e,t,n){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):Mr(e)?(i=e.size,o=!1):(e=Qt(e),i=e.length,o=Qt.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let a={[Me]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};Mr(e)?this._state!==Le?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Le?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}send(e,t,n){let i=this._extensions[Nc.extensionName],o=t.binary?2:1,a=t.compress,l,c;typeof e=="string"?(l=Buffer.byteLength(e),c=!1):Mr(e)?(l=e.size,c=!1):(e=Qt(e),l=e.length,c=Qt.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,o=0),t.fin&&(this._firstFragment=!0);let u={[Me]:l,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:a};Mr(e)?this._state!==Le?this.enqueue([this.getBlobData,e,this._compress,u,n]):this.getBlobData(e,this._compress,u,n):this._state!==Le?this.enqueue([this.dispatch,e,this._compress,u,n]):this.dispatch(e,this._compress,u,n)}getBlobData(e,t,n,i){this._bufferedBytes+=n[Me],this._state=mg,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(so,this,l,i);return}this._bufferedBytes-=n[Me];let a=Qt(o);t?this.dispatch(a,t,n,i):(this._state=Le,this.sendFrame(r.frame(a,n),i),this.dequeue())}).catch(o=>{process.nextTick(gg,this,o,i)})}dispatch(e,t,n,i){if(!t){this.sendFrame(r.frame(e,n),i);return}let o=this._extensions[Nc.extensionName];this._bufferedBytes+=n[Me],this._state=pg,o.compress(e,n.fin,(a,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");so(this,c,i);return}this._bufferedBytes-=n[Me],this._state=Le,n.readOnly=!1,this.sendFrame(r.frame(l,n),i),this.dequeue()})}dequeue(){for(;this._state===Le&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Uc.exports=io;function so(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let i=r._queue[n],o=i[i.length-1];typeof o=="function"&&o(e)}}function gg(r,e,t){so(r,e,t),r.onerror(e)}});var Jc=J((C1,Hc)=>{"use strict";var{kForOnEventAttribute:fn,kListener:ao}=ot(),zc=Symbol("kCode"),qc=Symbol("kData"),Vc=Symbol("kError"),Wc=Symbol("kMessage"),Zc=Symbol("kReason"),Br=Symbol("kTarget"),Gc=Symbol("kType"),Kc=Symbol("kWasClean"),lt=class{constructor(e){this[Br]=null,this[Gc]=e}get target(){return this[Br]}get type(){return this[Gc]}};Object.defineProperty(lt.prototype,"target",{enumerable:!0});Object.defineProperty(lt.prototype,"type",{enumerable:!0});var er=class extends lt{constructor(e,t={}){super(e),this[zc]=t.code===void 0?0:t.code,this[Zc]=t.reason===void 0?"":t.reason,this[Kc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[zc]}get reason(){return this[Zc]}get wasClean(){return this[Kc]}};Object.defineProperty(er.prototype,"code",{enumerable:!0});Object.defineProperty(er.prototype,"reason",{enumerable:!0});Object.defineProperty(er.prototype,"wasClean",{enumerable:!0});var Lr=class extends lt{constructor(e,t={}){super(e),this[Vc]=t.error===void 0?null:t.error,this[Wc]=t.message===void 0?"":t.message}get error(){return this[Vc]}get message(){return this[Wc]}};Object.defineProperty(Lr.prototype,"error",{enumerable:!0});Object.defineProperty(Lr.prototype,"message",{enumerable:!0});var hn=class extends lt{constructor(e,t={}){super(e),this[qc]=t.data===void 0?null:t.data}get data(){return this[qc]}};Object.defineProperty(hn.prototype,"data",{enumerable:!0});var yg={addEventListener(r,e,t={}){for(let i of this.listeners(r))if(!t[fn]&&i[ao]===e&&!i[fn])return;let n;if(r==="message")n=function(o,a){let l=new hn("message",{data:a?o:o.toString()});l[Br]=this,gi(e,this,l)};else if(r==="close")n=function(o,a){let l=new er("close",{code:o,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Br]=this,gi(e,this,l)};else if(r==="error")n=function(o){let a=new Lr("error",{error:o,message:o.message});a[Br]=this,gi(e,this,a)};else if(r==="open")n=function(){let o=new lt("open");o[Br]=this,gi(e,this,o)};else return;n[fn]=!!t[fn],n[ao]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[ao]===e&&!t[fn]){this.removeListener(r,t);break}}};Hc.exports={CloseEvent:er,ErrorEvent:Lr,Event:lt,EventTarget:yg,MessageEvent:hn};function gi(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var lo=J((_1,Yc)=>{"use strict";var{tokenChars:pn}=Or();function We(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function bg(r){let e=Object.create(null),t=Object.create(null),n=!1,i=!1,o=!1,a,l,c=-1,u=-1,h=-1,f=0;for(;f<r.length;f++)if(u=r.charCodeAt(f),a===void 0)if(h===-1&&pn[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=r.slice(c,h);u===44?(We(e,p,t),t=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&&pn[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),We(t,r.slice(c,h),!0),u===44&&(We(e,a,t),t=Object.create(null),a=void 0),c=h=-1}else if(u===61&&c!==-1&&h===-1)l=r.slice(c,f),c=h=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(i){if(pn[u]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:n||(n=!0),i=!1}else if(o)if(pn[u]===1)c===-1&&(c=f);else if(u===34&&c!==-1)o=!1,h=f;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(u===34&&r.charCodeAt(f-1)===61)o=!0;else if(h===-1&&pn[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=r.slice(c,h);n&&(p=p.replace(/\\/g,""),n=!1),We(t,l,p),u===44&&(We(e,a,t),t=Object.create(null),a=void 0),l=void 0,c=h=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=f);let d=r.slice(c,h);return a===void 0?We(e,d,t):(l===void 0?We(t,d,!0):n?We(t,l,d.replace(/\\/g,"")):We(t,l,d),We(e,a,t)),e}function vg(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(i=>{let o=n[i];return Array.isArray(o)||(o=[o]),o.map(a=>a===!0?i:`${i}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Yc.exports={format:vg,parse:bg}});var Di=J((k1,cu)=>{"use strict";var Dg=require("events"),wg=require("https"),Sg=require("http"),eu=require("net"),Cg=require("tls"),{randomBytes:_g,createHash:Eg}=require("crypto"),{Duplex:E1,Readable:x1}=require("stream"),{URL:co}=require("url"),kt=dn(),xg=no(),kg=oo(),{isBlob:Fg}=Or(),{BINARY_TYPES:Qc,CLOSE_TIMEOUT:Pg,EMPTY_BUFFER:yi,GUID:Tg,kForOnEventAttribute:uo,kListener:Ag,kStatusCode:Rg,kWebSocket:oe,NOOP:tu}=ot(),{EventTarget:{addEventListener:Ig,removeEventListener:Og}}=Jc(),{format:Mg,parse:jg}=lo(),{toBuffer:Bg}=cn(),ru=Symbol("kAborted"),fo=[8,13],ct=["CONNECTING","OPEN","CLOSING","CLOSED"],Lg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,te=class r extends Dg{constructor(e,t,n){super(),this._binaryType=Qc[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=yi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),nu(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Qc.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,t,n){let i=new xg({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),o=new kg(e,this._extensions,n.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[oe]=this,o[oe]=this,e[oe]=this,i.on("conclude",Ug),i.on("drain",zg),i.on("error",qg),i.on("message",Vg),i.on("ping",Wg),i.on("pong",Zg),o.onerror=Gg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",ou),e.on("data",vi),e.on("end",au),e.on("error",lu),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[kt.extensionName]&&this._extensions[kt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Ee(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),su(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ho(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||yi,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ho(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||yi,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){ho(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[kt.extensionName]||(i.compress=!1),this._sender.send(e||yi,i,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Ee(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(te,"CONNECTING",{enumerable:!0,value:ct.indexOf("CONNECTING")});Object.defineProperty(te.prototype,"CONNECTING",{enumerable:!0,value:ct.indexOf("CONNECTING")});Object.defineProperty(te,"OPEN",{enumerable:!0,value:ct.indexOf("OPEN")});Object.defineProperty(te.prototype,"OPEN",{enumerable:!0,value:ct.indexOf("OPEN")});Object.defineProperty(te,"CLOSING",{enumerable:!0,value:ct.indexOf("CLOSING")});Object.defineProperty(te.prototype,"CLOSING",{enumerable:!0,value:ct.indexOf("CLOSING")});Object.defineProperty(te,"CLOSED",{enumerable:!0,value:ct.indexOf("CLOSED")});Object.defineProperty(te.prototype,"CLOSED",{enumerable:!0,value:ct.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(te.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(te.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[uo])return e[Ag];return null},set(e){for(let t of this.listeners(r))if(t[uo]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[uo]:!0})}})});te.prototype.addEventListener=Ig;te.prototype.removeEventListener=Og;cu.exports=te;function nu(r,e,t,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Pg,protocolVersion:fo[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(r._autoPong=i.autoPong,r._closeTimeout=i.closeTimeout,!fo.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${fo.join(", ")})`);let o;if(e instanceof co)o=e;else try{o=new co(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),r._url=o.href;let a=o.protocol==="wss:",l=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!a&&!l?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let g=new SyntaxError(c);if(r._redirects===0)throw g;bi(r,g);return}let u=a?443:80,h=_g(16).toString("base64"),f=a?wg.request:Sg.request,d=new Set,p;if(i.createConnection=i.createConnection||(a?$g:Ng),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(p=new kt(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Mg({[kt.extensionName]:p.offer()})),t.length){for(let g of t){if(typeof g!="string"||!Lg.test(g)||d.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");d.add(g)}i.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),l){let g=i.path.split(":");i.socketPath=g[0],i.path=g[1]}let m;if(i.followRedirects){if(r._redirects===0){r._originalIpc=l,r._originalSecure=a,r._originalHostOrSocketPath=l?i.socketPath:o.host;let g=n&&n.headers;if(n={...n,headers:{}},g)for(let[b,y]of Object.entries(g))n.headers[b.toLowerCase()]=y}else if(r.listenerCount("redirect")===0){let g=l?r._originalIpc?i.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:o.host===r._originalHostOrSocketPath;(!g||r._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=r._req=f(i),r._redirects&&r.emit("redirect",r.url,m)}else m=r._req=f(i);i.timeout&&m.on("timeout",()=>{Ee(r,m,"Opening handshake has timed out")}),m.on("error",g=>{m===null||m[ru]||(m=r._req=null,bi(r,g))}),m.on("response",g=>{let b=g.headers.location,y=g.statusCode;if(b&&i.followRedirects&&y>=300&&y<400){if(++r._redirects>i.maxRedirects){Ee(r,m,"Maximum redirects exceeded");return}m.abort();let D;try{D=new co(b,e)}catch{let S=new SyntaxError(`Invalid URL: ${b}`);bi(r,S);return}nu(r,D,t,n)}else r.emit("unexpected-response",m,g)||Ee(r,m,`Unexpected server response: ${g.statusCode}`)}),m.on("upgrade",(g,b,y)=>{if(r.emit("upgrade",g),r.readyState!==te.CONNECTING)return;m=r._req=null;let D=g.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){Ee(r,b,"Invalid Upgrade header");return}let v=Eg("sha1").update(h+Tg).digest("base64");if(g.headers["sec-websocket-accept"]!==v){Ee(r,b,"Invalid Sec-WebSocket-Accept header");return}let S=g.headers["sec-websocket-protocol"],_;if(S!==void 0?d.size?d.has(S)||(_="Server sent an invalid subprotocol"):_="Server sent a subprotocol but none was requested":d.size&&(_="Server sent no subprotocol"),_){Ee(r,b,_);return}S&&(r._protocol=S);let k=g.headers["sec-websocket-extensions"];if(k!==void 0){if(!p){Ee(r,b,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let x;try{x=jg(k)}catch{Ee(r,b,"Invalid Sec-WebSocket-Extensions header");return}let z=Object.keys(x);if(z.length!==1||z[0]!==kt.extensionName){Ee(r,b,"Server indicated an extension that was not requested");return}try{p.accept(x[kt.extensionName])}catch{Ee(r,b,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[kt.extensionName]=p}r.setSocket(b,y,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,r):m.end()}function bi(r,e){r._readyState=te.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Ng(r){return r.path=r.socketPath,eu.connect(r)}function $g(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=eu.isIP(r.host)?"":r.host),Cg.connect(r)}function Ee(r,e,t){r._readyState=te.CLOSING;let n=new Error(t);Error.captureStackTrace(n,Ee),e.setHeader?(e[ru]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(bi,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function ho(r,e,t){if(e){let n=Fg(e)?e.size:Bg(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${ct[r.readyState]})`);process.nextTick(t,n)}}function Ug(r,e){let t=this[oe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[oe]!==void 0&&(t._socket.removeListener("data",vi),process.nextTick(iu,t._socket),r===1005?t.close():t.close(r,e))}function zg(){let r=this[oe];r.isPaused||r._socket.resume()}function qg(r){let e=this[oe];e._socket[oe]!==void 0&&(e._socket.removeListener("data",vi),process.nextTick(iu,e._socket),e.close(r[Rg])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Xc(){this[oe].emitClose()}function Vg(r,e){this[oe].emit("message",r,e)}function Wg(r){let e=this[oe];e._autoPong&&e.pong(r,!this._isServer,tu),e.emit("ping",r)}function Zg(r){this[oe].emit("pong",r)}function iu(r){r.resume()}function Gg(r){let e=this[oe];e.readyState!==te.CLOSED&&(e.readyState===te.OPEN&&(e._readyState=te.CLOSING,su(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function su(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function ou(){let r=this[oe];if(this.removeListener("close",ou),this.removeListener("data",vi),this.removeListener("end",au),r._readyState=te.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[oe]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Xc),r._receiver.on("finish",Xc))}function vi(r){this[oe]._receiver.write(r)||this.pause()}function au(){let r=this[oe];r._readyState=te.CLOSING,r._receiver.end(),this.end()}function lu(){let r=this[oe];this.removeListener("error",lu),this.on("error",tu),r&&(r._readyState=te.CLOSING,this.destroy())}});var hu=J((P1,fu)=>{"use strict";var F1=Di(),{Duplex:Kg}=require("stream");function uu(r){r.emit("close")}function Hg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function du(r){this.removeListener("error",du),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Jg(r,e){let t=!0,n=new Kg({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(o,a){let l=!a&&n._readableState.objectMode?o.toString():o;n.push(l)||r.pause()}),r.once("error",function(o){n.destroyed||(t=!1,n.destroy(o))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,o){if(r.readyState===r.CLOSED){o(i),process.nextTick(uu,n);return}let a=!1;r.once("error",function(c){a=!0,o(c)}),r.once("close",function(){a||o(i),process.nextTick(uu,n)}),t&&r.terminate()},n._final=function(i){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(i)});return}r._socket!==null&&(r._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){i()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(i,o,a){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(i,o,a)});return}r.send(i,a)},n.on("end",Hg),n.on("error",du),n}fu.exports=Jg});var mu=J((T1,pu)=>{"use strict";var{tokenChars:Yg}=Or();function Qg(r){let e=new Set,t=-1,n=-1,i=0;for(i;i<r.length;i++){let a=r.charCodeAt(i);if(n===-1&&Yg[a]===1)t===-1&&(t=i);else if(i!==0&&(a===32||a===9))n===-1&&t!==-1&&(n=i);else if(a===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let l=r.slice(t,n);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let o=r.slice(t,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}pu.exports={parse:Qg}});var Su=J((R1,wu)=>{"use strict";var Xg=require("events"),wi=require("http"),{Duplex:A1}=require("stream"),{createHash:ey}=require("crypto"),gu=lo(),tr=dn(),ty=mu(),ry=Di(),{CLOSE_TIMEOUT:ny,GUID:iy,kWebSocket:sy}=ot(),oy=/^[+/0-9A-Za-z]{22}==$/,yu=0,bu=1,Du=2,po=class extends Xg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ny,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ry,...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=wi.createServer((n,i)=>{let o=wi.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=ay(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,a)=>{this.handleUpgrade(i,o,a,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=yu}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===Du){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(mn,this);return}if(e&&this.once("close",e),this._state!==bu)if(this._state=bu,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(mn,this):process.nextTick(mn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{mn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,i){t.on("error",vu);let o=e.headers["sec-websocket-key"],a=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){rr(this,e,t,405,"Invalid HTTP method");return}if(a===void 0||a.toLowerCase()!=="websocket"){rr(this,e,t,400,"Invalid Upgrade header");return}if(o===void 0||!oy.test(o)){rr(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){rr(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){gn(t,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=ty.parse(c)}catch{rr(this,e,t,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 tr(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=gu.parse(h);p[tr.extensionName]&&(d.accept(p[tr.extensionName]),f[tr.extensionName]=d)}catch{rr(this,e,t,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,b)=>{if(!p)return gn(t,m||401,g,b);this.completeUpgrade(f,o,u,e,t,n,i)});return}if(!this.options.verifyClient(d))return gn(t,401)}this.completeUpgrade(f,o,u,e,t,n,i)}completeUpgrade(e,t,n,i,o,a,l){if(!o.readable||!o.writable)return o.destroy();if(o[sy])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>yu)return gn(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ey("sha1").update(t+iy).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[tr.extensionName]){let f=e[tr.extensionName].params,d=gu.format({[tr.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${d}`),h._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
|
|
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
|
|
9
9
|
`).join(`\r
|
|
10
|
-
`)),
|
|
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
|
|
11
11
|
`+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
|
|
12
12
|
`)+`\r
|
|
13
13
|
\r
|
|
14
|
-
`+
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
`).filter(o=>o!==""))try{yield JSON.parse(i)}catch{console.warn("invalid json: ",i)}},Qh=r=>{if(!r)return wl;let e=r.includes("://");r.startsWith(":")&&(r=`http://127.0.0.1${r}`,e=!0),e||(r=`http://${r}`);let t=new URL(r),n=t.port;n||(e?n=t.protocol==="https:"?"443":"80":n=Dl);let i="";t.username&&(i=t.username,t.password&&(i+=`:${t.password}`),i+="@");let o=`${t.protocol}//${i}${t.hostname}:${n}${t.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},Xh=Object.defineProperty,ep=(r,e,t)=>e in r?Xh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ss=(r,e,t)=>(ep(r,typeof e!="symbol"?e+"":e,t),t),ks=class{constructor(e){Ss(this,"config"),Ss(this,"fetch"),Ss(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=Qh(e?.host??wl)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,t){t.stream=t.stream??!1;let n=`${this.config.host}/api/${e}`;if(t.stream){let o=new AbortController,a=await Dt(this.fetch,n,t,{signal:o.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let l=Yh(a.body),c=new _s(o,l,()=>{let u=this.ongoingStreamedRequests.indexOf(c);u>-1&&this.ongoingStreamedRequests.splice(u,1)});return this.ongoingStreamedRequests.push(c),c}return await(await Dt(this.fetch,n,t,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let t=new Uint8Array(e),n="",i=t.byteLength;for(let o=0;o<i;o++)n+=String.fromCharCode(t[o]);return btoa(n)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let t of e.messages)t.images&&(t.images=await Promise.all(t.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 Jh(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await Dt(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await ws(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await Dt(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await Dt(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await Dt(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await ws(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await ws(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 Dt(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 Dt(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},_w=new ks;var kw=Pe(vs(),1),tn=class extends ks{async encodeImage(e){if(typeof e!="string")return Buffer.from(e).toString("base64");try{if(en.default.existsSync(e)){let t=await en.promises.readFile((0,Fs.resolve)(e));return Buffer.from(t).toString("base64")}}catch{}return e}async fileExists(e){try{return await en.promises.access(e),!0}catch{return!1}}async create(e){if(e.from&&await this.fileExists((0,Fs.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)}},Fw=new tn;var s={};zh(s,{BRAND:()=>xp,DIRTY:()=>jt,EMPTY_PATH:()=>ip,INVALID:()=>L,NEVER:()=>um,OK:()=>fe,ParseStatus:()=>ce,Schema:()=>W,ZodAny:()=>Ct,ZodArray:()=>st,ZodBigInt:()=>Lt,ZodBoolean:()=>Nt,ZodBranded:()=>nn,ZodCatch:()=>Jt,ZodDate:()=>$t,ZodDefault:()=>Ht,ZodDiscriminatedUnion:()=>Qn,ZodEffects:()=>Re,ZodEnum:()=>Gt,ZodError:()=>De,ZodFirstPartyTypeKind:()=>F,ZodFunction:()=>ei,ZodIntersection:()=>Vt,ZodIssueCode:()=>E,ZodLazy:()=>Wt,ZodLiteral:()=>Zt,ZodMap:()=>_r,ZodNaN:()=>xr,ZodNativeEnum:()=>Kt,ZodNever:()=>Be,ZodNull:()=>zt,ZodNullable:()=>Ve,ZodNumber:()=>Bt,ZodObject:()=>we,ZodOptional:()=>Te,ZodParsedType:()=>R,ZodPipeline:()=>sn,ZodPromise:()=>_t,ZodReadonly:()=>Yt,ZodRecord:()=>Xn,ZodSchema:()=>W,ZodSet:()=>Er,ZodString:()=>St,ZodSymbol:()=>Sr,ZodTransformer:()=>Re,ZodTuple:()=>qe,ZodType:()=>W,ZodUndefined:()=>Ut,ZodUnion:()=>qt,ZodUnknown:()=>it,ZodVoid:()=>Cr,addIssueToContext:()=>T,any:()=>Mp,array:()=>Np,bigint:()=>Tp,boolean:()=>Rl,coerce:()=>cm,custom:()=>Pl,date:()=>Ap,datetimeRegex:()=>kl,defaultErrorMap:()=>rt,discriminatedUnion:()=>qp,effect:()=>tm,enum:()=>Qp,function:()=>Hp,getErrorMap:()=>vr,getParsedType:()=>ze,instanceof:()=>Fp,intersection:()=>Vp,isAborted:()=>Jn,isAsync:()=>Dr,isDirty:()=>Yn,isValid:()=>wt,late:()=>kp,lazy:()=>Jp,literal:()=>Yp,makeIssue:()=>rn,map:()=>Gp,nan:()=>Pp,nativeEnum:()=>Xp,never:()=>Bp,null:()=>Op,nullable:()=>nm,number:()=>Al,object:()=>$p,objectUtil:()=>Ps,oboolean:()=>lm,onumber:()=>am,optional:()=>rm,ostring:()=>om,pipeline:()=>sm,preprocess:()=>im,promise:()=>em,quotelessJson:()=>tp,record:()=>Zp,set:()=>Kp,setErrorMap:()=>np,strictObject:()=>Up,string:()=>Tl,symbol:()=>Rp,transformer:()=>tm,tuple:()=>Wp,undefined:()=>Ip,union:()=>zp,unknown:()=>jp,util:()=>G,void:()=>Lp});var G;(function(r){r.assertEqual=i=>{};function e(i){}r.assertIs=e;function t(i){throw new Error}r.assertNever=t,r.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},r.getValidEnumValues=i=>{let o=r.objectKeys(i).filter(l=>typeof i[i[l]]!="number"),a={};for(let l of o)a[l]=i[l];return r.objectValues(a)},r.objectValues=i=>r.objectKeys(i).map(function(o){return i[o]}),r.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},r.find=(i,o)=>{for(let a of i)if(o(a))return a},r.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(G||(G={}));var Ps;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Ps||(Ps={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ze=r=>{switch(typeof r){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(r)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(r)?R.array:r===null?R.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?R.promise:typeof Map<"u"&&r instanceof Map?R.map:typeof Set<"u"&&r instanceof Set?R.set:typeof Date<"u"&&r instanceof Date?R.date:R.object;default:return R.unknown}};var E=G.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"]),tp=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),De=class r 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 t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let a of o.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(t(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(t(a))):l[u]=l[u]||{_errors:[]},l=l[u],c++}}};return i(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,G.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];t[o]=t[o]||[],t[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};De.create=r=>new De(r);var rp=(r,e)=>{let t;switch(r.code){case E.invalid_type:r.received===R.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case E.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,G.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:t=`Unrecognized key(s) in object: ${G.joinValues(r.keys,", ")}`;break;case E.invalid_union:t="Invalid input";break;case E.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${G.joinValues(r.options)}`;break;case E.invalid_enum_value:t=`Invalid enum value. Expected ${G.joinValues(r.options)}, received '${r.received}'`;break;case E.invalid_arguments:t="Invalid function arguments";break;case E.invalid_return_type:t="Invalid function return type";break;case E.invalid_date:t="Invalid date";break;case E.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:G.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case E.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case E.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case E.custom:t="Invalid input";break;case E.invalid_intersection_types:t="Intersection results could not be merged";break;case E.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case E.not_finite:t="Number must be finite";break;default:t=e.defaultError,G.assertNever(r)}return{message:t}},rt=rp;var Sl=rt;function np(r){Sl=r}function vr(){return Sl}var rn=r=>{let{data:e,path:t,errorMaps:n,issueData:i}=r,o=[...t,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,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:o,message:l}},ip=[];function T(r,e){let t=vr(),n=rn({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===rt?void 0:rt].filter(i=>!!i)});r.common.issues.push(n)}var ce=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let i of t){if(i.status==="aborted")return L;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let i of t){let o=await i.key,a=await i.value;n.push({key:o,value:a})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let i of t){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return L;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}},L=Object.freeze({status:"aborted"}),jt=r=>({status:"dirty",value:r}),fe=r=>({status:"valid",value:r}),Jn=r=>r.status==="aborted",Yn=r=>r.status==="dirty",wt=r=>r.status==="valid",Dr=r=>typeof Promise<"u"&&r instanceof Promise;var O;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(O||(O={}));var Ae=class{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,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}},Cl=(r,e)=>{if(wt(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new De(r.common.issues);return this._error=t,this._error}}};function V(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:i}=r;if(e&&(t||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}=r;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??t??l.defaultError}},description:i}}var W=class{get description(){return this._def.description}_getType(e){return ze(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ze(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ce,ctx:{common:e.parent.common,data:e.data,parsedType:ze(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Dr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ze(e)},i=this._parseSync({data:e,path:n.path,parent:n});return Cl(n,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ze(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return wt(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>wt(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ze(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(Dr(i)?i:Promise.resolve(i));return Cl(n,o)}refine(e,t){let n=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,o)=>{let a=e(i),l=()=>o.addIssue({code:E.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(l(),!1)):a?!0:(l(),!1)})}refinement(e,t){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof t=="function"?t(n,i):t),!1))}_refinement(e){return new Re({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:t=>this["~validate"](t)}}optional(){return Te.create(this,this._def)}nullable(){return Ve.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return st.create(this)}promise(){return _t.create(this,this._def)}or(e){return qt.create([this,e],this._def)}and(e){return Vt.create(this,e,this._def)}transform(e){return new Re({...V(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ht({...V(this._def),innerType:this,defaultValue:t,typeName:F.ZodDefault})}brand(){return new nn({typeName:F.ZodBranded,type:this,...V(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Jt({...V(this._def),innerType:this,catchValue:t,typeName:F.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return sn.create(this,e)}readonly(){return Yt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},sp=/^c[^\s-]{8,}$/i,op=/^[0-9a-z]+$/,ap=/^[0-9A-HJKMNP-TV-Z]{26}$/i,lp=/^[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,cp=/^[a-z0-9_-]{21}$/i,up=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,dp=/^[-+]?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)?)??$/,fp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,hp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ts,pp=/^(?:(?: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])$/,mp=/^(?:(?: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])$/,gp=/^(([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]))$/,yp=/^(([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])$/,bp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,vp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,El="((\\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])))",Dp=new RegExp(`^${El}$`);function xl(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function wp(r){return new RegExp(`^${xl(r)}$`)}function kl(r){let e=`${El}T${xl(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Sp(r,e){return!!((e==="v4"||!e)&&pp.test(r)||(e==="v6"||!e)&&gp.test(r))}function Cp(r,e){if(!up.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.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 _p(r,e){return!!((e==="v4"||!e)&&mp.test(r)||(e==="v6"||!e)&&yp.test(r))}var St=class r extends W{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let o=this._getOrReturnCtx(e);return T(o,{code:E.invalid_type,expected:R.string,received:o.parsedType}),L}let n=new ce,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let a=e.data.length>o.value,l=e.data.length<o.value;(a||l)&&(i=this._getOrReturnCtx(e,i),a?T(i,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):l&&T(i,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")fp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"email",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Ts||(Ts=new RegExp(hp,"u")),Ts.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"emoji",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")lp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"uuid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")cp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"nanoid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")sp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cuid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")op.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cuid2",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ap.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"ulid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),T(i,{validation:"url",code:E.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"regex",code:E.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),T(i,{code:E.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),T(i,{code:E.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),T(i,{code:E.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?kl(o).test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:E.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?Dp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:E.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?wp(o).test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:E.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?dp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"duration",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Sp(e.data,o.version)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"ip",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?Cp(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"jwt",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?_p(e.data,o.version)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cidr",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?bp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"base64",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?vp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"base64url",code:E.invalid_string,message:o.message}),n.dirty()):G.assertNever(o);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(i=>e.test(i),{validation:t,code:E.invalid_string,...O.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...O.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...O.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...O.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,...O.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,...O.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...O.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...O.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errToObj(t)})}nonempty(e){return this.min(1,O.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};St.create=r=>new St({checks:[],typeName:F.ZodString,coerce:r?.coerce??!1,...V(r)});function Ep(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,o=Number.parseInt(r.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return o%a/10**i}var Bt=class r extends W{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)!==R.number){let o=this._getOrReturnCtx(e);return T(o,{code:E.invalid_type,expected:R.number,received:o.parsedType}),L}let n,i=new ce;for(let o of this._def.checks)o.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:E.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:E.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:E.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Ep(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:E.not_finite,message:o.message}),i.dirty()):G.assertNever(o);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&G.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Bt.create=r=>new Bt({checks:[],typeName:F.ZodNumber,coerce:r?.coerce||!1,...V(r)});var Lt=class r extends W{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)!==R.bigint)return this._getInvalidInput(e);let n,i=new ce;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:E.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:E.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):G.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return T(t,{code:E.invalid_type,expected:R.bigint,received:t.parsedType}),L}gte(e,t){return this.setLimit("min",e,!0,O.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:O.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Lt.create=r=>new Lt({checks:[],typeName:F.ZodBigInt,coerce:r?.coerce??!1,...V(r)});var Nt=class extends W{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:E.invalid_type,expected:R.boolean,received:n.parsedType}),L}return fe(e.data)}};Nt.create=r=>new Nt({typeName:F.ZodBoolean,coerce:r?.coerce||!1,...V(r)});var $t=class r extends W{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let o=this._getOrReturnCtx(e);return T(o,{code:E.invalid_type,expected:R.date,received:o.parsedType}),L}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return T(o,{code:E.invalid_date}),L}let n=new ce,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:E.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:E.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):G.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};$t.create=r=>new $t({checks:[],coerce:r?.coerce||!1,typeName:F.ZodDate,...V(r)});var Sr=class extends W{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:E.invalid_type,expected:R.symbol,received:n.parsedType}),L}return fe(e.data)}};Sr.create=r=>new Sr({typeName:F.ZodSymbol,...V(r)});var Ut=class extends W{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:E.invalid_type,expected:R.undefined,received:n.parsedType}),L}return fe(e.data)}};Ut.create=r=>new Ut({typeName:F.ZodUndefined,...V(r)});var zt=class extends W{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:E.invalid_type,expected:R.null,received:n.parsedType}),L}return fe(e.data)}};zt.create=r=>new zt({typeName:F.ZodNull,...V(r)});var Ct=class extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return fe(e.data)}};Ct.create=r=>new Ct({typeName:F.ZodAny,...V(r)});var it=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return fe(e.data)}};it.create=r=>new it({typeName:F.ZodUnknown,...V(r)});var Be=class extends W{_parse(e){let t=this._getOrReturnCtx(e);return T(t,{code:E.invalid_type,expected:R.never,received:t.parsedType}),L}};Be.create=r=>new Be({typeName:F.ZodNever,...V(r)});var Cr=class extends W{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:E.invalid_type,expected:R.void,received:n.parsedType}),L}return fe(e.data)}};Cr.create=r=>new Cr({typeName:F.ZodVoid,...V(r)});var st=class r extends W{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==R.array)return T(t,{code:E.invalid_type,expected:R.array,received:t.parsedType}),L;if(i.exactLength!==null){let a=t.data.length>i.exactLength.value,l=t.data.length<i.exactLength.value;(a||l)&&(T(t,{code:a?E.too_big:E.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&&t.data.length<i.minLength.value&&(T(t,{code:E.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&t.data.length>i.maxLength.value&&(T(t,{code:E.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,l)=>i.type._parseAsync(new Ae(t,a,t.path,l)))).then(a=>ce.mergeArray(n,a));let o=[...t.data].map((a,l)=>i.type._parseSync(new Ae(t,a,t.path,l)));return ce.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:O.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:O.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:O.toString(t)}})}nonempty(e){return this.min(1,e)}};st.create=(r,e)=>new st({type:r,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...V(e)});function wr(r){if(r instanceof we){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Te.create(wr(n))}return new we({...r._def,shape:()=>e})}else return r instanceof st?new st({...r._def,type:wr(r.element)}):r instanceof Te?Te.create(wr(r.unwrap())):r instanceof Ve?Ve.create(wr(r.unwrap())):r instanceof qe?qe.create(r.items.map(e=>wr(e))):r}var we=class r extends W{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(),t=G.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:E.invalid_type,expected:R.object,received:u.parsedType}),L}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),l=[];if(!(this._def.catchall instanceof Be&&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=o[u],f=i.data[u];c.push({key:{status:"valid",value:u},value:h._parse(new Ae(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Be){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:E.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 Ae(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=>ce.mergeObjectSync(n,u)):ce.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return O.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let i=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:O.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:F.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of G.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of G.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return wr(this)}partial(e){let t={};for(let n of G.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of G.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Te;)o=o._def.innerType;t[n]=o}return new r({...this._def,shape:()=>t})}keyof(){return Fl(G.objectKeys(this.shape))}};we.create=(r,e)=>new we({shape:()=>r,unknownKeys:"strip",catchall:Be.create(),typeName:F.ZodObject,...V(e)});we.strictCreate=(r,e)=>new we({shape:()=>r,unknownKeys:"strict",catchall:Be.create(),typeName:F.ZodObject,...V(e)});we.lazycreate=(r,e)=>new we({shape:r,unknownKeys:"strip",catchall:Be.create(),typeName:F.ZodObject,...V(e)});var qt=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function i(o){for(let l of o)if(l.result.status==="valid")return l.result;for(let l of o)if(l.result.status==="dirty")return t.common.issues.push(...l.ctx.common.issues),l.result;let a=o.map(l=>new De(l.ctx.common.issues));return T(t,{code:E.invalid_union,unionErrors:a}),L}if(t.common.async)return Promise.all(n.map(async o=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let c of n){let u={...t,common:{...t.common,issues:[]},parent:null},h=c._parseSync({data:t.data,path:t.path,parent:u});if(h.status==="valid")return h;h.status==="dirty"&&!o&&(o={result:h,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let l=a.map(c=>new De(c));return T(t,{code:E.invalid_union,unionErrors:l}),L}}get options(){return this._def.options}};qt.create=(r,e)=>new qt({options:r,typeName:F.ZodUnion,...V(e)});var nt=r=>r instanceof Wt?nt(r.schema):r instanceof Re?nt(r.innerType()):r instanceof Zt?[r.value]:r instanceof Gt?r.options:r instanceof Kt?G.objectValues(r.enum):r instanceof Ht?nt(r._def.innerType):r instanceof Ut?[void 0]:r instanceof zt?[null]:r instanceof Te?[void 0,...nt(r.unwrap())]:r instanceof Ve?[null,...nt(r.unwrap())]:r instanceof nn||r instanceof Yt?nt(r.unwrap()):r instanceof Jt?nt(r._def.innerType):[],Qn=class r extends W{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return T(t,{code:E.invalid_type,expected:R.object,received:t.parsedType}),L;let n=this.discriminator,i=t.data[n],o=this.optionsMap.get(i);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(T(t,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),L)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let i=new Map;for(let o of t){let a=nt(o.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,o)}}return new r({typeName:F.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...V(n)})}};function As(r,e){let t=ze(r),n=ze(e);if(r===e)return{valid:!0,data:r};if(t===R.object&&n===R.object){let i=G.objectKeys(e),o=G.objectKeys(r).filter(l=>i.indexOf(l)!==-1),a={...r,...e};for(let l of o){let c=As(r[l],e[l]);if(!c.valid)return{valid:!1};a[l]=c.data}return{valid:!0,data:a}}else if(t===R.array&&n===R.array){if(r.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<r.length;o++){let a=r[o],l=e[o],c=As(a,l);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return t===R.date&&n===R.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Vt=class extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=(o,a)=>{if(Jn(o)||Jn(a))return L;let l=As(o.value,a.value);return l.valid?((Yn(o)||Yn(a))&&t.dirty(),{status:t.value,value:l.data}):(T(n,{code:E.invalid_intersection_types}),L)};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(([o,a])=>i(o,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}))}};Vt.create=(r,e,t)=>new Vt({left:r,right:e,typeName:F.ZodIntersection,...V(t)});var qe=class r extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:E.invalid_type,expected:R.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return T(n,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let o=[...n.data].map((a,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new Ae(n,a,n.path,l)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>ce.mergeArray(t,a)):ce.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};qe.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new qe({items:r,typeName:F.ZodTuple,rest:null,...V(e)})};var Xn=class r extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:E.invalid_type,expected:R.object,received:n.parsedType}),L;let i=[],o=this._def.keyType,a=this._def.valueType;for(let l in n.data)i.push({key:o._parse(new Ae(n,l,n.path,l)),value:a._parse(new Ae(n,n.data[l],n.path,l)),alwaysSet:l in n.data});return n.common.async?ce.mergeObjectAsync(t,i):ce.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof W?new r({keyType:e,valueType:t,typeName:F.ZodRecord,...V(n)}):new r({keyType:St.create(),valueType:e,typeName:F.ZodRecord,...V(t)})}},_r=class extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:E.invalid_type,expected:R.map,received:n.parsedType}),L;let i=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([l,c],u)=>({key:i._parse(new Ae(n,l,n.path,[u,"key"])),value:o._parse(new Ae(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 L;(u.status==="dirty"||h.status==="dirty")&&t.dirty(),l.set(u.value,h.value)}return{status:t.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 L;(u.status==="dirty"||h.status==="dirty")&&t.dirty(),l.set(u.value,h.value)}return{status:t.value,value:l}}}};_r.create=(r,e,t)=>new _r({valueType:e,keyType:r,typeName:F.ZodMap,...V(t)});var Er=class r extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:E.invalid_type,expected:R.set,received:n.parsedType}),L;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(T(n,{code:E.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(T(n,{code:E.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let o=this._def.valueType;function a(c){let u=new Set;for(let h of c){if(h.status==="aborted")return L;h.status==="dirty"&&t.dirty(),u.add(h.value)}return{status:t.value,value:u}}let l=[...n.data.values()].map((c,u)=>o._parse(new Ae(n,c,n.path,u)));return n.common.async?Promise.all(l).then(c=>a(c)):a(l)}min(e,t){return new r({...this._def,minSize:{value:e,message:O.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:O.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Er.create=(r,e)=>new Er({valueType:r,minSize:null,maxSize:null,typeName:F.ZodSet,...V(e)});var ei=class r extends W{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return T(t,{code:E.invalid_type,expected:R.function,received:t.parsedType}),L;function n(l,c){return rn({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,vr(),rt].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function i(l,c){return rn({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,vr(),rt].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let o={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof _t){let l=this;return fe(async function(...c){let u=new De([]),h=await l._def.args.parseAsync(c,o).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,o).catch(p=>{throw u.addIssue(i(f,p)),u})})}else{let l=this;return fe(function(...c){let u=l._def.args.safeParse(c,o);if(!u.success)throw new De([n(c,u.error)]);let h=Reflect.apply(a,this,u.data),f=l._def.returns.safeParse(h,o);if(!f.success)throw new De([i(h,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:qe.create(e).rest(it.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||qe.create([]).rest(it.create()),returns:t||it.create(),typeName:F.ZodFunction,...V(n)})}},Wt=class extends W{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Wt.create=(r,e)=>new Wt({getter:r,typeName:F.ZodLazy,...V(e)});var Zt=class extends W{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return T(t,{received:t.data,code:E.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}};Zt.create=(r,e)=>new Zt({value:r,typeName:F.ZodLiteral,...V(e)});function Fl(r,e){return new Gt({values:r,typeName:F.ZodEnum,...V(e)})}var Gt=class r extends W{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return T(t,{expected:G.joinValues(n),received:t.parsedType,code:E.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return T(t,{received:t.data,code:E.invalid_enum_value,options:n}),L}return fe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Gt.create=Fl;var Kt=class extends W{_parse(e){let t=G.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let i=G.objectValues(t);return T(n,{expected:G.joinValues(i),received:n.parsedType,code:E.invalid_type}),L}if(this._cache||(this._cache=new Set(G.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=G.objectValues(t);return T(n,{received:n.data,code:E.invalid_enum_value,options:i}),L}return fe(e.data)}get enum(){return this._def.values}};Kt.create=(r,e)=>new Kt({values:r,typeName:F.ZodNativeEnum,...V(e)});var _t=class extends W{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.promise&&t.common.async===!1)return T(t,{code:E.invalid_type,expected:R.promise,received:t.parsedType}),L;let n=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return fe(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};_t.create=(r,e)=>new _t({type:r,typeName:F.ZodPromise,...V(e)});var Re=class extends W{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:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:a=>{T(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async l=>{if(t.value==="aborted")return L;let c=await this._def.schema._parseAsync({data:l,path:n.path,parent:n});return c.status==="aborted"?L:c.status==="dirty"?jt(c.value):t.value==="dirty"?jt(c.value):c});{if(t.value==="aborted")return L;let l=this._def.schema._parseSync({data:a,path:n.path,parent:n});return l.status==="aborted"?L:l.status==="dirty"?jt(l.value):t.value==="dirty"?jt(l.value):l}}if(i.type==="refinement"){let a=l=>{let c=i.refinement(l,o);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"?L:(l.status==="dirty"&&t.dirty(),a(l.value),{status:t.value,value:l.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(l=>l.status==="aborted"?L:(l.status==="dirty"&&t.dirty(),a(l.value).then(()=>({status:t.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(!wt(a))return L;let l=i.transform(a.value,o);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:l}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>wt(a)?Promise.resolve(i.transform(a.value,o)).then(l=>({status:t.value,value:l})):L);G.assertNever(i)}};Re.create=(r,e,t)=>new Re({schema:r,typeName:F.ZodEffects,effect:e,...V(t)});Re.createWithPreprocess=(r,e,t)=>new Re({schema:e,effect:{type:"preprocess",transform:r},typeName:F.ZodEffects,...V(t)});var Te=class extends W{_parse(e){return this._getType(e)===R.undefined?fe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Te.create=(r,e)=>new Te({innerType:r,typeName:F.ZodOptional,...V(e)});var Ve=class extends W{_parse(e){return this._getType(e)===R.null?fe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ve.create=(r,e)=>new Ve({innerType:r,typeName:F.ZodNullable,...V(e)});var Ht=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ht.create=(r,e)=>new Ht({innerType:r,typeName:F.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...V(e)});var Jt=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Dr(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new De(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new De(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Jt.create=(r,e)=>new Jt({innerType:r,typeName:F.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...V(e)});var xr=class extends W{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:E.invalid_type,expected:R.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}};xr.create=r=>new xr({typeName:F.ZodNaN,...V(r)});var xp=Symbol("zod_brand"),nn=class extends W{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},sn=class r extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?L:o.status==="dirty"?(t.dirty(),jt(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?L:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:F.ZodPipeline})}},Yt=class extends W{_parse(e){let t=this._def.innerType._parse(e),n=i=>(wt(i)&&(i.value=Object.freeze(i.value)),i);return Dr(t)?t.then(i=>n(i)):n(t)}unwrap(){return this._def.innerType}};Yt.create=(r,e)=>new Yt({innerType:r,typeName:F.ZodReadonly,...V(e)});function _l(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Pl(r,e={},t){return r?Ct.create().superRefine((n,i)=>{let o=r(n);if(o instanceof Promise)return o.then(a=>{if(!a){let l=_l(e,n),c=l.fatal??t??!0;i.addIssue({code:"custom",...l,fatal:c})}});if(!o){let a=_l(e,n),l=a.fatal??t??!0;i.addIssue({code:"custom",...a,fatal:l})}}):Ct.create()}var kp={object:we.lazycreate},F;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(F||(F={}));var Fp=(r,e={message:`Input not instance of ${r.name}`})=>Pl(t=>t instanceof r,e),Tl=St.create,Al=Bt.create,Pp=xr.create,Tp=Lt.create,Rl=Nt.create,Ap=$t.create,Rp=Sr.create,Ip=Ut.create,Op=zt.create,Mp=Ct.create,jp=it.create,Bp=Be.create,Lp=Cr.create,Np=st.create,$p=we.create,Up=we.strictCreate,zp=qt.create,qp=Qn.create,Vp=Vt.create,Wp=qe.create,Zp=Xn.create,Gp=_r.create,Kp=Er.create,Hp=ei.create,Jp=Wt.create,Yp=Zt.create,Qp=Gt.create,Xp=Kt.create,em=_t.create,tm=Re.create,rm=Te.create,nm=Ve.create,im=Re.createWithPreprocess,sm=sn.create,om=()=>Tl().optional(),am=()=>Al().optional(),lm=()=>Rl().optional(),cm={string:(r=>St.create({...r,coerce:!0})),number:(r=>Bt.create({...r,coerce:!0})),boolean:(r=>Nt.create({...r,coerce:!0})),bigint:(r=>Lt.create({...r,coerce:!0})),date:(r=>$t.create({...r,coerce:!0}))};var um=L;var Sn=Pe(require("process"),1),I=Pe(dc(),1),Xe=Pe(xu(),1);var Fu=Symbol("Let zodToJsonSchema decide on which parser to use");var ku={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"},Pu=r=>typeof r=="string"?{...ku,name:r}:{...ku,...r};var Tu=r=>{let e=Pu(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,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 mo(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function K(r,e,t,n,i){r[e]=t,mo(r,e,n,i)}var Si=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};function re(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?Si(e,r.currentPath):e.join("/")}}function Au(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==F.ZodAny&&(t.items=$(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&K(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&K(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(K(t,"minItems",r.exactLength.value,r.exactLength.message,e),K(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function Ru(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?K(t,"minimum",n.value,n.message,e):K(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),K(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?K(t,"maximum",n.value,n.message,e):K(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),K(t,"maximum",n.value,n.message,e));break;case"multipleOf":K(t,"multipleOf",n.value,n.message,e);break}return t}function Iu(){return{type:"boolean"}}function Ci(r,e){return $(r.type._def,e)}var Ou=(r,e)=>$(r.innerType._def,e);function go(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>go(r,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 py(r,e)}}var py=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":K(t,"minimum",n.value,n.message,e);break;case"max":K(t,"maximum",n.value,n.message,e);break}return t};function Mu(r,e){return{...$(r.innerType._def,e),default:r.defaultValue()}}function ju(r,e){return e.effectStrategy==="input"?$(r.schema._def,e):re(e)}function Bu(r){return{type:"string",enum:Array.from(r.values)}}var my=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Lu(r,e){let t=[$(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),$(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return t.forEach(o=>{if(my(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:l,...c}=o;a=c}else n=void 0;i.push(a)}}),i.length?{allOf:i,...n}:void 0}function Nu(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}var yo,Ne={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:()=>(yo===void 0&&(yo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),yo),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 _i(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":K(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":K(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":$e(t,"email",n.message,e);break;case"format:idn-email":$e(t,"idn-email",n.message,e);break;case"pattern:zod":me(t,Ne.email,n.message,e);break}break;case"url":$e(t,"uri",n.message,e);break;case"uuid":$e(t,"uuid",n.message,e);break;case"regex":me(t,n.regex,n.message,e);break;case"cuid":me(t,Ne.cuid,n.message,e);break;case"cuid2":me(t,Ne.cuid2,n.message,e);break;case"startsWith":me(t,RegExp(`^${bo(n.value,e)}`),n.message,e);break;case"endsWith":me(t,RegExp(`${bo(n.value,e)}$`),n.message,e);break;case"datetime":$e(t,"date-time",n.message,e);break;case"date":$e(t,"date",n.message,e);break;case"time":$e(t,"time",n.message,e);break;case"duration":$e(t,"duration",n.message,e);break;case"length":K(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),K(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{me(t,RegExp(bo(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&$e(t,"ipv4",n.message,e),n.version!=="v4"&&$e(t,"ipv6",n.message,e);break}case"base64url":me(t,Ne.base64url,n.message,e);break;case"jwt":me(t,Ne.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&me(t,Ne.ipv4Cidr,n.message,e),n.version!=="v4"&&me(t,Ne.ipv6Cidr,n.message,e);break}case"emoji":me(t,Ne.emoji(),n.message,e);break;case"ulid":{me(t,Ne.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{$e(t,"binary",n.message,e);break}case"contentEncoding:base64":{K(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{me(t,Ne.base64,n.message,e);break}}break}case"nanoid":me(t,Ne.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function bo(r,e){return e.patternStrategy==="escape"?yy(r):r}var gy=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function yy(r){let e="";for(let t=0;t<r.length;t++)gy.has(r[t])||(e+="\\"),e+=r[t];return e}function $e(r,e,t,n){r.format||r.anyOf?.some(i=>i.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):K(r,"format",e,t,n)}function me(r,e,t,n){r.pattern||r.allOf?.some(i=>i.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:$u(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):K(r,"pattern",$u(e,n),t,n)}function $u(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,i="",o=!1,a=!1,l=!1;for(let c=0;c<n.length;c++){if(o){i+=n[c],o=!1;continue}if(t.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(t.m){if(n[c]==="^"){i+=`(^|(?<=[\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
|
|
15
|
+
eDP-1 connected (normal left inverted right x axis y axis)
|
|
16
|
+
2560x1440 60.00 +
|
|
17
|
+
1920x1440 60.00
|
|
18
|
+
1856x1392 60.01
|
|
19
|
+
1792x1344 60.01
|
|
20
|
+
1920x1200 59.95
|
|
21
|
+
1920x1080 59.93
|
|
22
|
+
1600x1200 60.00
|
|
23
|
+
1680x1050 59.95 59.88
|
|
24
|
+
1600x1024 60.17
|
|
25
|
+
1400x1050 59.98
|
|
26
|
+
1280x1024 60.02
|
|
27
|
+
1440x900 59.89
|
|
28
|
+
1280x960 60.00
|
|
29
|
+
1360x768 59.80 59.96
|
|
30
|
+
1152x864 60.00
|
|
31
|
+
1024x768 60.04 60.00
|
|
32
|
+
960x720 60.00
|
|
33
|
+
928x696 60.05
|
|
34
|
+
896x672 60.01
|
|
35
|
+
960x600 60.00
|
|
36
|
+
960x540 59.99
|
|
37
|
+
800x600 60.00 60.32 56.25
|
|
38
|
+
840x525 60.01 59.88
|
|
39
|
+
800x512 60.17
|
|
40
|
+
700x525 59.98
|
|
41
|
+
640x512 60.02
|
|
42
|
+
720x450 59.89
|
|
43
|
+
640x480 60.00 59.94
|
|
44
|
+
680x384 59.80 59.96
|
|
45
|
+
576x432 60.06
|
|
46
|
+
512x384 60.00
|
|
47
|
+
400x300 60.32 56.34
|
|
48
|
+
320x240 60.05
|
|
49
|
+
DP-1 disconnected (normal left inverted right x axis y axis)
|
|
50
|
+
HDMI-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 476mm x 268mm
|
|
51
|
+
1920x1080 60.00*+ 50.00 50.00 59.94
|
|
52
|
+
1680x1050 59.88
|
|
53
|
+
1600x900 60.00
|
|
54
|
+
1280x1024 60.02
|
|
55
|
+
1440x900 59.90
|
|
56
|
+
1280x800 59.91
|
|
57
|
+
1280x720 60.00 50.00 59.94
|
|
58
|
+
1024x768 60.00
|
|
59
|
+
800x600 60.32
|
|
60
|
+
720x576 50.00
|
|
61
|
+
720x480 60.00 59.94
|
|
62
|
+
640x480 60.00 59.94
|
|
63
|
+
720x400 70.08
|
|
64
|
+
DP-2 disconnected (normal left inverted right x axis y axis)
|
|
65
|
+
HDMI-2 disconnected (normal left inverted right x axis y axis)
|
|
66
|
+
DP-2-1 connected 1920x1080+3840+0 (normal left inverted right x axis y axis) 476mm x 268mm
|
|
67
|
+
1920x1080 60.00*+ 50.00 50.00 59.94
|
|
68
|
+
1680x1050 59.88
|
|
69
|
+
1600x900 60.00
|
|
70
|
+
1280x1024 60.02
|
|
71
|
+
1440x900 59.90
|
|
72
|
+
1280x800 59.91
|
|
73
|
+
1280x720 60.00 50.00 59.94
|
|
74
|
+
1024x768 60.00
|
|
75
|
+
800x600 60.32
|
|
76
|
+
720x576 50.00
|
|
77
|
+
720x480 60.00 59.94
|
|
78
|
+
640x480 60.00 59.94
|
|
79
|
+
720x400 70.08
|
|
80
|
+
DP-2-2 connected 1920x1080+1920+0 (normal left inverted right x axis y axis) 476mm x 268mm
|
|
81
|
+
1920x1080 60.00*+ 50.00 50.00 59.94
|
|
82
|
+
1680x1050 59.88
|
|
83
|
+
1600x900 60.00
|
|
84
|
+
1280x1024 60.02
|
|
85
|
+
1440x900 59.90
|
|
86
|
+
1280x800 59.91
|
|
87
|
+
1280x720 60.00 50.00 59.94
|
|
88
|
+
1024x768 60.00
|
|
89
|
+
800x600 60.32
|
|
90
|
+
720x576 50.00
|
|
91
|
+
720x480 60.00 59.94
|
|
92
|
+
640x480 60.00 59.94
|
|
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
|
|
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_=`
|
|
99
|
+
Graphics/Displays:
|
|
100
|
+
|
|
101
|
+
Intel Iris:
|
|
102
|
+
|
|
103
|
+
Chipset Model: Intel Iris
|
|
104
|
+
Type: GPU
|
|
105
|
+
Bus: Built-In
|
|
106
|
+
VRAM (Dynamic, Max): 1536 MB
|
|
107
|
+
Vendor: Intel (0x8086)
|
|
108
|
+
Device ID: 0x0a2e
|
|
109
|
+
Revision ID: 0x0009
|
|
110
|
+
Displays:
|
|
111
|
+
Color LCD:
|
|
112
|
+
Display Type: Retina LCD
|
|
113
|
+
Resolution: 2560 x 1600 Retina
|
|
114
|
+
Retina: Yes
|
|
115
|
+
Pixel Depth: 32-Bit Color (ARGB8888)
|
|
116
|
+
Main Display: Yes
|
|
117
|
+
Mirror: Off
|
|
118
|
+
Online: Yes
|
|
119
|
+
Built-In: Yes
|
|
120
|
+
HP 22cwa:
|
|
121
|
+
Resolution: 1920 x 1080 @ 60Hz (1080p)
|
|
122
|
+
Pixel Depth: 32-Bit Color (ARGB8888)
|
|
123
|
+
Display Serial Number: 6CM7201231
|
|
124
|
+
Mirror: Off
|
|
125
|
+
Online: Yes
|
|
126
|
+
Rotation: Supported
|
|
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
|
|
129
|
+
C:\\Users\\devetry\\screenshot-desktop\\lib\\win32>// 2>nul || \r
|
|
130
|
+
\\.\\DISPLAY1;0;1920;1080;0\r
|
|
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(`
|
|
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
|
|
19
138
|
]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
|
|
20
|
-
]))`;continue}}if(
|
|
139
|
+
]))`;continue}}if(r.s&&n[c]==="."){i+=a?`${n[c]}\r
|
|
21
140
|
`:`[${n[c]}\r
|
|
22
|
-
]`;continue}i+=n[c],n[c]==="\\"?o=!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`),r.source}return i}function Ei(r,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"&&r.keyType?._def.typeName===F.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,i)=>({...n,[i]:$(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??re(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:$(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===F.ZodString&&r.keyType._def.checks?.length){let{type:n,...i}=_i(r.keyType._def,e);return{...t,propertyNames:i}}else{if(r.keyType?._def.typeName===F.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===F.ZodBranded&&r.keyType._def.type._def.typeName===F.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...i}=Ci(r.keyType._def,e);return{...t,propertyNames:i}}}return t}function Uu(r,e){if(e.mapStrategy==="record")return Ei(r,e);let t=$(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||re(e),n=$(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||re(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function zu(r){let e=r.values,n=Object.keys(r.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),i=Array.from(new Set(n.map(o=>typeof o)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function qu(r){return r.target==="openAi"?void 0:{not:re({...r,currentPath:[...r.currentPath,"not"]})}}function Vu(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var yn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Zu(r,e){if(e.target==="openApi3")return Wu(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in yn&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((i,o)=>{let a=yn[o._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((i,o)=>{let a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...i,a];case"bigint":return[...i,"integer"];case"object":if(o._def.value===null)return[...i,"null"];default:return i}},[]);if(n.length===t.length){let i=n.filter((o,a,l)=>l.indexOf(o)===a);return{type:i.length>1?i:i[0],enum:t.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,i)=>[...n,...i._def.values.filter(o=>!n.includes(o))],[])};return Wu(r,e)}var Wu=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,i)=>$(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function Gu(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:yn[r.innerType._def.typeName],nullable:!0}:{type:[yn[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=$(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=$(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Ku(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",mo(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?K(t,"minimum",n.value,n.message,e):K(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),K(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?K(t,"maximum",n.value,n.message,e):K(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),K(t,"maximum",n.value,n.message,e));break;case"multipleOf":K(t,"multipleOf",n.value,n.message,e);break}return t}function Hu(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},i=[],o=r.shape();for(let l in o){let c=o[l];if(c===void 0||c._def===void 0)continue;let u=vy(c);u&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let h=$(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=by(r,e);return a!==void 0&&(n.additionalProperties=a),n}function by(r,e){if(r.catchall._def.typeName!=="ZodNever")return $(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function vy(r){try{return r.isOptional()}catch{return!0}}var Ju=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return $(r.innerType._def,e);let t=$(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:re(e)},t]}:re(e)};var Yu=(r,e)=>{if(e.pipeStrategy==="input")return $(r.in._def,e);if(e.pipeStrategy==="output")return $(r.out._def,e);let t=$(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=$(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(i=>i!==void 0)}};function Qu(r,e){return $(r.type._def,e)}function Xu(r,e){let n={type:"array",uniqueItems:!0,items:$(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&K(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&K(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function ed(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>$(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:$(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>$(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function td(r){return{not:re(r)}}function rd(r){return re(r)}var nd=(r,e)=>$(r.innerType._def,e);var id=(r,e,t)=>{switch(e){case F.ZodString:return _i(r,t);case F.ZodNumber:return Ku(r,t);case F.ZodObject:return Hu(r,t);case F.ZodBigInt:return Ru(r,t);case F.ZodBoolean:return Iu();case F.ZodDate:return go(r,t);case F.ZodUndefined:return td(t);case F.ZodNull:return Vu(t);case F.ZodArray:return Au(r,t);case F.ZodUnion:case F.ZodDiscriminatedUnion:return Zu(r,t);case F.ZodIntersection:return Lu(r,t);case F.ZodTuple:return ed(r,t);case F.ZodRecord:return Ei(r,t);case F.ZodLiteral:return Nu(r,t);case F.ZodEnum:return Bu(r);case F.ZodNativeEnum:return zu(r);case F.ZodNullable:return Gu(r,t);case F.ZodOptional:return Ju(r,t);case F.ZodMap:return Uu(r,t);case F.ZodSet:return Xu(r,t);case F.ZodLazy:return()=>r.getter()._def;case F.ZodPromise:return Qu(r,t);case F.ZodNaN:case F.ZodNever:return qu(t);case F.ZodEffects:return ju(r,t);case F.ZodAny:return re(t);case F.ZodUnknown:return rd(t);case F.ZodDefault:return Mu(r,t);case F.ZodBranded:return Ci(r,t);case F.ZodReadonly:return nd(r,t);case F.ZodCatch:return Ou(r,t);case F.ZodPipeline:return Yu(r,t);case F.ZodFunction:case F.ZodVoid:case F.ZodSymbol:return;default:return(n=>{})(e)}};function $(r,e,t=!1){let n=e.seen.get(r);if(e.override){let l=e.override?.(r,e,n,t);if(l!==Fu)return l}if(n&&!t){let l=Dy(n,e);if(l!==void 0)return l}let i={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,i);let o=id(r,r.typeName,e),a=typeof o=="function"?$(o(),e):o;if(a&&wy(r,e,a),e.postProcess){let l=e.postProcess(a,r,e);return i.jsonSchema=a,l}return i.jsonSchema=a,a}var Dy=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:Si(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),re(e)):e.$refStrategy==="seen"?re(e):void 0}},wy=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var xi=(r,e)=>{let t=Tu(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,h])=>({...c,[u]:$(h._def,{...t,currentPath:[...t.basePath,t.definitionPath,u]},!0)??re(t)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=$(r._def,i===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,i]},!1)??re(t),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let l=i===void 0?n?{...o,[t.definitionPath]:n}:o:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,i].join("/"),[t.definitionPath]:{...n,[i]:o}};return t.target==="jsonSchema7"?l.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(l.$schema="https://json-schema.org/draft/2019-09/schema#"),t.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 Sy(r){return typeof r=="object"&&r!==null&&typeof r.get=="function"&&typeof r.subscribe=="function"}var Tt=class{subscribeWithCleaner(e,t){let n=this.subscribe(t);e.register(n)}subscribeOnce(e){let t=this.subscribe(n=>{t(),e(n)});return t}subscribeOnceWithCleaner(e,t){let n=this.subscribeOnce(t);e.register(n)}derive(e,t=(n,i)=>n===i){if(Sy(this))return Ue.deriveFrom([this],e);let n=this;if(n.get!==void 0){if(n.get()===Ue.NOT_AVAILABLE)return Ue.createWithoutInitialValue(a=>n.subscribe(l=>{ht(l)&&a(e(l))}));let o=n;return Ue.create(e(o.get()),a=>o.subscribe(l=>{a(e(l))}),t)}return Ue.createWithoutInitialValue(i=>this.subscribe(o=>{ht(o)&&i(e(o))}),t)}},Cn=class r extends Tt{constructor(){super(),this.subscribers=new Set,this.onSubscribed=null,this.onUnsubscribed=null}emit(e){queueMicrotask(()=>{for(let t of this.subscribers)t(e)})}static create(){let e=new r;return[e,n=>{e.emit(n)}]}subscribe(e){let t=this.subscribers.size;return this.subscribers.add(e),t===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:t=1e3}){let[n,i]=r.create();return n.onSubscribed=()=>{let o=[],a=null,l=0,c=()=>{a=null,i(o),o=[]};n.onUnsubscribed=this.subscribe(u=>{if(o.push(u),a===null)l=Date.now(),a=setTimeout(c,Math.min(e,t));else{clearTimeout(a);let h=Date.now()-l;a=setTimeout(c,Math.min(e,Math.max(0,t-h)))}})},n}};function ee(){let r,e;return{promise:new Promise((n,i)=>{r=n,e=i}),resolve:r,reject:e}}var Wa=Symbol.for("immer-nothing"),vn=Symbol.for("immer-draftable"),Y=Symbol.for("immer-state"),Kd=process.env.NODE_ENV!=="production"?[function(r){return`The plugin for '${r}' has not been loaded into Immer. To enable the plugin, import and call \`enable${r}()\` when initializing your application.`},function(r){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 '${r}'`},"This object has been frozen and should not be mutated",function(r){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+r},"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(r){return`'current' expects a draft, got: ${r}`},"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(r){return`'original' expects a draft, got: ${r}`}]:[];function ie(r,...e){if(process.env.NODE_ENV!=="production"){let t=Kd[r],n=typeof t=="function"?t.apply(null,e):t;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${r}. Full error at: https://bit.ly/3cXEKWf`)}var fr=Object.getPrototypeOf;function hr(r){return!!r&&!!r[Y]}function et(r){return r?Hd(r)||Array.isArray(r)||!!r[vn]||!!r.constructor?.[vn]||$n(r)||Un(r):!1}var Cy=Object.prototype.constructor.toString();function Hd(r){if(!r||typeof r!="object")return!1;let e=fr(r);if(e===null)return!0;let t=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return t===Object?!0:typeof t=="function"&&Function.toString.call(t)===Cy}function Gr(r,e){pr(r)===0?Reflect.ownKeys(r).forEach(t=>{e(t,r[t],r)}):r.forEach((t,n)=>e(n,t,r))}function pr(r){let e=r[Y];return e?e.type_:Array.isArray(r)?1:$n(r)?2:Un(r)?3:0}function _n(r,e){return pr(r)===2?r.has(e):Object.prototype.hasOwnProperty.call(r,e)}function vo(r,e){return pr(r)===2?r.get(e):r[e]}function Jd(r,e,t){let n=pr(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function _y(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}function $n(r){return r instanceof Map}function Un(r){return r instanceof Set}function ae(r){return r.copy_||r.base_}function Lo(r,e){if($n(r))return new Map(r);if(Un(r))return new Set(r);if(Array.isArray(r))return Array.prototype.slice.call(r);let t=Hd(r);if(e===!0||e==="class_only"&&!t){let n=Object.getOwnPropertyDescriptors(r);delete n[Y];let i=Reflect.ownKeys(n);for(let o=0;o<i.length;o++){let a=i[o],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:r[a]})}return Object.create(fr(r),n)}else{let n=fr(r);if(n!==null&&t)return{...r};let i=Object.create(n);return Object.assign(i,r)}}function Za(r,e=!1){return us(r)||hr(r)||!et(r)||(pr(r)>1&&(r.set=r.add=r.clear=r.delete=Ey),Object.freeze(r),e&&Object.values(r).forEach(t=>Za(t,!0))),r}function Ey(){ie(2)}function us(r){return Object.isFrozen(r)}var No={};function mr(r){let e=No[r];return e||ie(0,r),e}function Yd(r,e){No[r]||(No[r]=e)}var En;function Ui(){return En}function xy(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function sd(r,e){e&&(mr("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function $o(r){Uo(r),r.drafts_.forEach(ky),r.drafts_=null}function Uo(r){r===En&&(En=r.parent_)}function od(r){return En=xy(En,r)}function ky(r){let e=r[Y];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function ad(r,e){e.unfinalizedDrafts_=e.drafts_.length;let t=e.drafts_[0];return r!==void 0&&r!==t?(t[Y].modified_&&($o(e),ie(4)),et(r)&&(r=zi(e,r),e.parent_||qi(e,r)),e.patches_&&mr("Patches").generateReplacementPatches_(t[Y].base_,r,e.patches_,e.inversePatches_)):r=zi(e,t,[]),$o(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==Wa?r:void 0}function zi(r,e,t){if(us(e))return e;let n=e[Y];if(!n)return Gr(e,(i,o)=>ld(r,n,e,i,o,t)),e;if(n.scope_!==r)return e;if(!n.modified_)return qi(r,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let i=n.copy_,o=i,a=!1;n.type_===3&&(o=new Set(i),i.clear(),a=!0),Gr(o,(l,c)=>ld(r,n,i,l,c,t,a)),qi(r,i,!1),t&&r.patches_&&mr("Patches").generatePatches_(n,t,r.patches_,r.inversePatches_)}return n.copy_}function ld(r,e,t,n,i,o,a){if(process.env.NODE_ENV!=="production"&&i===t&&ie(5),hr(i)){let l=o&&e&&e.type_!==3&&!_n(e.assigned_,n)?o.concat(n):void 0,c=zi(r,i,l);if(Jd(t,n,c),hr(c))r.canAutoFreeze_=!1;else return}else a&&t.add(i);if(et(i)&&!us(i)){if(!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1)return;zi(r,i),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(t,n)&&qi(r,i)}}function qi(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&Za(e,t)}function Fy(r,e){let t=Array.isArray(r),n={type_:t?1:0,scope_:e?e.scope_:Ui(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1},i=n,o=Ga;t&&(i=[n],o=xn);let{revoke:a,proxy:l}=Proxy.revocable(i,o);return n.draft_=l,n.revoke_=a,l}var Ga={get(r,e){if(e===Y)return r;let t=ae(r);if(!_n(t,e))return Py(r,t,e);let n=t[e];return r.finalized_||!et(n)?n:n===Do(r.base_,e)?(wo(r),r.copy_[e]=kn(n,r)):n},has(r,e){return e in ae(r)},ownKeys(r){return Reflect.ownKeys(ae(r))},set(r,e,t){let n=Qd(ae(r),e);if(n?.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){let i=Do(ae(r),e),o=i?.[Y];if(o&&o.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(_y(t,i)&&(t!==void 0||_n(r.base_,e)))return!0;wo(r),ft(r)}return r.copy_[e]===t&&(t!==void 0||e in r.copy_)||Number.isNaN(t)&&Number.isNaN(r.copy_[e])||(r.copy_[e]=t,r.assigned_[e]=!0),!0},deleteProperty(r,e){return Do(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,wo(r),ft(r)):delete r.assigned_[e],r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){let t=ae(r),n=Reflect.getOwnPropertyDescriptor(t,e);return n&&{writable:!0,configurable:r.type_!==1||e!=="length",enumerable:n.enumerable,value:t[e]}},defineProperty(){ie(11)},getPrototypeOf(r){return fr(r.base_)},setPrototypeOf(){ie(12)}},xn={};Gr(Ga,(r,e)=>{xn[r]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});xn.deleteProperty=function(r,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&ie(13),xn.set.call(this,r,e,void 0)};xn.set=function(r,e,t){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&ie(14),Ga.set.call(this,r[0],e,t,r[0])};function Do(r,e){let t=r[Y];return(t?ae(t):r)[e]}function Py(r,e,t){let n=Qd(e,t);return n?"value"in n?n.value:n.get?.call(r.draft_):void 0}function Qd(r,e){if(!(e in r))return;let t=fr(r);for(;t;){let n=Object.getOwnPropertyDescriptor(t,e);if(n)return n;t=fr(t)}}function ft(r){r.modified_||(r.modified_=!0,r.parent_&&ft(r.parent_))}function wo(r){r.copy_||(r.copy_=Lo(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var Ty=class{constructor(r){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,n)=>{if(typeof e=="function"&&typeof t!="function"){let o=t;t=e;let a=this;return function(c=o,...u){return a.produce(c,h=>t.call(this,h,...u))}}typeof t!="function"&&ie(6),n!==void 0&&typeof n!="function"&&ie(7);let i;if(et(e)){let o=od(this),a=kn(e,void 0),l=!0;try{i=t(a),l=!1}finally{l?$o(o):Uo(o)}return sd(o,n),ad(i,o)}else if(!e||typeof e!="object"){if(i=t(e),i===void 0&&(i=e),i===Wa&&(i=void 0),this.autoFreeze_&&Za(i,!0),n){let o=[],a=[];mr("Patches").generateReplacementPatches_(e,i,o,a),n(o,a)}return i}else ie(1,e)},this.produceWithPatches=(e,t)=>{if(typeof e=="function")return(a,...l)=>this.produceWithPatches(a,c=>e(c,...l));let n,i;return[this.produce(e,t,(a,l)=>{n=a,i=l}),n,i]},typeof r?.autoFreeze=="boolean"&&this.setAutoFreeze(r.autoFreeze),typeof r?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(r.useStrictShallowCopy)}createDraft(r){et(r)||ie(8),hr(r)&&(r=Ay(r));let e=od(this),t=kn(r,void 0);return t[Y].isManual_=!0,Uo(e),t}finishDraft(r,e){let t=r&&r[Y];(!t||!t.isManual_)&&ie(9);let{scope_:n}=t;return sd(n,e),ad(void 0,n)}setAutoFreeze(r){this.autoFreeze_=r}setUseStrictShallowCopy(r){this.useStrictShallowCopy_=r}applyPatches(r,e){let t;for(t=e.length-1;t>=0;t--){let i=e[t];if(i.path.length===0&&i.op==="replace"){r=i.value;break}}t>-1&&(e=e.slice(t+1));let n=mr("Patches").applyPatches_;return hr(r)?n(r,e):this.produce(r,i=>n(i,e))}};function kn(r,e){let t=$n(r)?mr("MapSet").proxyMap_(r,e):Un(r)?mr("MapSet").proxySet_(r,e):Fy(r,e);return(e?e.scope_:Ui()).drafts_.push(t),t}function Ay(r){return hr(r)||ie(10,r),Xd(r)}function Xd(r){if(!et(r)||us(r))return r;let e=r[Y],t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=Lo(r,e.scope_.immer_.useStrictShallowCopy_)}else t=Lo(r,!0);return Gr(t,(n,i)=>{Jd(t,n,Xd(i))}),e&&(e.finalized_=!1),t}function Ry(){class r extends Map{constructor(c,u){super(),this[Y]={type_:2,parent_:u,scope_:u?u.scope_:Ui(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return ae(this[Y]).size}has(c){return ae(this[Y]).has(c)}set(c,u){let h=this[Y];return a(h),(!ae(h).has(c)||ae(h).get(c)!==u)&&(t(h),ft(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[Y];return a(u),t(u),ft(u),u.base_.has(c)?u.assigned_.set(c,!1):u.assigned_.delete(c),u.copy_.delete(c),!0}clear(){let c=this[Y];a(c),ae(c).size&&(t(c),ft(c),c.assigned_=new Map,Gr(c.base_,u=>{c.assigned_.set(u,!1)}),c.copy_.clear())}forEach(c,u){let h=this[Y];ae(h).forEach((f,d,p)=>{c.call(u,this.get(d),d,this)})}get(c){let u=this[Y];a(u);let h=ae(u).get(c);if(u.finalized_||!et(h)||h!==u.base_.get(c))return h;let f=kn(h,u);return t(u),u.copy_.set(c,f),f}keys(){return ae(this[Y]).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 r(l,c)}function t(l){l.copy_||(l.assigned_=new Map,l.copy_=new Map(l.base_))}class n extends Set{constructor(c,u){super(),this[Y]={type_:3,parent_:u,scope_:u?u.scope_:Ui(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return ae(this[Y]).size}has(c){let u=this[Y];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[Y];return a(u),this.has(c)||(o(u),ft(u),u.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let u=this[Y];return a(u),o(u),ft(u),u.copy_.delete(c)||(u.drafts_.has(c)?u.copy_.delete(u.drafts_.get(c)):!1)}clear(){let c=this[Y];a(c),ae(c).size&&(o(c),ft(c),c.copy_.clear())}values(){let c=this[Y];return a(c),o(c),c.copy_.values()}entries(){let c=this[Y];return a(c),o(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 o(l){l.copy_||(l.copy_=new Set,l.base_.forEach(c=>{if(et(c)){let u=kn(c,l);l.drafts_.set(c,u),l.copy_.add(u)}else l.copy_.add(c)}))}function a(l){l.revoked_&&ie(3,JSON.stringify(ae(l)))}Yd("MapSet",{proxyMap_:e,proxySet_:i})}function Iy(){process.env.NODE_ENV!=="production"&&Kd.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",t="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 o(d,p,m,g);case 3:return l(d,p,m,g)}}function o(d,p,m,g){let{base_:b,assigned_:y}=d,D=d.copy_;D.length<b.length&&([b,D]=[D,b],[m,g]=[g,m]);for(let v=0;v<b.length;v++)if(y[v]&&D[v]!==b[v]){let S=p.concat([v]);m.push({op:e,path:S,value:f(D[v])}),g.push({op:e,path:S,value:f(b[v])})}for(let v=b.length;v<D.length;v++){let S=p.concat([v]);m.push({op:t,path:S,value:f(D[v])})}for(let v=D.length-1;b.length<=v;--v){let S=p.concat([v]);g.push({op:n,path:S})}}function a(d,p,m,g){let{base_:b,copy_:y}=d;Gr(d.assigned_,(D,v)=>{let S=vo(b,D),_=vo(y,D),k=v?_n(b,D)?e:t:n;if(S===_&&k===e)return;let x=p.concat(D);m.push(k===n?{op:k,path:x}:{op:k,path:x,value:_}),g.push(k===t?{op:n,path:x}:k===n?{op:t,path:x,value:f(S)}:{op:e,path:x,value:f(S)})})}function l(d,p,m,g){let{base_:b,copy_:y}=d,D=0;b.forEach(v=>{if(!y.has(v)){let S=p.concat([D]);m.push({op:n,path:S,value:v}),g.unshift({op:t,path:S,value:v})}D++}),D=0,y.forEach(v=>{if(!b.has(v)){let S=p.concat([D]);m.push({op:t,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===Wa?void 0:p}),g.push({op:e,path:[],value:d})}function u(d,p){return p.forEach(m=>{let{path:g,op:b}=m,y=d;for(let _=0;_<g.length-1;_++){let k=pr(y),x=g[_];typeof x!="string"&&typeof x!="number"&&(x=""+x),(k===0||k===1)&&(x==="__proto__"||x==="constructor")&&ie(19),typeof y=="function"&&x==="prototype"&&ie(19),y=vo(y,x),typeof y!="object"&&ie(18,g.join("/"))}let D=pr(y),v=h(m.value),S=g[g.length-1];switch(b){case e:switch(D){case 2:return y.set(S,v);case 3:ie(16);default:return y[S]=v}case t:switch(D){case 1:return S==="-"?y.push(v):y.splice(S,0,v);case 2:return y.set(S,v);case 3:return y.add(v);default:return y[S]=v}case n:switch(D){case 1:return y.splice(S,1);case 2:return y.delete(S);case 3:return y.delete(m.value);default:return delete y[S]}default:ie(17,b)}}),d}function h(d){if(!et(d))return d;if(Array.isArray(d))return d.map(h);if($n(d))return new Map(Array.from(d.entries()).map(([m,g])=>[m,h(g)]));if(Un(d))return new Set(Array.from(d).map(h));let p=Object.create(fr(d));for(let m in d)p[m]=h(d[m]);return _n(d,vn)&&(p[vn]=d[vn]),p}function f(d){return hr(d)?h(d):d}Yd("Patches",{applyPatches_:u,generatePatches_:i,generateReplacementPatches_:c})}var ke=new Ty;ke.produce;var Oy=ke.produceWithPatches.bind(ke);ke.setAutoFreeze.bind(ke);ke.setUseStrictShallowCopy.bind(ke);var zo=ke.applyPatches.bind(ke);ke.createDraft.bind(ke);ke.finishDraft.bind(ke);Ry();Iy();function $r(...r){return r.filter(e=>e!==void 0).reduce((e,t)=>e.concat(t),[])}function cd(r){return[{op:"replace",path:[],value:r}]}function Ka(r,e){let t=(n,i)=>{r(()=>[n,cd(n)],$r(e?.(),i))};return t.withProducer=(n,i)=>{r(o=>{let[a,l]=Oy(o,n);if(ht(a))return[a,l];throw new Error("Cannot update value to NOT_AVAILABLE")},$r(e?.(),i))},t.withUpdater=(n,i)=>{r(o=>{let a=n(o);return[a,cd(a)]},$r(e?.(),i))},t.withPatchUpdater=(n,i)=>{r(n,$r(e?.(),i))},t.withPatches=(n,i)=>{r(o=>[zo(o,n),n],$r(e?.(),i))},t.withValueAndPatches=(n,i,o)=>{r(()=>[n,i],$r(e?.(),o))},t}var My=(r,e)=>r===e,Fn=class r extends Tt{static create(e,t=My){let n=new r(e,t),o=Ka((a,l)=>{n.update(a,l)});return[n,o]}static createReadonly(e){return r.create(e)[0]}constructor(e,t){super(),this.value=e,this.equalsPredicate=t,this.subscribers=new Set,this.queuedUpdaters=[],this.isEmitting=!1}get(){return this.value}pull(){return this.value}notifyFull(e,t,n){for(let{type:i,callback:o}of this.subscribers)i==="full"&&o(e,t,n)}notifyAll(e,t,n){for(let{type:i,callback:o}of this.subscribers)i==="regular"?o(e):o(e,t,n)}notifyAndUpdateIfChanged(e,t,n){this.equalsPredicate(this.value,e)?n.length>0&&this.notifyFull(e,t,n):(this.value=e,this.notifyAll(e,t,n))}isReplaceRoot(e){return e.path.length===0&&e.op==="replace"}update(e,t){if(this.queuedUpdaters.push([e,t]),!this.isEmitting){this.isEmitting=!0;try{for(;this.queuedUpdaters.length>0;){let n=this.value,i=[],o=[];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&&o.push(...l)}this.notifyAndUpdateIfChanged(n,i,o)}}finally{this.isEmitting=!1}}}subscribe(e){let t={type:"regular",callback:e};return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}subscribeAndNow(e){let t=this.subscribe(e);return e(this.value),t}subscribeFull(e){let t={type:"full",callback:e};return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}async until(e){let t=this.get();if(e(t))return t;let{promise:n,resolve:i}=ee(),o=this.subscribe(a=>{e(a)&&(i(a),o())});return await n}};function ht(r){return r!==Ue.NOT_AVAILABLE}var Ue=class r extends Tt{static{this.NOT_AVAILABLE=Symbol("notAvailable")}static create(e,t,n=(i,o)=>i===o){return new r(e,t,n)}static createWithoutInitialValue(e,t=(n,i)=>n===i){let n=(i,o)=>i===r.NOT_AVAILABLE||o===r.NOT_AVAILABLE?i===o:t(i,o);return new r(r.NOT_AVAILABLE,e,n)}static deriveFrom(e,t,n){let i;n!==void 0&&(i=(a,l)=>a===r.NOT_AVAILABLE||l===r.NOT_AVAILABLE?a===l:n(a,l));let o=()=>{let a=e.map(l=>l.get());return a.some(l=>l===r.NOT_AVAILABLE)?r.NOT_AVAILABLE:t(...a)};return new r(o(),a=>{let l=e.map(u=>u.subscribe(()=>{let h=o();ht(h)&&a(h)})),c=o();return ht(c)&&a(c),()=>{l.forEach(u=>u())}},i)}static asyncDeriveFrom(e,t,n,i){let o;i!==void 0&&(o=(c,u)=>c===r.NOT_AVAILABLE||u===r.NOT_AVAILABLE?c===u:i(c,u));let a=-1,l=-1;return new r(r.NOT_AVAILABLE,c=>{let u=()=>{l++;let f=l,d=t.map(p=>p.get());d.some(p=>p===r.NOT_AVAILABLE)||n(...d).then(p=>{if(ht(p))if(e==="eager")f>a&&(a=f,c(p));else{let m=e;throw new Error(`Unknown strategy: ${m}`)}})},h=t.map(f=>f.subscribe(()=>{u()}));return u(),()=>{h.forEach(f=>f())}},o)}constructor(e,t,n=(i,o)=>i===o){super(),this.subscribeUpstream=t,this.dataIsStale=!0,this.upstreamUnsubscribe=null,this.subscribersCount=0,this.isSubscribedToUpstream=!1,this.updateReceivedSynchronousCallbacks=new Set,[this.signal,this.setValue]=Fn.create(e,n),[this.updateReceivedEvent,this.emitUpdateReceivedEvent]=Cn.create()}isStale(){return this.dataIsStale}subscribeToUpstream(){this.isSubscribedToUpstream=!0;let e=!0,t=!1,n=this.subscribeUpstream(Ka((i,o)=>{if(e){this.setValue.withPatchUpdater(i,o),this.dataIsStale=t,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,t=!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:t}=ee();if(!this.isStale())t(this.get());else{let n=this.subscribe(()=>{});this.updateReceivedEvent.subscribeOnce(()=>{t(this.get())}),e.then(n)}return e}runOnNextFreshData(e){if(!this.isStale())e(this.get());else{let t=null,n=()=>{this.updateReceivedSynchronousCallbacks.delete(n),e(this.get()),t?.()};this.updateReceivedSynchronousCallbacks.add(n),t=this.subscribe(()=>{})}}async ensureAvailable(){return await this.pull(),this}subscribe(e){this.isSubscribedToUpstream||this.subscribeToUpstream(),this.subscribersCount++;let t=this.signal.subscribe(e),n=!1;return()=>{n||(t(),n=!0,this.subscribersCount--,this.subscribersCount===0&&this.isSubscribedToUpstream&&this.unsubscribeFromUpstream())}}subscribeFull(e){this.isSubscribedToUpstream||this.subscribeToUpstream(),this.subscribersCount++;let t=this.signal.subscribeFull(e),n=!1;return()=>{n||(t(),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 t=this.get();if(ht(t)&&e(t))return t;let{promise:n,resolve:i}=ee(),o=this.subscribe(a=>{ht(a)&&e(a)&&(i(a),o())});return await n}},jy=[41343,52993,16141,39414,22931],bn=Symbol(),mt=class r extends Tt{static create(){let e=new r;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)!==bn&&this.queued.push(bn),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===bn?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=[bn,...this.queued.filter(t=>t!==bn)],this.notifier()),()=>{this.subscriber=null}}flow(){let[e,t]=Cn.create();return this.subscribe(t),e}},qo=class extends Tt{constructor(){super(...arguments),this.canceled=!1,this.listeners=new Set}subscribe(e){if(this.canceled){let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!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}},Vi=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(r=0){let e=new Error().stack;return e?e.split(`
|
|
23
|
-
`).slice(2+
|
|
24
|
-
`):""}function
|
|
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(`
|
|
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(`
|
|
25
144
|
at `)).trimEnd()+`
|
|
26
|
-
`+e).trimEnd()}var Wi=class{constructor(e=0){this.nextId=e}next(){let e=this.nextId;return this.nextId++,e}};function By(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var ki={exports:{}},Fi={exports:{}},Co,ud;function Ly(){return ud||(ud=1,Co=({onlyFirst:r=!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,r?void 0:"g")}),Co}var _o,dd;function ef(){if(dd)return _o;dd=1;let r=Ly();return _o=e=>typeof e=="string"?e.replace(r(),""):e,_o}var Pi={exports:{}},fd;function Ny(){if(fd)return Pi.exports;fd=1;let r=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 Pi.exports=r,Pi.exports.default=r,Pi.exports}var Eo,hd;function $y(){return hd||(hd=1,Eo=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}),Eo}var pd;function ds(){if(pd)return Fi.exports;pd=1;let r=ef(),e=Ny(),t=$y(),n=i=>{if(typeof i!="string"||i.length===0||(i=r(i),i.length===0))return 0;i=i.replace(t()," ");let o=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++,o+=e(l)?2:1)}return o};return Fi.exports=n,Fi.exports.default=n,Fi.exports}var Ti={exports:{}},md;function Uy(){if(md)return Ti.exports;md=1;let r=ds(),e=t=>{let n=0;for(let i of t.split(`
|
|
27
|
-
`))n=Math.max(n,
|
|
28
|
-
`,c=o.pad||" ",u=a!=="right"?t: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=r(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(o){return e(o,{align:"left"})},e.center=function(o){return e(o,{align:"center"})},e.right=function(o){return e(o,{align:"right"})},xo=e;function t(i,o){return Math.floor((i-o)/2)}function n(i,o){return i-o}return xo}var Bi={exports:{}},ko,vd;function Xy(){return vd||(vd=1,ko={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]}),ko}var Fo,Dd;function tf(){if(Dd)return Fo;Dd=1;let r=Xy(),e={};for(let i of Object.keys(r))e[r[i]]=i;let t={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"]}};Fo=t;for(let i of Object.keys(t)){if(!("channels"in t[i]))throw new Error("missing channels property: "+i);if(!("labels"in t[i]))throw new Error("missing channel labels property: "+i);if(t[i].labels.length!==t[i].channels)throw new Error("channel and label counts mismatch: "+i);let{channels:o,labels:a}=t[i];delete t[i].channels,delete t[i].labels,Object.defineProperty(t[i],"channels",{value:o}),Object.defineProperty(t[i],"labels",{value:a})}t.rgb.hsl=function(i){let o=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.min(o,a,l),u=Math.max(o,a,l),h=u-c,f,d;u===c?f=0:o===u?f=(a-l)/h:a===u?f=2+(l-o)/h:l===u&&(f=4+(o-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]},t.rgb.hsv=function(i){let o,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(b){return(p-b)/6/m+1/2};return m===0?(c=0,u=0):(u=m/p,o=g(h),a=g(f),l=g(d),h===p?c=l-a:f===p?c=1/3+o-l:d===p&&(c=2/3+a-o),c<0?c+=1:c>1&&(c-=1)),[c*360,u*100,p*100]},t.rgb.hwb=function(i){let o=i[0],a=i[1],l=i[2],c=t.rgb.hsl(i)[0],u=1/255*Math.min(o,Math.min(a,l));return l=1-1/255*Math.max(o,Math.max(a,l)),[c,u*100,l*100]},t.rgb.cmyk=function(i){let o=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.min(1-o,1-a,1-l),u=(1-o-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,o){return(i[0]-o[0])**2+(i[1]-o[1])**2+(i[2]-o[2])**2}return t.rgb.keyword=function(i){let o=e[i];if(o)return o;let a=1/0,l;for(let c of Object.keys(r)){let u=r[c],h=n(i,u);h<a&&(a=h,l=c)}return l},t.keyword.rgb=function(i){return r[i]},t.rgb.xyz=function(i){let o=i[0]/255,a=i[1]/255,l=i[2]/255;o=o>.04045?((o+.055)/1.055)**2.4:o/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=o*.4124+a*.3576+l*.1805,u=o*.2126+a*.7152+l*.0722,h=o*.0193+a*.1192+l*.9505;return[c*100,u*100,h*100]},t.rgb.lab=function(i){let o=t.rgb.xyz(i),a=o[0],l=o[1],c=o[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]},t.hsl.rgb=function(i){let o=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=o+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},t.hsl.hsv=function(i){let o=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[o,f*100,h*100]},t.hsv.rgb=function(i){let o=i[0]/60,a=i[1]/100,l=i[2]/100,c=Math.floor(o)%6,u=o-Math.floor(o),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]}},t.hsv.hsl=function(i){let o=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,[o,u*100,h*100]},t.hwb.rgb=function(i){let o=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*o),f=1-l;u=6*o-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]},t.cmyk.rgb=function(i){let o=i[0]/100,a=i[1]/100,l=i[2]/100,c=i[3]/100,u=1-Math.min(1,o*(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]},t.xyz.rgb=function(i){let o=i[0]/100,a=i[1]/100,l=i[2]/100,c,u,h;return c=o*3.2406+a*-1.5372+l*-.4986,u=o*-.9689+a*1.8758+l*.0415,h=o*.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]},t.xyz.lab=function(i){let o=i[0],a=i[1],l=i[2];o/=95.047,a/=100,l/=108.883,o=o>.008856?o**(1/3):7.787*o+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*(o-a),h=200*(a-l);return[c,u,h]},t.lab.xyz=function(i){let o=i[0],a=i[1],l=i[2],c,u,h;u=(o+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]},t.lab.lch=function(i){let o=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[o,h,c]},t.lch.lab=function(i){let o=i[0],a=i[1],c=i[2]/360*2*Math.PI,u=a*Math.cos(c),h=a*Math.sin(c);return[o,u,h]},t.rgb.ansi16=function(i,o=null){let[a,l,c]=i,u=o===null?t.rgb.hsv(i)[2]:o;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},t.hsv.ansi16=function(i){return t.rgb.ansi16(t.hsv.rgb(i),i[2])},t.rgb.ansi256=function(i){let o=i[0],a=i[1],l=i[2];return o===a&&a===l?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(a/255*5)+Math.round(l/255*5)},t.ansi16.rgb=function(i){let o=i%10;if(o===0||o===7)return i>50&&(o+=3.5),o=o/10.5*255,[o,o,o];let a=(~~(i>50)+1)*.5,l=(o&1)*a*255,c=(o>>1&1)*a*255,u=(o>>2&1)*a*255;return[l,c,u]},t.ansi256.rgb=function(i){if(i>=232){let u=(i-232)*10+8;return[u,u,u]}i-=16;let o,a=Math.floor(i/36)/5*255,l=Math.floor((o=i%36)/6)/5*255,c=o%6/5*255;return[a,l,c]},t.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},t.hex.rgb=function(i){let o=i.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!o)return[0,0,0];let a=o[0];o[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]},t.rgb.hcg=function(i){let o=i[0]/255,a=i[1]/255,l=i[2]/255,c=Math.max(Math.max(o,a),l),u=Math.min(Math.min(o,a),l),h=c-u,f,d;return h<1?f=u/(1-h):f=0,h<=0?d=0:c===o?d=(a-l)/h%6:c===a?d=2+(l-o)/h:d=4+(o-a)/h,d/=6,d%=1,[d*360,h*100,f*100]},t.hsl.hcg=function(i){let o=i[1]/100,a=i[2]/100,l=a<.5?2*o*a:2*o*(1-a),c=0;return l<1&&(c=(a-.5*l)/(1-l)),[i[0],l*100,c*100]},t.hsv.hcg=function(i){let o=i[1]/100,a=i[2]/100,l=o*a,c=0;return l<1&&(c=(a-l)/(1-l)),[i[0],l*100,c*100]},t.hcg.rgb=function(i){let o=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=o%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]},t.hcg.hsv=function(i){let o=i[1]/100,a=i[2]/100,l=o+a*(1-o),c=0;return l>0&&(c=o/l),[i[0],c*100,l*100]},t.hcg.hsl=function(i){let o=i[1]/100,l=i[2]/100*(1-o)+.5*o,c=0;return l>0&&l<.5?c=o/(2*l):l>=.5&&l<1&&(c=o/(2*(1-l))),[i[0],c*100,l*100]},t.hcg.hwb=function(i){let o=i[1]/100,a=i[2]/100,l=o+a*(1-o);return[i[0],(l-o)*100,(1-l)*100]},t.hwb.hcg=function(i){let o=i[1]/100,l=1-i[2]/100,c=l-o,u=0;return c<1&&(u=(l-c)/(1-c)),[i[0],c*100,u*100]},t.apple.rgb=function(i){return[i[0]/65535*255,i[1]/65535*255,i[2]/65535*255]},t.rgb.apple=function(i){return[i[0]/255*65535,i[1]/255*65535,i[2]/255*65535]},t.gray.rgb=function(i){return[i[0]/100*255,i[0]/100*255,i[0]/100*255]},t.gray.hsl=function(i){return[0,0,i[0]]},t.gray.hsv=t.gray.hsl,t.gray.hwb=function(i){return[0,100,i[0]]},t.gray.cmyk=function(i){return[0,0,0,i[0]]},t.gray.lab=function(i){return[i[0],0,0]},t.gray.hex=function(i){let o=Math.round(i[0]/100*255)&255,l=((o<<16)+(o<<8)+o).toString(16).toUpperCase();return"000000".substring(l.length)+l},t.rgb.gray=function(i){return[(i[0]+i[1]+i[2])/3/255*100]},Fo}var Po,wd;function eb(){if(wd)return Po;wd=1;let r=tf();function e(){let o={},a=Object.keys(r);for(let l=a.length,c=0;c<l;c++)o[a[c]]={distance:-1,parent:null};return o}function t(o){let a=e(),l=[o];for(a[o].distance=0;l.length;){let c=l.pop(),u=Object.keys(r[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(o,a){return function(l){return a(o(l))}}function i(o,a){let l=[a[o].parent,o],c=r[a[o].parent][o],u=a[o].parent;for(;a[u].parent;)l.unshift(a[u].parent),c=n(r[a[u].parent][u],c),u=a[u].parent;return c.conversion=l,c}return Po=function(o){let a=t(o),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},Po}var To,Sd;function tb(){if(Sd)return To;Sd=1;let r=tf(),e=eb(),t={},n=Object.keys(r);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 o(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=>{t[a]={},Object.defineProperty(t[a],"channels",{value:r[a].channels}),Object.defineProperty(t[a],"labels",{value:r[a].labels});let l=e(a);Object.keys(l).forEach(u=>{let h=l[u];t[a][u]=o(h),t[a][u].raw=i(h)})}),To=t,To}Bi.exports;var Cd;function rb(){return Cd||(Cd=1,(function(r){let e=(h,f)=>(...d)=>`\x1B[${h(...d)+f}m`,t=(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,o=(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=tb());let m=p?10:0,g={};for(let[b,y]of Object.entries(l)){let D=b==="ansi16"?"ansi":b;b===f?g[D]=h(d,m):typeof y=="object"&&(g[D]=h(y[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(t,"ansi256",i,!1)),a(f.color,"ansi16m",()=>c(n,"rgb",o,!1)),a(f.bgColor,"ansi",()=>c(e,"ansi16",i,!0)),a(f.bgColor,"ansi256",()=>c(t,"ansi256",i,!0)),a(f.bgColor,"ansi16m",()=>c(n,"rgb",o,!0)),f}Object.defineProperty(r,"exports",{enumerable:!0,get:u})})(Bi)),Bi.exports}var Ao,_d;function nb(){if(_d)return Ao;_d=1;let r=ds(),e=ef(),t=rb(),n=new Set(["\x1B","\x9B"]),i=39,o="\x07",a="[",l="]",c="m",u=`${l}8;;`,h=b=>`${n.values().next().value}${a}${b}${c}`,f=b=>`${n.values().next().value}${u}${b}${o}`,d=b=>b.split(" ").map(y=>r(y)),p=(b,y,D)=>{let v=[...y],S=!1,_=!1,k=r(e(b[b.length-1]));for(let[x,z]of v.entries()){let w=r(z);if(k+w<=D?b[b.length-1]+=z:(b.push(z),k=0),n.has(z)&&(S=!0,_=v.slice(x+1).join("").startsWith(u)),S){_?z===o&&(S=!1,_=!1):z===c&&(S=!1);continue}k+=w,k===D&&x<v.length-1&&(b.push(""),k=0)}!k&&b[b.length-1].length>0&&b.length>1&&(b[b.length-2]+=b.pop())},m=b=>{let y=b.split(" "),D=y.length;for(;D>0&&!(r(y[D-1])>0);)D--;return D===y.length?b:y.slice(0,D).join(" ")+y.slice(D).join("")},g=(b,y,D={})=>{if(D.trim!==!1&&b.trim()==="")return"";let v="",S,_,k=d(b),x=[""];for(let[w,C]of b.split(" ").entries()){D.trim!==!1&&(x[x.length-1]=x[x.length-1].trimStart());let P=r(x[x.length-1]);if(w!==0&&(P>=y&&(D.wordWrap===!1||D.trim===!1)&&(x.push(""),P=0),(P>0||D.trim===!1)&&(x[x.length-1]+=" ",P++)),D.hard&&k[w]>y){let U=y-P,Z=1+Math.floor((k[w]-U-1)/y);Math.floor((k[w]-1)/y)<Z&&x.push(""),p(x,C,y);continue}if(P+k[w]>y&&P>0&&k[w]>0){if(D.wordWrap===!1&&P<y){p(x,C,y);continue}x.push("")}if(P+k[w]>y&&D.wordWrap===!1){p(x,C,y);continue}x[x.length-1]+=C}D.trim!==!1&&(x=x.map(m));let z=[...x.join(`
|
|
29
|
-
`)];for(let[w,
|
|
30
|
-
`?(
|
|
31
|
-
`&&(S&&P&&(v+=h(S)),
|
|
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(`
|
|
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
|
+
`?(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,`
|
|
32
151
|
`).split(`
|
|
33
|
-
`).map(v=>g(v,
|
|
34
|
-
`),
|
|
35
|
-
`,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
|
|
36
|
-
`),
|
|
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=`
|
|
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)+`
|
|
37
156
|
|
|
38
|
-
`+e,
|
|
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+=`
|
|
39
158
|
|
|
40
159
|
|
|
41
160
|
`+I.default.bgWhite.black(" </> STACK TRACE ")+`
|
|
42
161
|
|
|
43
|
-
`+I.default.gray(e));let
|
|
44
|
-
`+
|
|
45
|
-
`,i+1))!==-1;)
|
|
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]+=`
|
|
46
165
|
|
|
47
|
-
`+r
|
|
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`
|
|
48
167
|
Cannot modify immutable ${this.getClassName()} instance. Use asMutableCopy() to get a
|
|
49
168
|
mutable copy.
|
|
50
|
-
`)}};var Vo=class r extends Tt{static{this.NOT_AVAILABLE=Ue.NOT_AVAILABLE}applyOptimisticUpdates(e){for(let t of this.queuedUpdates)[e]=t.updater(e);return e}updateOptimisticValue(e){let t=this.innerSignal.get();ht(t)&&this.setOuterSignal(this.applyOptimisticUpdates(t),e)}constructor(e,t,n,i){super(),this.writeUpstream=n,this.isWriteLoopRunning=!1,this.isSubscriptionHandledByWriteLoop=!1,this.queuedUpdates=[],this.currentEnsureAvailablePromise=null,[this.writeErrorEvent,this.emitWriteErrorEvent]=Cn.create(),[this.outerSignal,this.setOuterSignal]=Fn.create(e,i),this.innerSignal=Ue.create(e,t,i),this.innerSignal.passiveSubscribeFull((o,a,l)=>{this.isSubscriptionHandledByWriteLoop||this.updateOptimisticValue(l)})}static create(e,t,n,i=(o,a)=>o===a){let o=new r(e,t,n,i),a=Ka(o.update.bind(o));return[o,a,(c,u)=>o.emitWriteErrorEvent({tags:c,error:u})]}static createWithoutInitialValue(e,t,n=(i,o)=>i===o){let i=(o,a)=>o===r.NOT_AVAILABLE||a===r.NOT_AVAILABLE?o===a:n(o,a);return r.create(r.NOT_AVAILABLE,e,t,i)}async update(e,t){let{promise:n,reject:i,resolve:o}=ee();return this.queuedUpdates.push({updater:e,tags:t??[],resolve:o,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 t=this.queuedUpdates.length,n=c=>{let u=[];for(let h=0;h<t;h++){let[f,d]=this.queuedUpdates[h].updater(c);c=f,u.push(...d)}return[c,u]},i=()=>{for(let c=0;c<t;c++)this.queuedUpdates[c].resolve()},o=c=>{for(let u=0;u<t;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,t),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(),o(p),this.queuedUpdates.splice(0,t))})),this.writeUpstream(...n(this.innerSignal.get()),[l,...a])||(h(),i(),this.queuedUpdates.splice(0,t),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 t=this.outerSignal.subscribe(e),n=this.innerSignal.subscribe(()=>{});return()=>{t(),n()}}subscribeFull(e){let t=this.outerSignal.subscribeFull(e),n=this.innerSignal.subscribeFull(()=>{});return()=>{t(),n()}}};function Sb(r){r.includes(":")||(r=`local:${r}`);let e=r.indexOf(":"),t=r.slice(0,e),n=r.slice(e+1);switch(t){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: ${t}.`)}}function Cb(r){return new Promise((e,t)=>{if(r.aborted){t(r.reason);return}r.addEventListener("abort",()=>{t(r.reason)},{once:!0})})}function _b(r,e){return Promise.race([r,Cb(e)])}var Eb=["HSA_OVERRIDE_GFX_VERSION"],xb=s.enum(Eb),kb=s.record(xb,s.string()),Fb=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Pn=s.string().regex(Fb),Pb=/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/,Tn=s.string().regex(Pb),Tb=/^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])$/u,kd=s.string().regex(Tb,{message:"Invalid file name"}),Ab=/^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])(?:\/[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ]))*$/u;s.string().regex(Ab,{message:"Invalid relative path"});var Rb=s.object({type:s.literal("huggingface"),user:kd,repo:kd}),rf=s.discriminatedUnion("type",[Rb]),Ib=s.enum(["baseModel","draftModel","custom"]),nf=s.object({purpose:Ib}),Ob=s.object({type:s.literal("model"),...nf.shape,modelKeys:s.array(s.string().min(1)),sources:s.array(rf)}),Mb=s.object({type:s.literal("artifact"),...nf.shape,owner:Pn,name:Tn}),jb=s.discriminatedUnion("type",[Ob,Mb]),Ha=s.object({owner:Pn,name:Tn.min(1,"Name is required").max(100,"Name too long"),revision:s.number().int().optional(),dependencies:s.array(jb).optional(),tags:s.array(s.string()).optional()}),Bb=/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:[-.][a-z0-9]+)*$/,Lb=s.string().regex(Bb,{message:"Invalid artifact identifier format. Expected 'owner/name'."}),Nb=s.object({type:s.literal("model"),...Ha.shape}),$b=s.enum(["ecmascript","node","mcpBridge"]),Ja=s.object({type:s.literal("plugin"),runner:$b,...Ha.shape}),Ub=s.object({type:s.literal("preset"),...Ha.shape});s.discriminatedUnion("type",[Ja,Ub,Nb]);var zb=s.enum(["plugin","preset","model"]),sf=s.object({title:s.string(),description:s.string().optional(),noAutoDismiss:s.boolean().optional()}),of=s.enum(["image","text/plain","application/pdf","application/word","text/other","unknown"]),Ce=s.any().transform((r,e)=>{try{return JSON.parse(JSON.stringify(r))}catch(t){return e.addIssue({code:s.ZodIssueCode.custom,message:"Not JSON serializable: "+t.message}),r}}),Li=s.object({type:s.literal("text"),text:s.string()}),Ni=s.object({type:s.literal("file"),name:s.string(),identifier:s.string(),sizeBytes:s.number().int(),fileType:of}),qb=s.object({id:s.string().optional(),type:s.literal("function"),arguments:s.record(Ce).optional(),name:s.string()}),An=s.discriminatedUnion("type",[qb]),af=s.object({type:s.literal("toolCallRequest"),toolCallRequest:An});s.object({content:s.string(),toolCallId:s.string().optional()});var lf=s.object({type:s.literal("toolCallResult"),content:s.string(),toolCallId:s.string().optional()});s.discriminatedUnion("type",[Li,Ni,af,lf]);s.enum(["assistant","user","system","tool"]);var ur=s.discriminatedUnion("role",[s.object({role:s.literal("assistant"),content:s.array(s.discriminatedUnion("type",[Li,Ni,af]))}),s.object({role:s.literal("user"),content:s.array(s.discriminatedUnion("type",[Li,Ni]))}),s.object({role:s.literal("system"),content:s.array(s.discriminatedUnion("type",[Li,Ni]))}),s.object({role:s.literal("tool"),content:s.array(lf)})]),dr=s.object({messages:s.array(ur)}),Vb=s.object({fileName:s.string(),absoluteFilePath:s.string().optional(),pageNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional(),lineNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional()}),Wb=s.enum(["red","green","blue","yellow","orange","purple","default"]),Zb=Wb,Gb=s.discriminatedUnion("type",[s.object({type:s.literal("llm.prediction.input"),modelPath:s.string(),modelIdentifier:s.string(),input:s.string()})]),Kb=s.object({timestamp:s.number(),data:Gb}),cf=s.union([s.number().min(0).max(1),s.literal("max"),s.literal("off")]),Hb=s.enum(["evenly","favorMainGpu"]),uf=s.object({ratio:cf.optional(),mainGpu:s.number().int().optional(),splitStrategy:Hb.optional(),disabledGpus:s.array(s.number().int()).optional()}),Wo=["f32","f16","q8_0","q4_0","q4_1","iq4_nl","q5_0","q5_1"],Jb=s.enum(Wo),Yb=s.union([s.literal(8),s.literal(6),s.literal(4),s.literal(3),s.literal(2)]),Qb=s.union([s.literal(32),s.literal(64),s.literal(128)]),Xb=s.object({enabled:s.boolean(),bits:Yb,groupSize:Qb,quantizedStart:s.number().int().nonnegative()}),e0=s.object({gpu:uf.optional(),gpuStrictVramCap:s.boolean().optional(),offloadKVCacheToGpu:s.boolean().optional(),contextLength:s.number().int().min(1).optional(),ropeFrequencyBase:s.number().optional(),ropeFrequencyScale:s.number().optional(),evalBatchSize:s.number().int().min(1).optional(),flashAttention:s.boolean().optional(),keepModelInMemory:s.boolean().optional(),seed:s.number().int().optional(),useFp16ForKVCache:s.boolean().optional(),tryMmap:s.boolean().optional(),numExperts:s.number().int().optional(),llamaKCacheQuantizationType:s.enum(Wo).or(s.literal(!1)).optional(),llamaVCacheQuantizationType:s.enum(Wo).or(s.literal(!1)).optional()}),t0=s.object({gpu:uf.optional(),contextLength:s.number().int().min(1).optional(),ropeFrequencyBase:s.number().optional(),ropeFrequencyScale:s.number().optional(),keepModelInMemory:s.boolean().optional(),tryMmap:s.boolean().optional()}),fs=s.enum(["gguf","safetensors","onnx","ggml","mlx_placeholder","torch_safetensors"]),r0=s.object({name:s.string(),bits:s.number().int()}),Ya=s.object({modelKey:s.string(),format:fs,displayName:s.string(),path:s.string(),sizeBytes:s.number().int(),paramsString:s.string().optional(),architecture:s.string().optional(),quantization:r0.optional()}),df=Ya.extend({identifier:s.string(),instanceReference:s.string()}),ff=s.object({maxContextLength:s.number().int()}),n0=s.object({contextLength:s.number().int()}),hf=s.object({type:s.literal("embedding")}).extend(Ya.shape).extend(ff.shape),pf=s.object({type:s.literal("embedding")}).extend(df.shape).extend(ff.shape).extend(n0.shape),Rn=s.enum(["llm","embedding","imageGen","transcription","tts"]),Vr=s.string().min(1).max(1024).refine(r=>r!=="__proto__",{message:'For security reasons, "__proto__" is not allowed'}).refine(r=>/\p{C}/u.test(r)===!1,{message:"Control characters are not allowed"}),Qa=s.object({domain:Rn.optional(),identifier:Vr.optional(),path:Vr.optional(),vision:s.boolean().optional()}),Ye=s.discriminatedUnion("type",[s.object({type:s.literal("query"),query:Qa}),s.object({type:s.literal("instanceReference"),instanceReference:s.string()})]),i0=[s.object({code:s.literal("generic.specificModelUnloaded")}),s.object({code:s.literal("generic.noModelMatchingQuery"),query:Qa,loadedModelsSample:s.array(s.string()),totalLoadedModels:s.number().int()}),s.object({code:s.literal("generic.pathNotFound"),path:s.string(),availablePathsSample:s.array(s.string()),totalModels:s.number().int()}),s.object({code:s.literal("generic.identifierNotFound"),identifier:s.string(),loadedModelsSample:s.array(s.string()),totalLoadedModels:s.number().int()}),s.object({code:s.literal("generic.domainMismatch"),path:s.string(),actualDomain:Rn,expectedDomain:Rn}),s.object({code:s.literal("generic.engineDoesNotSupportFeature"),feature:s.string(),engineName:s.string(),engineType:s.string(),installedVersion:s.string(),supportedVersion:s.string().nullable()}),s.object({code:s.literal("generic.presetNotFound"),specifiedFuzzyPresetIdentifier:s.string(),availablePresetsSample:s.array(s.object({identifier:s.string(),name:s.string()})),totalAvailablePresets:s.number().int()})],s0=[],o0=s.discriminatedUnion("code",[...s0,...i0]);function nr(r){return s.any().transform(e=>r.safeParse(e).success?e:void 0)}var xe=s.object({title:nr(s.string()).default("Unknown error"),cause:nr(s.string()).optional(),suggestion:nr(s.string()).optional(),errorData:nr(s.record(s.string(),s.unknown())).optional(),displayData:nr(o0).optional(),stack:nr(s.string()).optional(),rootTitle:nr(s.string()).optional()});function sr(r){if(typeof r=="object"){let e=r.title??r.lmstudioRawError??r.message??"Unknown error";return xe.parse({title:e,cause:r.cause,suggestion:r.suggestion,errorData:r.errorData,displayData:r.displayData,stack:r.stack,rootTitle:e})}else{let e=String(r);return{title:e,rootTitle:e}}}function mf(r,e){let t=r;t.title=e.title,e.cause!==void 0&&(t.cause=e.cause),e.suggestion!==void 0&&(t.suggestion=e.suggestion),e.errorData!==void 0&&(t.errorData=e.errorData)}function Gi(r,e="Rehydrated error",t){let n=new Error(r.rootTitle);return mf(n,r),r.displayData!==void 0&&(n.displayData=r.displayData),t!==void 0?r.stack!==void 0?n.stack=`Error: ${e}
|
|
51
|
-
${
|
|
52
|
-
- Caused By: ${
|
|
53
|
-
${
|
|
54
|
-
${n.stack.substring(
|
|
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}
|
|
170
|
+
${r}
|
|
171
|
+
- Caused By: ${t.stack}`:n.stack=`Error: ${e}
|
|
172
|
+
${r}`:t.stack!==void 0?n.stack=`Error: ${e}
|
|
173
|
+
${n.stack.substring(t.stack.indexOf(`
|
|
55
174
|
`)+1)}
|
|
56
|
-
- Caused By: `+r.stack:n.message+=` - caused by error without stack (${r.title})`,n}var Zo=s.object({library:s.string(),version:s.string()}),gf=s.object({parserId:Zo.optional()});s.enum(["local","base64"]);s.discriminatedUnion("type",[s.object({type:s.literal("local"),fileName:s.string()}),s.object({type:s.literal("base64"),base64Data:s.string()})]);var a0=["evenly","priorityOrder","custom"],l0=s.enum(a0),c0={strategy:"evenly",disabledGpus:[],priority:[],customRatio:[]},u0=s.object({strategy:l0,disabledGpus:s.array(s.number().int().min(0)),priority:s.array(s.number().int().min(0)),customRatio:s.array(s.number().min(0))});function yf(r){return{strategy:r?.splitStrategy=="favorMainGpu"?"priorityOrder":r?.splitStrategy??"evenly",disabledGpus:r?.disabledGpus??[],priority:r?.mainGpu?[r.mainGpu]:[],customRatio:[]}}var bf=s.object({key:s.string(),value:s.any()}),X=s.object({fields:s.array(bf)}),d0=s.enum(["currentlyEditing","currentlyLoaded","apiOverride","conversationSpecific","conversationGlobal","preset","serverSession","httpServerRequestOverride","completeModeFormatting","instance","userModelDefault","virtualModel","modelDefault","hardware"]),f0=s.object({layerName:d0,config:X}),Ki=s.object({layers:s.array(f0)}),h0=s.object({key:s.string(),condition:s.discriminatedUnion("type",[s.object({type:s.literal("equals"),value:s.any()}),s.object({type:s.literal("notEquals"),value:s.any()})])}),vf=s.discriminatedUnion("type",[s.object({type:s.literal("default")}),s.object({type:s.literal("customLabel"),label:s.string(),color:s.optional(Zb)}),s.object({type:s.literal("thinking"),ended:s.boolean().optional(),title:s.string().optional()})]),p0=s.discriminatedUnion("type",[s.object({type:s.literal("object"),properties:s.record(Ce),required:s.array(s.string()).optional(),additionalProperties:s.boolean().optional(),$defs:s.record(Ce).optional()})]),ar=s.discriminatedUnion("type",[s.object({type:s.literal("function"),function:s.object({name:s.string(),description:s.string().optional(),parameters:p0.optional()})})]);s.array(ar);var Df=s.discriminatedUnion("type",[s.object({type:s.literal("none")}),s.object({type:s.literal("toolArray"),tools:s.array(ar).optional(),force:s.boolean().optional()})]),wf=s.object({omitBosToken:s.boolean().optional(),omitEosToken:s.boolean().optional(),toolDefinitions:s.array(ar).optional()}),m0=s.discriminatedUnion("type",[s.object({type:s.literal("jsonFile"),absPath:s.string()}),s.object({type:s.literal("yamlFile"),absPath:s.string()})]);s.array(s.object({role:s.enum(["user","assistant","system"]),content:s.string()}));s.array(s.union([s.object({system:s.string()}),s.object({user:s.string()}),s.object({assistant:s.string()})]));var Sf=s.object({vision:s.boolean(),trainedForToolUse:s.boolean(),maxContextLength:s.number().int()}),g0=s.object({contextLength:s.number().int()}),Cf=s.object({type:s.literal("llm")}).extend(Ya.shape).extend(Sf.shape),Go=s.object({type:s.literal("llm")}).extend(df.shape).extend(Sf.shape).extend(g0.shape),_f=s.enum(["passThrough","removeSpecial","snakeCase","camelCase"]),yr=s.custom(r=>typeof r?.parse=="function","Expected a zod schema"),y0=s.object({beforeSystem:s.string(),afterSystem:s.string(),beforeUser:s.string(),afterUser:s.string(),beforeAssistant:s.string(),afterAssistant:s.string()}),b0=s.object({template:s.string()}),v0=s.enum(["manual","jinja"]),Ef=s.object({type:v0,manualPromptTemplate:y0.optional(),jinjaPromptTemplate:b0.optional(),stopStrings:s.array(s.string())}),D0=s.enum(["none","json","gbnf"]),Xa=s.object({type:D0,jsonSchema:Ce.optional(),gbnfGrammar:s.string().optional()}),xf=s.enum(["stopAtLimit","truncateMiddle","rollingWindow"]),kf=s.object({enabled:s.boolean(),startString:s.string(),endString:s.string()}),el=s.object({maxTokens:s.number().int().min(-1).optional().or(s.literal(!1)),temperature:s.number().min(0).optional(),stopStrings:s.array(s.string()).optional(),toolCallStopStrings:s.array(s.string()).optional(),contextOverflowPolicy:xf.optional(),structured:s.union([yr,Xa]).optional(),rawTools:Df.optional(),toolNaming:_f.optional(),topKSampling:s.number().optional(),repeatPenalty:s.number().optional().or(s.literal(!1)),minPSampling:s.number().optional().or(s.literal(!1)),topPSampling:s.number().optional().or(s.literal(!1)),cpuThreads:s.number().int().optional(),promptTemplate:Ef.optional(),draftModel:s.string().optional(),speculativeDecodingNumDraftTokensExact:s.number().int().min(1).optional(),speculativeDecodingMinDraftLengthToConsider:s.number().int().min(0).optional(),speculativeDecodingMinContinueDraftingProbability:s.number().optional(),reasoningParsing:kf.optional(),raw:X.optional()});s.object({...el.shape,structured:Xa.optional()});var w0=s.object({version:s.union([s.literal(0),s.literal(1),s.literal(2)]),learningRate:s.number(),targetEntropy:s.number()}),S0=s.union([s.number(),s.literal("-inf")]),C0=s.array(s.tuple([s.number(),S0])),Ff=s.enum(["none","reasoning","reasoningStartTag","reasoningEndTag"]),Pf=s.object({content:s.string(),tokensCount:s.number().int(),containsDrafted:s.boolean(),reasoningType:Ff,isStructural:s.boolean()}),Tf=s.object({tokenCount:s.number().int().optional(),containsDrafted:s.boolean().optional(),reasoningType:Ff.optional(),isStructural:s.boolean().optional()}),_0=s.enum(["userStopped","modelUnloaded","failed","eosFound","stopStringFound","toolCalls","maxPredictedTokensReached","contextLengthReached"]),Af=s.object({stopReason:_0,tokensPerSecond:s.number().optional(),numGpuLayers:s.number().optional(),timeToFirstTokenSec:s.number().optional(),totalTimeSec:s.number().optional(),promptTokensCount:s.number().int().optional(),predictedTokensCount:s.number().int().optional(),totalTokensCount:s.number().int().optional(),usedDraftModelKey:s.string().optional(),totalDraftTokensCount:s.number().int().optional(),acceptedDraftTokensCount:s.number().int().optional(),rejectedDraftTokensCount:s.number().int().optional(),ignoredDraftTokensCount:s.number().int().optional()}),E0=s.object({indexedModelIdentifier:s.string(),identifier:s.string(),loadModelConfig:X,predictionConfig:X,stats:Af}),x0=s.discriminatedUnion("type",[s.object({type:s.literal("beforeId"),id:s.string()}),s.object({type:s.literal("afterId"),id:s.string()})]),k0=s.enum(["waiting","loading","done","error","canceled"]),Rf=s.object({status:k0,text:s.string()}),tl=s.object({type:s.literal("status.create"),id:s.string(),state:Rf,location:x0.optional(),indentation:s.number().int().optional()}),rl=s.object({type:s.literal("status.update"),id:s.string(),state:Rf}),nl=s.object({type:s.literal("status.remove"),id:s.string()}),il=s.object({type:s.literal("citationBlock.create"),id:s.string(),citedText:s.string(),fileName:s.string(),fileIdentifier:s.string(),pageNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional(),lineNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional()}),sl=s.object({type:s.literal("debugInfoBlock.create"),id:s.string(),debugInfo:s.string()}),If=s.object({type:s.literal("contentBlock.create"),id:s.string(),includeInContext:s.boolean(),roleOverride:s.enum(["user","assistant","system","tool"]).optional(),style:vf.optional(),prefix:s.string().optional(),suffix:s.string().optional()}),Of=s.object({type:s.literal("contentBlock.appendText"),id:s.string(),text:s.string(),tokensCount:s.number().int().optional(),fromDraftModel:s.boolean().optional(),isStructural:s.boolean().optional()}),Mf=s.object({type:s.literal("contentBlock.appendToolResult"),id:s.string(),callId:s.number().int(),toolCallRequestId:s.string().optional(),content:s.string()}),jf=s.object({type:s.literal("contentBlock.appendToolRequest"),id:s.string(),callId:s.number().int(),toolCallRequestId:s.string().optional(),name:s.string(),parameters:s.record(s.unknown()),pluginIdentifier:s.string().optional()}),Bf=s.object({type:s.literal("contentBlock.replaceToolRequest"),id:s.string(),callId:s.number().int(),toolCallRequestId:s.string().optional(),name:s.string(),parameters:s.record(s.unknown()),pluginIdentifier:s.string().optional()}),Lf=s.object({type:s.literal("contentBlock.replaceText"),id:s.string(),text:s.string()}),F0=s.object({type:s.literal("contentBlock.setPrefix"),id:s.string(),prefix:s.string()}),P0=s.object({type:s.literal("contentBlock.setSuffix"),id:s.string(),suffix:s.string()}),Nf=s.object({type:s.literal("contentBlock.attachGenInfo"),id:s.string(),genInfo:E0}),$f=s.object({type:s.literal("contentBlock.setStyle"),id:s.string(),style:vf}),T0=s.discriminatedUnion("type",[s.object({type:s.literal("generatingToolCall"),name:s.string().optional(),pluginIdentifier:s.string().optional(),argumentsString:s.string().optional()}),s.object({type:s.literal("toolCallGenerationFailed"),error:s.string(),rawContent:s.string().optional()}),s.object({type:s.literal("toolCallQueued")}),s.object({type:s.literal("confirmingToolCall")}),s.object({type:s.literal("toolCallDenied"),denyReason:s.string().optional()}),s.object({type:s.literal("callingTool")}),s.object({type:s.literal("toolCallFailed"),error:s.string()}),s.object({type:s.literal("toolCallSucceeded"),timeMs:s.number().int()})]),Uf=s.object({status:T0,customStatus:s.string(),customWarnings:s.array(s.string())}),zf=s.object({type:s.literal("toolStatus.create"),id:s.string(),callId:s.number().int(),state:Uf}),qf=s.object({type:s.literal("toolStatus.update"),id:s.string(),state:Uf}),Vf=s.object({type:s.literal("toolStatus.argumentFragment"),id:s.string(),content:s.string()}),Wf=s.object({type:s.literal("setSenderName"),name:s.string()}),A0=s.discriminatedUnion("type",[tl,rl,nl,il,sl,If,Of,jf,Bf,Mf,Lf,F0,P0,Nf,$f,zf,qf,Vf,Wf]);s.discriminatedUnion("type",[tl,rl,nl,il,sl,If,Of,Lf,jf,Bf,Mf,Nf,$f,zf,qf,Vf,Wf]);var R0=s.object({type:s.literal("confirmToolCall"),callId:s.number().int(),pluginIdentifier:s.string().optional(),name:s.string(),parameters:s.record(s.any())}),I0=s.object({type:s.literal("textInput"),prompt:s.string()}),O0=s.discriminatedUnion("type",[R0,I0]),M0=s.object({type:s.literal("confirmToolCall"),result:s.discriminatedUnion("type",[s.object({type:s.literal("allow"),toolArgsOverride:s.record(s.any()).optional()}),s.object({type:s.literal("deny"),denyReason:s.string().optional()})])}),j0=s.object({type:s.literal("textInput"),result:s.string()}),B0=s.discriminatedUnion("type",[M0,j0]);s.object({modelTag:s.string().optional(),ignoreUserConfig:s.boolean().optional()});s.discriminatedUnion("type",[tl,rl,nl,il,sl]);var L0=s.discriminatedUnion("type",[s.object({type:s.literal("model"),identifier:s.string()}),s.object({type:s.literal("generator"),pluginIdentifier:s.string()})]),N0=s.discriminatedUnion("type",[Cf,hf]),$0=s.discriminatedUnion("type",[Go,pf]),Fd=s.discriminatedUnion("type",[s.object({type:s.literal("direct"),config:X,workingDirectoryPath:s.string().optional()}),s.object({type:s.literal("predictionProcess"),pci:s.string(),token:s.string()})]),Pd=s.object({identifier:s.string(),isDev:s.boolean(),isTrusted:s.boolean(),hasPromptPreprocessor:s.boolean(),hasPredictionLoopHandler:s.boolean(),hasToolsProvider:s.boolean(),hasGenerator:s.boolean()}),Td=s.object({displayName:s.string(),sizeBytes:s.number(),quantName:s.string().optional(),compatibilityType:fs}),Ad=s.enum(["pending","fetching","satisfied","completed"]),U0=s.discriminatedUnion("type",[s.object({type:s.literal("artifact"),owner:Pn,name:Tn,state:Ad,artifactType:zb.optional(),sizeBytes:s.number().int().optional(),dependencyNodes:s.array(s.number().int())}),s.object({type:s.literal("model"),state:Ad,resolvedSources:s.number().int().optional(),totalSources:s.number().int().optional(),alreadyOwned:Td.optional(),selected:Td.optional()})]),Rd=s.object({nodes:s.array(U0),downloadSizeBytes:s.number().int()}),z0=s.object({relativePath:s.string(),sizeBytes:s.number().int()}),q0=s.object({files:s.array(z0),usedIgnoreFile:s.string().nullable()}),Ro=s.object({downloadedBytes:s.number().int(),totalBytes:s.number().int(),speedBytesPerSecond:s.number()}),V0=s.enum(["fullGPUOffload","partialGPUOffload","fitWithoutGPU","willNotFit"]),W0=s.object({quantization:s.string().optional(),name:s.string(),sizeBytes:s.number().int(),fitEstimation:V0,recommended:s.boolean().optional(),downloadIdentifier:s.string(),indexedModelIdentifier:s.string()}),Zf=s.discriminatedUnion("type",[s.object({type:s.literal("catalog"),identifier:s.string()}),s.object({type:s.literal("hf"),identifier:s.string()})]),Z0=s.object({name:s.string(),identifier:Zf,exact:s.boolean().optional(),staffPick:s.boolean().optional()}),Gf=s.object({searchTerm:s.string().optional(),limit:s.number().int().positive().max(25).optional(),compatibilityTypes:s.array(fs).optional()}),G0=s.object({content:s.string(),score:s.number(),sourceIndex:s.number().int(),pageNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional(),lineNumber:s.union([s.number().int(),s.tuple([s.number().int(),s.number().int()])]).optional()}),K0=s.object({entries:s.array(G0)});s.object({content:s.string(),score:s.number(),citation:Vb});var Kf=s.discriminatedUnion("type",[s.object({type:s.literal("recursive-v1"),chunkSize:s.number().int(),chunkOverlap:s.number().int()})]),Io=s.enum(["loading","chunking","embedding"]),H0=s.enum(["unknown","integratedGpu","dedicatedGpu"]),J0=s.object({name:s.string(),deviceId:s.number().int(),totalMemoryBytes:s.number().int(),type:H0});s.object({key:s.string(),name:s.string(),accelerators:s.array(J0)});var Y0=s.object({shortKey:s.string(),fullKey:s.string(),typeKey:s.string(),typeParams:Ce,defaultValue:Ce}),Id=s.object({fields:s.array(Y0),extensionPrefixes:s.array(s.string()).optional()});s.object({fullKey:s.string(),error:Ce});var Ii=s.union([s.literal(!0),s.literal(!1),s.literal("mixed")]),Q0=s.object({domain:Rn.optional(),architectures:s.array(s.string()).optional(),compatibilityTypes:s.array(fs).optional(),paramsStrings:s.array(s.string()).optional(),minMemoryUsageBytes:s.number().optional(),contextLengths:s.array(s.number()).optional(),trainedForToolUse:Ii.optional(),vision:Ii.optional(),reasoning:Ii.optional(),fim:Ii.optional()}),X0=s.object({key:s.string(),sources:s.array(rf)}),ol=s.object({type:s.literal("setJinjaVariable"),variable:s.string()}),ev=s.object({type:s.literal("prependSystemPrompt"),content:s.string()}),tv=s.object({type:s.literal("appendSystemPrompt"),content:s.string()}),al=s.object({key:s.string(),displayName:s.string(),description:s.string()}),rv=al.extend({type:s.literal("boolean"),defaultValue:s.boolean(),effects:s.array(s.discriminatedUnion("type",[ol,ev,tv]))}),nv=al.extend({type:s.literal("string"),defaultValue:s.string(),effects:s.array(s.discriminatedUnion("type",[ol]))}),iv=al.extend({type:s.literal("select"),options:s.array(s.object({label:s.string(),value:s.string()})),defaultValue:s.string(),effects:s.array(s.discriminatedUnion("type",[ol]))}),sv=s.discriminatedUnion("type",[rv,nv,iv]),ov=s.object({type:s.literal("equals"),key:s.string(),value:Ce}),av=s.discriminatedUnion("type",[ov]),lv=s.object({message:s.string(),conditions:s.array(av),fields:s.array(bf).optional()});s.object({model:s.string().regex(/^[^/]+\/[^/]+$/),base:s.union([s.string(),s.array(X0)]),tags:s.array(s.string().max(100)).optional(),config:s.object({load:X.optional(),operation:X.optional()}).optional(),metadataOverrides:Q0.optional(),customFields:s.array(sv).optional(),suggestions:s.array(lv).optional()});var cv=s.enum(["debug","info","warn","error"]);function B(r,e,t,n){if(t!==void 0)try{let i=t(...n);typeof i=="object"&&typeof i.catch=="function"&&i.catch(o=>{r.error(`Error in the ${e} callback (triggered asynchronously):`,o)})}catch(i){r.error(`Error in the ${e} callback:`,i)}}function uv(r){return r?.isSimpleLogger===!0}var dv=I.default.greenBright("I"),fv=I.default.yellowBright("W"),hv=I.default.redBright("E"),pv=I.default.blueBright("D"),H=class r{constructor(e="",t=console,{useLogLevelPrefixes:n,infoPrefix:i,warnPrefix:o,errorPrefix:a,debugPrefix:l}={}){this.isSimpleLogger=!0,this.infoPrefix=[],this.warnPrefix=[],this.errorPrefix=[],this.debugPrefix=[],uv(t)?(n=n??t.opts.useLogLevelPrefixes,i=i===void 0?t.opts.infoPrefix:i,o=o===void 0?t.opts.warnPrefix:o,a=a===void 0?t.opts.errorPrefix:a,l=l===void 0?t.opts.debugPrefix:l,e===""?(this.innerPrefix=t.innerPrefix,this.fullPrefix=t.fullPrefix):(t.fullPrefix===""?this.innerPrefix=e:this.innerPrefix=`${t.innerPrefix}][${e}`,this.fullPrefix=I.default.whiteBright(`[${this.innerPrefix}]`)),this.parentLogger=t.parentLogger):(n=n??!1,i=i===void 0?dv:i,o=o===void 0?fv:o,a=a===void 0?hv:a,l=l===void 0?pv:l,e===""?(this.innerPrefix="",this.fullPrefix=""):(this.innerPrefix=e,this.fullPrefix=I.default.whiteBright(`[${this.innerPrefix}]`)),this.parentLogger=t),n&&(i!==null&&this.infoPrefix.push(i),o!==null&&this.warnPrefix.push(o),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:o,errorPrefix:a,debugPrefix:l}}subclass(e){return new r(`${this.innerPrefix}:${e}`,this.parentLogger)}info(...e){this.parentLogger.info(...this.infoPrefix,...e)}infoText(e,...t){this.info(j(e,...t))}infoWithoutPrefix(...e){this.parentLogger.info(...e)}error(...e){this.parentLogger.error(...this.errorPrefix,...e)}errorText(e,...t){this.error(j(e,...t))}errorWithoutPrefix(...e){this.parentLogger.error(...e)}warn(...e){this.parentLogger.warn(...this.warnPrefix,...e)}warnText(e,...t){this.warn(j(e,...t))}warnWithoutPrefix(...e){this.parentLogger.warn(...e)}debug(...e){this.parentLogger.debug(...this.debugPrefix,...e)}debugText(e,...t){this.debug(j(e,...t))}debugWithoutPrefix(...e){this.parentLogger.debug(...e)}throw(e){throw new Error(`${this.fullPrefix} ${e}`)}logAtLevel(e,...t){switch(e){case"debug":this.debug(...t);break;case"info":this.info(...t);break;case"warn":this.warn(...t);break;case"error":this.error(...t);break}}static fromMultiple(e,t){return new r("",{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)}},{...t,useLogLevelPrefixes:!1})}},Od,Md=Symbol("finished"),Hi=class{finished(e){if(this.status!=="pending")throw new Error("`finished` called while not pending");e===void 0?(this.status="resolved",this.nextFragmentPromiseBundle?.resolve(Md),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[Od]="StreamablePromise";let{promise:e,resolve:t,reject:n}=ee();this.promiseFinal=e,this.resolveFinal=t,this.rejectFinal=n}then(e,t){return this.promiseFinal.then(e,t)}catch(e){return this.promiseFinal.catch(e)}finally(e){return this.promiseFinal.finally(e)}obtainNextFragmentPromiseBundle(){return this.nextFragmentPromiseBundle===null&&(this.nextFragmentPromiseBundle=ee()),this.nextFragmentPromiseBundle}async*[(Od=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===Md)break;yield n,e++}await this.promiseFinal,await Promise.resolve()}},Qe=class r{constructor({attachStack:e}={}){this.attachStack=e??!0}static prettyPrintZod(e,t){return t.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(`
|
|
57
|
-
`)}validateOrThrow(e,
|
|
58
|
-
|
|
59
|
-
${
|
|
60
|
-
|
|
61
|
-
${l.map(({error:h,rootObjectName:f})=>
|
|
62
|
-
`)}`,this.attachStack?
|
|
63
|
-
${e}.${
|
|
64
|
-
`);return this.validateOrThrow(`Invalid parameter(s) for ${l}:`,n,i,
|
|
65
|
-
${e}.${
|
|
66
|
-
`)}:`},n,i,
|
|
67
|
-
${e}(${I.default.redBright(
|
|
68
|
-
`);return this.validateOrThrow(`Invalid parameter(s) when constructing ${a}`,
|
|
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(`
|
|
176
|
+
`)}validateOrThrow(e,r,n,i,s){let a=n.safeParse(i);if(a.success)return a.data;throw Ee(`${e}
|
|
177
|
+
|
|
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}
|
|
179
|
+
|
|
180
|
+
${l.map(({error:h,rootObjectName:f})=>t.prettyPrintZod(f,h)).join(`
|
|
181
|
+
`)}`,this.attachStack?s:void 0)}}validateMethodParamOrThrow(e,r,n,i,s,a){let l=I.default.yellowBright(j`
|
|
182
|
+
${e}.${r}(${I.default.redBright(n)})
|
|
183
|
+
`);return this.validateOrThrow(`Invalid parameter(s) for ${l}:`,n,i,s,a)}validateMethodParamsOrThrow(e,r,n,i,s,a){return this.validateMultipleOrThrow(l=>{let c=n.map((h,f)=>l.has(f)?I.default.redBright(h):h);return`Invalid parameter(s) for ${I.default.yellowBright(j`
|
|
184
|
+
${e}.${r}(${c.join(", ")})
|
|
185
|
+
`)}:`},n,i,s,a)}validateConstructorParamOrThrow(e,r,n,i,s){let a=I.default.yellowBright(j`
|
|
186
|
+
${e}(${I.default.redBright(r)})
|
|
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`
|
|
69
188
|
${e}(${l.join(", ")})
|
|
70
|
-
`)}:`},
|
|
71
|
-
Unsupported role for append() API with [role, content] parameters: ${
|
|
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`
|
|
190
|
+
Unsupported role for append() API with [role, content] parameters: ${r}.
|
|
72
191
|
Supported roles are 'user', 'system', and 'assistant'.
|
|
73
|
-
`)}}withAppended(...e){let
|
|
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`
|
|
74
193
|
Tried to access the message at index ${e}, but the history only has
|
|
75
194
|
${this.data.messages.length} messages.
|
|
76
|
-
`);return
|
|
195
|
+
`);return he.createRaw(this.data.messages[r],this.mutable)}getMessagesArray(){return this.data.messages.map(e=>he.createRaw(e,this.mutable))}map(e){return this.getMessagesArray().map(e)}flatMap(e){return this.getMessagesArray().flatMap(e)}*[Symbol.iterator](){for(let e of this.data.messages)yield he.createRaw(e,this.mutable)}consumeFiles(e,r){this.guardMutable();let n=[];for(let i of this.data.messages)n.push(...he.createRaw(i,!0).consumeFiles(e,r));return n}async consumeFilesAsync(e,r){this.guardMutable();let n=[];for(let i of this.data.messages)n.push(...await he.createRaw(i,!0).consumeFilesAsync(e,r));return n}getSystemPrompt(){return this.data.messages.filter(e=>e.role==="system").map(e=>e.content.filter(r=>r.type==="text").map(r=>r.text).join(" ")).join(`
|
|
77
196
|
|
|
78
|
-
`)}replaceSystemPrompt(e){this.guardMutable(),this.data.messages=this.data.messages.filter(
|
|
79
|
-
`+this.data.messages.map(e=>
|
|
197
|
+
`)}replaceSystemPrompt(e){this.guardMutable(),this.data.messages=this.data.messages.filter(r=>r.role!=="system"),this.data.messages.unshift({role:"system",content:[{type:"text",text:e}]})}filterInPlace(e){this.guardMutable(),this.data.messages=this.data.messages.filter(r=>e(he.createRaw(r,!0)))}toString(){return`Chat {
|
|
198
|
+
`+this.data.messages.map(e=>he.createRaw(e,!1).toString().split(`
|
|
80
199
|
`).map(n=>" "+n).join(`
|
|
81
200
|
`)).join(`
|
|
82
201
|
`)+`
|
|
83
|
-
}`}},
|
|
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(`
|
|
84
203
|
`)?this.data.role+`:
|
|
85
204
|
`+e.split(`
|
|
86
|
-
`).map(
|
|
87
|
-
`):this.data.role+": "+e}},
|
|
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(`
|
|
88
207
|
`);throw n.length>10&&(i+=`
|
|
89
208
|
... and ${n.length-10} more`),new Error(`Cannot access key ${e}. Key does not exist in the schematics. Available keys:
|
|
90
209
|
|
|
91
|
-
`+i)}return
|
|
210
|
+
`+i)}return r}obtainFieldByFullKey(e){let r=this.getFullKeyMap().get(e);if(r===void 0){let n=[...this.getFullKeyMap().keys()],i=n.slice(0,10).map(s=>`- ${s}`).join(`
|
|
92
211
|
`);throw n.length>10&&(i+=`
|
|
93
212
|
... and ${n.length-10} more`),new Error(`Cannot access full key ${e}. Full key does not exist in the schematics. Availablekeys:
|
|
94
213
|
|
|
95
|
-
`+i)}return
|
|
96
|
-
`),e)}var
|
|
97
|
-
${
|
|
98
|
-
${
|
|
99
|
-
${
|
|
100
|
-
${
|
|
101
|
-
${
|
|
102
|
-
${
|
|
103
|
-
${
|
|
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")}
|
|
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
|
+
${r("config:customInputs.llmPromptTemplate.manual.subfield.beforeSystem/label","Before System")}: ${dn(t.manualPromptTemplate?.beforeSystem)}
|
|
218
|
+
${r("config:customInputs.llmPromptTemplate.manual.subfield.afterSystem/label","After System")}: ${dn(t.manualPromptTemplate?.afterSystem)}
|
|
219
|
+
${r("config:customInputs.llmPromptTemplate.manual.subfield.beforeUser/label","Before User")}: ${dn(t.manualPromptTemplate?.beforeUser)}
|
|
220
|
+
${r("config:customInputs.llmPromptTemplate.manual.subfield.afterUser/label","After User")}: ${dn(t.manualPromptTemplate?.afterUser)}
|
|
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:`
|
|
104
223
|
`,beforeAssistant:"AI: ",afterAssistant:`
|
|
105
224
|
`,beforeUser:"Human: ",afterUser:`
|
|
106
|
-
`},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",
|
|
107
|
-
`}e.prototype.toString=function(g){return this.errors.map(t).join("")},Object.defineProperty(e.prototype,"valid",{get:function(){return!this.errors.length}}),ue.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=ue.SchemaError=function m(g,b){this.message=g,this.schema=b,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 o=ue.SchemaContext=function(g,b,y,D,v){this.schema=g,this.options=b,Array.isArray(y)?(this.path=y,this.propertyPath=y.reduce(function(S,_){return S+l(_)},"instance")):this.propertyPath=y,this.base=D,this.schemas=v};o.prototype.resolve=function(g){return p(this.base,g)},o.prototype.makeChild=function(g,b){var y=b===void 0?this.path:this.path.concat([b]),D=g.$id||g.id;let v=p(this.base,D||"");var S=new o(g,this.options,y,v,Object.create(this.schemas));return D&&!S.schemas[v]&&(S.schemas[v]=g),S};var a=ue.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"],ue.isFormat=function(g,b,y){if(typeof g=="string"&&a[b]!==void 0){if(a[b]instanceof RegExp)return a[b].test(g);if(typeof a[b]=="function")return a[b](g)}else if(y&&y.customFormats&&typeof y.customFormats[b]=="function")return y.customFormats[b](g);return!0};var l=ue.makeSuffix=function(g){return g=g.toString(),!g.match(/[.\s\[\]]/)&&!g.match(/^[\d]/)?"."+g:g.match(/^\d+$/)?"["+g+"]":"["+JSON.stringify(g)+"]"};ue.deepCompareStrict=function m(g,b){if(typeof g!=typeof b)return!1;if(Array.isArray(g))return!Array.isArray(b)||g.length!==b.length?!1:g.every(function(v,S){return m(g[S],b[S])});if(typeof g=="object"){if(!g||!b)return g===b;var y=Object.keys(g),D=Object.keys(b);return y.length!==D.length?!1:y.every(function(v){return m(g[v],b[v])})}return g===b};function c(m,g,b,y){typeof b=="object"?g[y]=f(m[y],b):m.indexOf(b)===-1&&g.push(b)}function u(m,g,b){g[b]=m[b]}function h(m,g,b,y){typeof g[y]!="object"||!g[y]?b[y]=g[y]:m[y]?b[y]=f(m[y],g[y]):b[y]=g[y]}function f(m,g){var b=Array.isArray(g),y=b&&[]||{};return b?(m=m||[],y=y.concat(m),g.forEach(c.bind(null,m,y))):(m&&typeof m=="object"&&Object.keys(m).forEach(u.bind(null,m,y)),Object.keys(g).forEach(h.bind(null,m,g,y))),y}ue.deepMerge=f,ue.objectGetPath=function(g,b){for(var y=b.split("/").slice(1),D;typeof(D=y.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")}ue.encodePath=function(g){return g.map(d).join("")},ue.getDecimalPlaces=function(g){var b=0;if(isNaN(g))return b;typeof g!="number"&&(g=Number(g));var y=g.toString().split("e");if(y.length===2){if(y[1][0]!=="-")return b;b=Number(y[1].slice(1))}var D=y[0].split(".");return D.length===2&&(b+=D[1].length),b},ue.isSchema=function(g){return typeof g=="object"&&g||typeof g=="boolean"};var p=ue.resolveUrl=function(g,b){let y=new URL(b,new URL(g,"resolve://"));if(y.protocol==="resolve:"){let{pathname:D,search:v,hash:S}=y;return D+v+S}return y.toString()};return ue}var Mo,Ld;function Ev(){if(Ld)return Mo;Ld=1;var r=lr(),e=r.ValidatorResult,t=r.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),b=Array.isArray(d.type)?d.type:[d.type];if(!b.some(this.testType.bind(this,f,d,p,m))){var y=b.map(function(D){if(D){var v=D.$id||D.id;return v?"<"+v+">":D+""}});g.addError({name:"type",argument:y,message:"is not of a type(s) "+y})}return g};function o(h,f,d,p,m){var g=f.throwError,b=f.throwAll;f.throwError=!1,f.throwAll=!1;var y=this.validateSchema(h,m,f,d);return f.throwError=g,f.throwAll=b,!y.valid&&p instanceof Function&&p(y),y.valid}i.anyOf=function(f,d,p,m){if(f===void 0)return null;var g=new e(f,d,p,m),b=new e(f,d,p,m);if(!Array.isArray(d.anyOf))throw new t("anyOf must be an array");if(!d.anyOf.some(o.bind(this,f,p,m,function(D){b.importErrors(D)}))){var y=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(b),g.addError({name:"anyOf",argument:y,message:"is not any of "+y.join(",")})}return g},i.allOf=function(f,d,p,m){if(f===void 0)return null;if(!Array.isArray(d.allOf))throw new t("allOf must be an array");var g=new e(f,d,p,m),b=this;return d.allOf.forEach(function(y,D){var v=b.validateSchema(f,y,p,m);if(!v.valid){var S=y.$id||y.id,_=S||y.title&&JSON.stringify(y.title)||y.$ref&&"<"+y.$ref+">"||"[subschema "+D+"]";g.addError({name:"allOf",argument:{id:_,length:v.errors.length,valid:v},message:"does not match allOf schema "+_+" 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 t("oneOf must be an array");var g=new e(f,d,p,m),b=new e(f,d,p,m),y=d.oneOf.filter(o.bind(this,f,p,m,function(v){b.importErrors(v)})).length,D=d.oneOf.map(function(v,S){var _=v.$id||v.id;return _||v.title&&JSON.stringify(v.title)||v.$ref&&"<"+v.$ref+">"||"[subschema "+S+"]"});return y!==1&&(p.nestedErrors&&g.importErrors(b),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(!r.isSchema(d.if))throw new Error('Expected "if" keyword to be a schema');var g=o.call(this,f,p,m,null,d.if),b=new e(f,d,p,m),y;if(g){if(d.then===void 0)return;if(!r.isSchema(d.then))throw new Error('Expected "then" keyword to be a schema');y=this.validateSchema(f,d.then,p,m.makeChild(d.then)),b.importErrors(y)}else{if(d.else===void 0)return;if(!r.isSchema(d.else))throw new Error('Expected "else" keyword to be a schema');y=this.validateSchema(f,d.else,p,m.makeChild(d.else)),b.importErrors(y)}return b};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),b=d.propertyNames!==void 0?d.propertyNames:{};if(!r.isSchema(b))throw new t('Expected "propertyNames" to be a schema (object or boolean)');for(var y in f)if(a(f,y)!==void 0){var D=this.validateSchema(y,b,p,m.makeChild(b));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),b=d.properties||{};for(var y in b){var D=b[y];if(D!==void 0){if(D===null)throw new t('Unexpected null, expected schema in "properties"');typeof p.preValidateProperty=="function"&&p.preValidateProperty(f,y,D,p,m);var v=a(f,y),S=this.validateSchema(v,D,p,m.makeChild(D,y));S.instance!==g.instance[y]&&(g.instance[y]=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 b=f.additionalProperties||{};typeof d.preValidateProperty=="function"&&d.preValidateProperty(h,m,b,d,p);var y=this.validateSchema(h[m],b,d,p.makeChild(b,m));y.instance!==g.instance[m]&&(g.instance[m]=y.instance),g.importErrors(y)}}i.patternProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),b=d.patternProperties||{};for(var y in f){var D=!0;for(var v in b){var S=b[v];if(S!==void 0){if(S===null)throw new t('Unexpected null, expected schema in "patternProperties"');try{var _=new RegExp(v,"u")}catch{_=new RegExp(v)}if(_.test(y)){D=!1,typeof p.preValidateProperty=="function"&&p.preValidateProperty(f,y,S,p,m);var k=this.validateSchema(f[y],S,p,m.makeChild(S,y));k.instance!==g.instance[y]&&(g.instance[y]=k.instance),g.importErrors(k)}}}D&&l.call(this,f,d,p,m,y,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 b in f)l.call(this,f,d,p,m,b,g);return g}},i.minProperties=function(f,d,p,m){if(this.types.object(f)){var g=new e(f,d,p,m),b=Object.keys(f);return b.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),b=Object.keys(f);return b.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 b=new e(f,d,p,m);return f.every(function(y,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 b.addError({name:"items",message:"additionalItems not permitted"}),!1;var S=g.validateSchema(y,v,p,m.makeChild(v,D));return S.instance!==b.instance[D]&&(b.instance[D]=S.instance),b.importErrors(S),!0}),b}},i.contains=function(f,d,p,m){var g=this;if(this.types.array(f)&&d.contains!==void 0){if(!r.isSchema(d.contains))throw new Error('Expected "contains" keyword to be a schema');var b=new e(f,d,p,m),y=f.some(function(D,v){var S=g.validateSchema(D,d.contains,p,m.makeChild(d.contains,v));return S.errors.length===0});return y===!1&&b.addError({name:"contains",argument:d.contains,message:"must contain an item matching given schema"}),b}},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),b=f>d.exclusiveMinimum;return b||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),b=f<d.exclusiveMaximum;return b||g.addError({name:"exclusiveMaximum",argument:d.exclusiveMaximum,message:"must be strictly less than "+d.exclusiveMaximum}),g}};var c=function(f,d,p,m,g,b){if(this.types.number(f)){var y=d[g];if(y==0)throw new t(g+" cannot be zero");var D=new e(f,d,p,m),v=r.getDecimalPlaces(f),S=r.getDecimalPlaces(y),_=Math.max(v,S),k=Math.pow(10,_);return Math.round(f*k)%Math.round(y*k)!==0&&D.addError({name:g,argument:y,message:b+JSON.stringify(y)}),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(b){a(f,b)===void 0&&g.addError({name:"required",argument:b,message:"requires property "+JSON.stringify(b)})}),g},i.pattern=function(f,d,p,m){if(this.types.string(f)){var g=new e(f,d,p,m),b=d.pattern;try{var y=new RegExp(b,"u")}catch{y=new RegExp(b)}return f.match(y)||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&&!r.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),b=f.match(/[\uDC00-\uDFFF]/g),y=f.length-(b?b.length:0);return y>=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),b=f.match(/[\uDC00-\uDFFF]/g),y=f.length-(b?b.length:0);return y<=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(r.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 b in d.dependencies)if(f[b]!==void 0){var y=d.dependencies[b],D=m.makeChild(y,b);if(typeof y=="string"&&(y=[y]),Array.isArray(y))y.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,y,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 t("enum expects an array",d);var g=new e(f,d,p,m);return d.enum.some(r.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 r.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 b=new e(f,d,p,m),y=d.not||d.disallow;return y?(Array.isArray(y)||(y=[y]),y.forEach(function(D){if(g.testType(f,d,p,m,D)){var v=D&&(D.$id||D.id),S=v||D;b.addError({name:"not",argument:S,message:"is of prohibited type "+S})}}),b):null},Mo=n,Mo}var Oi={},Nd;function ta(){if(Nd)return Oi;Nd=1;var r=lr();Oi.SchemaScanResult=e;function e(t,n){this.id=t,this.ref=n}return Oi.scan=function(n,i){function o(h,f){if(!f||typeof f!="object")return;if(f.$ref){let g=r.resolveUrl(h,f.$ref);u[g]=u[g]?u[g]+1:0;return}var d=f.$id||f.id;let p=r.resolveUrl(h,d);var m=d?p:h;if(m){if(m.indexOf("#")<0&&(m+="#"),c[m]){if(!r.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]),o(m+"/additionalItems",f.additionalItems),l(m+"/properties",f.properties),o(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),o(m+"/not",f.not)}function a(h,f){if(Array.isArray(f))for(var d=0;d<f.length;d++)o(h+"/"+d,f[d])}function l(h,f){if(!(!f||typeof f!="object"))for(var d in f)o(h+"/"+d,f[d])}var c={},u={};return o(n,i),new e(c,u)},Oi}var jo,$d;function xv(){if($d)return jo;$d=1;var r=Ev(),e=lr(),t=ta().scan,n=e.ValidatorResult,i=e.ValidatorResultError,o=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(r.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=t(p||l,d),b=p||d.$id||d.id;for(var y in g.id)this.schemas[y]=g.id[y];for(var y in g.ref)this.unresolvedRefs.push(y);return this.unresolvedRefs=this.unresolvedRefs.filter(function(D){return typeof m.schemas[D]>"u"}),this.schemas[b]},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 o("Expected `schema` to be an object or boolean");m||(m={});var b=p.$id||p.id;let y=e.resolveUrl(m.base,b||"");if(!g){g=new a(p,m,[],y,Object.create(this.schemas)),g.schemas[y]||(g.schemas[y]=p);var D=t(y,p);for(var v in D.id){var S=D.id[v];g.schemas[v]=S}}if(m.required&&d===void 0){var _=new n(d,p,m,g);return _.addError("is required, but is undefined"),_}var _=this.validateSchema(d,p,m,g);if(_){if(m.throwAll&&_.errors.length)throw new i(_)}else throw new Error("Result undefined");return _};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 b=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 y={schema:p,ctx:g};p.extends.forEach(this.schemaTraverser.bind(this,y)),p=y.schema,y.schema=null,y.ctx=null,y=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 _=m&&m.skipAttributes||[];for(var k in p)if(!r.ignoreProperties[k]&&_.indexOf(k)<0){var x=null,z=this.attributes[k];if(z)x=z.call(this,d,p,m,g);else if(m.allowUnknownAttributes===!1)throw new o("Unsupported attribute: "+k,p);x&&b.importErrors(x)}if(typeof m.rewrite=="function"){var w=m.rewrite.call(this,d,p,m,g);b.instance=w}return b},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 b=new URL(p,"thismessage::/").hash;var y=b&&b.length&&p.substr(0,p.length-b.length);if(!y||!m.schemas[y])throw new o("no such schema <"+p+">",d);var D=e.objectGetPath(m.schemas[y],b.substr(1));if(D===void 0)throw new o("no such schema "+b+" located in <"+y+">",d);return{subschema:D,switchSchema:p}},c.prototype.testType=function(d,p,m,g,b){if(b!==void 0){if(b===null)throw new o('Unexpected null in "type" keyword');if(typeof this.types[b]=="function")return this.types[b].call(this,d);if(b&&typeof b=="object"){var y=this.validateSchema(d,b,m,g);return y===void 0||!(y&&y.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)},jo=c,jo}var Ud;function kv(){if(Ud)return Ge;Ud=1;var r=Ge.Validator=xv();return Ge.ValidatorResult=lr().ValidatorResult,Ge.ValidatorResultError=lr().ValidatorResultError,Ge.ValidationError=lr().ValidationError,Ge.SchemaError=lr().SchemaError,Ge.SchemaScanResult=ta().SchemaScanResult,Ge.scan=ta().scan,Ge.validate=function(e,t,n){var i=new r;return i.validate(e,t,n)},Ge}var Fv=kv(),hs=s.object({name:s.string(),description:s.string()}),ra=class{constructor(e,t,n){this.logger=e,this.signal=t,this.callId=n}status(e){this.logger.info(e)}warn(e){this.logger.warn(e)}},Pv=hs.extend({type:s.literal("function"),parametersSchema:yr,checkParameters:s.function(),implementation:s.function()}),Tv=hs.extend({type:s.literal("rawFunction"),parametersSchema:yr,checkParameters:s.function(),implementation:s.function()}),Av=hs.extend({type:s.literal("unimplementedRawFunction"),parametersJsonSchema:yr,checkParameters:s.function(),implementation:s.function()}),Rv=hs.extend({type:s.literal("remoteTool"),pluginIdentifier:s.string(),parametersJsonSchema:yr,checkParameters:s.function(),implementation:s.function()});s.discriminatedUnion("type",[Pv,Tv,Av,Rv]);function Iv(r,e){return e.map(t=>`${[r,...t.path].join(".")} ${t.message}`).join(`
|
|
108
|
-
`)}var
|
|
109
|
-
Failed to parse arguments for tool "${
|
|
110
|
-
${
|
|
111
|
-
`)},implementation:i}}function Mv(r){return{type:"function",function:{name:r.name,description:r.description,parameters:xi(r.parametersSchema)}}}function jv(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parametersJsonSchema}}}function Bv(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parametersJsonSchema}}}function ul(r){let e=r.type;switch(e){case"function":return Mv(r);case"rawFunction":case"unimplementedRawFunction":return jv(r);case"remoteTool":return Bv(r);default:{let t=e;throw new Error(`Unhandled type: ${t}`)}}}var cr=class extends Error{constructor(e,t){super(e),this.rawContent=t}},Rt=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:t,returns:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.rpcEndpoints.set(e,{name:e,parameter:t,returns:n,serialization:i,handler:null}),this}addChannelEndpoint(e,{creationParameter:t,toServerPacket:n,toClientPacket:i,serialization:o="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.channelEndpoints.set(e,{name:e,creationParameter:t,toServerPacket:n,toClientPacket:i,serialization:o,handler:null}),this}addSignalEndpoint(e,{creationParameter:t,signalData:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.signalEndpoints.set(e,{name:e,creationParameter:t,signalData:n,serialization:i,handler:null}),this}addWritableSignalEndpoint(e,{creationParameter:t,signalData:n,serialization:i="raw"}){return this.assertEndpointNameNotExists(e),this.existingEndpointNames.add(e),this.writableSignalEndpoints.set(e,{name:e,creationParameter:t,signalData:n,serialization:i,handler:null}),this}handleRpcEndpoint(e,t){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=t,this.unhandledEndpoints.delete(e)}handleChannelEndpoint(e,t){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=t,this.unhandledEndpoints.delete(e)}handleSignalEndpoint(e,t){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=t,this.unhandledEndpoints.delete(e)}handleWritableSignalEndpoint(e,t){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=t,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()]}},Ft;(function(r){r.Connected="CONNECTED",r.Errored="ERRORED",r.Closed="CLOSED"})(Ft||(Ft={}));var Mi=new H("Channel"),ia=class r{constructor(e){this.innerSend=e,this.nextAckId=0,this.waitingForAck=new Map,this.receivedACK=t=>{if(this.connectionStatus.get()!==Ft.Connected){Mi.warn("Received ACK while in status",this.connectionStatus.get());return}let n=this.waitingForAck.get(t);if(n===void 0){Mi.warn("Received ACK for a message that is no longer waiting for ACK, ackId =",t);return}n.resolve(),this.waitingForAck.delete(t)},this.receivedMessage=t=>{if(this.connectionStatus.get()!==Ft.Connected){Mi.warn("Received message while in status",this.connectionStatus.get());return}this.emitOnMessage(t)},this.errored=t=>{if(this.connectionStatus.get()!==Ft.Connected){Mi.warn("Received error while in status",this.connectionStatus.get());return}this.rejectAllWaitingForAck(t),this.setConnectionStatus(Ft.Errored),this.emitOnError(t)},this.closed=()=>{this.rejectAllWaitingForAck(new Error("Channel closed")),this.setConnectionStatus(Ft.Closed),this.emitOnClose()},[this.onMessage,this.emitOnMessage]=mt.create(),[this.onError,this.emitOnError]=mt.create(),[this.onClose,this.emitOnClose]=mt.create(),[this.connectionStatus,this.setConnectionStatus]=Fn.create(Ft.Connected)}rejectAllWaitingForAck(e){let t=Array.from(this.waitingForAck.values()).map(({reject:n})=>n);this.waitingForAck.clear();for(let n of t)n(e)}static create(e){let t=new r(e);return{channel:t,receivedAck:t.receivedACK,receivedMessage:t.receivedMessage,errored:t.errored,closed:t.closed}}send(e){this.innerSend(e)}sendAndWaitForACK(e){let{promise:t,resolve:n,reject:i}=ee(),o=this.nextAckId;return this.nextAckId++,this.waitingForAck.set(o,{resolve:n,reject:i}),this.innerSend(e,o),t}},Lv=(function(){function r(){this.keyToValue=new Map,this.valueToKey=new Map}return r.prototype.set=function(e,t){this.keyToValue.set(e,t),this.valueToKey.set(t,e)},r.prototype.getByKey=function(e){return this.keyToValue.get(e)},r.prototype.getByValue=function(e){return this.valueToKey.get(e)},r.prototype.clear=function(){this.keyToValue.clear(),this.valueToKey.clear()},r})(),nh=(function(){function r(e){this.generateIdentifier=e,this.kv=new Lv}return r.prototype.register=function(e,t){this.kv.getByValue(e)||(t||(t=this.generateIdentifier(e)),this.kv.set(t,e))},r.prototype.clear=function(){this.kv.clear()},r.prototype.getIdentifier=function(e){return this.kv.getByValue(e)},r.prototype.getValue=function(e){return this.kv.getByKey(e)},r})(),Nv=globalThis&&globalThis.__extends||(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),$v=(function(r){Nv(e,r);function e(){var t=r.call(this,function(n){return n.name})||this;return t.classToAllowedProps=new Map,t}return e.prototype.register=function(t,n){typeof n=="object"?(n.allowProps&&this.classToAllowedProps.set(t,n.allowProps),r.prototype.register.call(this,t,n.identifier)):r.prototype.register.call(this,t,n)},e.prototype.getAllowedProps=function(t){return this.classToAllowedProps.get(t)},e})(nh),Uv=globalThis&&globalThis.__read||function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o};function zv(r){if("values"in Object)return Object.values(r);var e=[];for(var t in r)r.hasOwnProperty(t)&&e.push(r[t]);return e}function qv(r,e){var t=zv(r);if("find"in t)return t.find(e);for(var n=t,i=0;i<n.length;i++){var o=n[i];if(e(o))return o}}function Kr(r,e){Object.entries(r).forEach(function(t){var n=Uv(t,2),i=n[0],o=n[1];return e(o,i)})}function $i(r,e){return r.indexOf(e)!==-1}function zd(r,e){for(var t=0;t<r.length;t++){var n=r[t];if(e(n))return n}}var Vv=(function(){function r(){this.transfomers={}}return r.prototype.register=function(e){this.transfomers[e.name]=e},r.prototype.findApplicable=function(e){return qv(this.transfomers,function(t){return t.isApplicable(e)})},r.prototype.findByName=function(e){return this.transfomers[e]},r})(),Wv=function(r){return Object.prototype.toString.call(r).slice(8,-1)},ih=function(r){return typeof r>"u"},Zv=function(r){return r===null},On=function(r){return typeof r!="object"||r===null||r===Object.prototype?!1:Object.getPrototypeOf(r)===null?!0:Object.getPrototypeOf(r)===Object.prototype},sa=function(r){return On(r)&&Object.keys(r).length===0},It=function(r){return Array.isArray(r)},Gv=function(r){return typeof r=="string"},Kv=function(r){return typeof r=="number"&&!isNaN(r)},Hv=function(r){return typeof r=="boolean"},Jv=function(r){return r instanceof RegExp},Mn=function(r){return r instanceof Map},jn=function(r){return r instanceof Set},sh=function(r){return Wv(r)==="Symbol"},Yv=function(r){return r instanceof Date&&!isNaN(r.valueOf())},Qv=function(r){return r instanceof Error},qd=function(r){return typeof r=="number"&&isNaN(r)},Xv=function(r){return Hv(r)||Zv(r)||ih(r)||Kv(r)||Gv(r)||sh(r)},eD=function(r){return typeof r=="bigint"},tD=function(r){return r===1/0||r===-1/0},rD=function(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)},nD=function(r){return r instanceof URL},oh=function(r){return r.replace(/\./g,"\\.")},Bo=function(r){return r.map(String).map(oh).join(".")},Dn=function(r){for(var e=[],t="",n=0;n<r.length;n++){var i=r.charAt(n),o=i==="\\"&&r.charAt(n+1)===".";if(o){t+=".",n++;continue}var a=i===".";if(a){e.push(t),t="";continue}t+=i}var l=t;return e.push(l),e},oa=globalThis&&globalThis.__assign||function(){return oa=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},oa.apply(this,arguments)},aa=globalThis&&globalThis.__read||function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},la=globalThis&&globalThis.__spreadArray||function(r,e){for(var t=0,n=e.length,i=r.length;t<n;t++,i++)r[i]=e[t];return r};function Ke(r,e,t,n){return{isApplicable:r,annotation:e,transform:t,untransform:n}}var ah=[Ke(ih,"undefined",function(){return null},function(){}),Ke(eD,"bigint",function(r){return r.toString()},function(r){return typeof BigInt<"u"?BigInt(r):(console.error("Please add a BigInt polyfill."),r)}),Ke(Yv,"Date",function(r){return r.toISOString()},function(r){return new Date(r)}),Ke(Qv,"Error",function(r,e){var t={name:r.name,message:r.message};return e.allowedErrorProps.forEach(function(n){t[n]=r[n]}),t},function(r,e){var t=new Error(r.message);return t.name=r.name,t.stack=r.stack,e.allowedErrorProps.forEach(function(n){t[n]=r[n]}),t}),Ke(Jv,"regexp",function(r){return""+r},function(r){var e=r.slice(1,r.lastIndexOf("/")),t=r.slice(r.lastIndexOf("/")+1);return new RegExp(e,t)}),Ke(jn,"set",function(r){return la([],aa(r.values()))},function(r){return new Set(r)}),Ke(Mn,"map",function(r){return la([],aa(r.entries()))},function(r){return new Map(r)}),Ke(function(r){return qd(r)||tD(r)},"number",function(r){return qd(r)?"NaN":r>0?"Infinity":"-Infinity"},Number),Ke(function(r){return r===0&&1/r===-1/0},"number",function(){return"-0"},Number),Ke(nD,"URL",function(r){return r.toString()},function(r){return new URL(r)})];function ps(r,e,t,n){return{isApplicable:r,annotation:e,transform:t,untransform:n}}var lh=ps(function(r,e){if(sh(r)){var t=!!e.symbolRegistry.getIdentifier(r);return t}return!1},function(r,e){var t=e.symbolRegistry.getIdentifier(r);return["symbol",t]},function(r){return r.description},function(r,e,t){var n=t.symbolRegistry.getValue(e[1]);if(!n)throw new Error("Trying to deserialize unknown symbol");return n}),iD=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce(function(r,e){return r[e.name]=e,r},{}),ch=ps(rD,function(r){return["typed-array",r.constructor.name]},function(r){return la([],aa(r))},function(r,e){var t=iD[e[1]];if(!t)throw new Error("Trying to deserialize unknown typed array");return new t(r)});function uh(r,e){if(r?.constructor){var t=!!e.classRegistry.getIdentifier(r.constructor);return t}return!1}var dh=ps(uh,function(r,e){var t=e.classRegistry.getIdentifier(r.constructor);return["class",t]},function(r,e){var t=e.classRegistry.getAllowedProps(r.constructor);if(!t)return oa({},r);var n={};return t.forEach(function(i){n[i]=r[i]}),n},function(r,e,t){var n=t.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),r)}),fh=ps(function(r,e){return!!e.customTransformerRegistry.findApplicable(r)},function(r,e){var t=e.customTransformerRegistry.findApplicable(r);return["custom",t.name]},function(r,e){var t=e.customTransformerRegistry.findApplicable(r);return t.serialize(r)},function(r,e,t){var n=t.customTransformerRegistry.findByName(e[1]);if(!n)throw new Error("Trying to deserialize unknown custom value");return n.deserialize(r)}),sD=[dh,lh,fh,ch],Vd=function(r,e){var t=zd(sD,function(i){return i.isApplicable(r,e)});if(t)return{value:t.transform(r,e),type:t.annotation(r,e)};var n=zd(ah,function(i){return i.isApplicable(r,e)});if(n)return{value:n.transform(r,e),type:n.annotation}},hh={};ah.forEach(function(r){hh[r.annotation]=r});var oD=function(r,e,t){if(It(e))switch(e[0]){case"symbol":return lh.untransform(r,e,t);case"class":return dh.untransform(r,e,t);case"custom":return fh.untransform(r,e,t);case"typed-array":return ch.untransform(r,e,t);default:throw new Error("Unknown transformation: "+e)}else{var n=hh[e];if(!n)throw new Error("Unknown transformation: "+e);return n.untransform(r,t)}},Wr=function(r,e){for(var t=r.keys();e>0;)t.next(),e--;return t.next().value};function ph(r){if($i(r,"__proto__"))throw new Error("__proto__ is not allowed as a property");if($i(r,"prototype"))throw new Error("prototype is not allowed as a property");if($i(r,"constructor"))throw new Error("constructor is not allowed as a property")}var aD=function(r,e){ph(e);for(var t=0;t<e.length;t++){var n=e[t];if(jn(r))r=Wr(r,+n);else if(Mn(r)){var i=+n,o=+e[++t]==0?"key":"value",a=Wr(r,i);switch(o){case"key":r=a;break;case"value":r=r.get(a);break}}else r=r[n]}return r},ca=function(r,e,t){if(ph(e),e.length===0)return t(r);for(var n=r,i=0;i<e.length-1;i++){var o=e[i];if(It(n)){var a=+o;n=n[a]}else if(On(n))n=n[o];else if(jn(n)){var l=+o;n=Wr(n,l)}else if(Mn(n)){var c=i===e.length-2;if(c)break;var l=+o,u=+e[++i]==0?"key":"value",h=Wr(n,l);switch(u){case"key":n=h;break;case"value":n=n.get(h);break}}}var f=e[e.length-1];if(It(n)?n[+f]=t(n[+f]):On(n)&&(n[f]=t(n[f])),jn(n)){var d=Wr(n,+f),p=t(d);d!==p&&(n.delete(d),n.add(p))}if(Mn(n)){var l=+e[e.length-2],m=Wr(n,l),u=+f==0?"key":"value";switch(u){case"key":{var g=t(m);n.set(g,n.get(m)),g!==m&&n.delete(m);break}case"value":{n.set(m,t(n.get(m)));break}}}return r},pt=globalThis&&globalThis.__read||function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},Pt=globalThis&&globalThis.__spreadArray||function(r,e){for(var t=0,n=e.length,i=r.length;t<n;t++,i++)r[i]=e[t];return r};function ua(r,e,t){if(t===void 0&&(t=[]),!!r){if(!It(r)){Kr(r,function(a,l){return ua(a,e,Pt(Pt([],pt(t)),pt(Dn(l))))});return}var n=pt(r,2),i=n[0],o=n[1];o&&Kr(o,function(a,l){ua(a,e,Pt(Pt([],pt(t)),pt(Dn(l))))}),e(i,t)}}function lD(r,e,t){return ua(e,function(n,i){r=ca(r,i,function(o){return oD(o,n,t)})}),r}function cD(r,e){function t(a,l){var c=aD(r,Dn(l));a.map(Dn).forEach(function(u){r=ca(r,u,function(){return c})})}if(It(e)){var n=pt(e,2),i=n[0],o=n[1];i.forEach(function(a){r=ca(r,Dn(a),function(){return r})}),o&&Kr(o,t)}else Kr(e,t);return r}var uD=function(r,e){return On(r)||It(r)||Mn(r)||jn(r)||uh(r,e)};function dD(r,e,t){var n=t.get(r);n?n.push(e):t.set(r,[e])}function fD(r,e){var t={},n=void 0;return r.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 o=pt(i),a=o[0],l=o.slice(1);a.length===0?n=l.map(Bo):t[Bo(a)]=l.map(Bo)}}),n?sa(t)?[n]:[n,t]:sa(t)?void 0:t}var mh=function(r,e,t,n,i,o,a){var l;i===void 0&&(i=[]),o===void 0&&(o=[]),a===void 0&&(a=new Map);var c=Xv(r);if(!c){dD(r,i,e);var u=a.get(r);if(u)return n?{transformedValue:null}:u}if(!uD(r,t)){var h=Vd(r,t),f=h?{transformedValue:h.value,annotations:[h.type]}:{transformedValue:r};return c||a.set(r,f),f}if($i(o,r))return{transformedValue:null};var d=Vd(r,t),p=(l=d?.value)!==null&&l!==void 0?l:r,m=It(p)?[]:{},g={};Kr(p,function(y,D){var v=mh(y,e,t,n,Pt(Pt([],pt(i)),[D]),Pt(Pt([],pt(o)),[r]),a);m[D]=v.transformedValue,It(v.annotations)?g[D]=v.annotations:On(v.annotations)&&Kr(v.annotations,function(S,_){g[oh(D)+"."+_]=S})});var b=sa(g)?{transformedValue:m,annotations:d?[d.type]:void 0}:{transformedValue:m,annotations:d?[d.type,g]:g};return c||a.set(r,b),b};function gh(r){return Object.prototype.toString.call(r).slice(8,-1)}function Wd(r){return gh(r)==="Array"}function hD(r){if(gh(r)!=="Object")return!1;let e=Object.getPrototypeOf(r);return!!e&&e.constructor===Object&&e===Object.prototype}function pD(r,e,t,n,i){let o={}.propertyIsEnumerable.call(n,e)?"enumerable":"nonenumerable";o==="enumerable"&&(r[e]=t),i&&o==="nonenumerable"&&Object.defineProperty(r,e,{value:t,enumerable:!1,writable:!0,configurable:!0})}function da(r,e={}){if(Wd(r))return r.map(i=>da(i,e));if(!hD(r))return r;let t=Object.getOwnPropertyNames(r),n=Object.getOwnPropertySymbols(r);return[...t,...n].reduce((i,o)=>{if(Wd(e.props)&&!e.props.includes(o))return i;let a=r[o],l=da(a,e);return pD(i,o,l,r,e.nonenumerable),i},{})}var or=globalThis&&globalThis.__assign||function(){return or=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},or.apply(this,arguments)},mD=globalThis&&globalThis.__read||function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],a;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(l){a={error:l}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},gD=globalThis&&globalThis.__spreadArray||function(r,e){for(var t=0,n=e.length,i=r.length;t<n;t++,i++)r[i]=e[t];return r},yh=(function(){function r(e){var t=e===void 0?{}:e,n=t.dedupe,i=n===void 0?!1:n;this.classRegistry=new $v,this.symbolRegistry=new nh(function(o){var a;return(a=o.description)!==null&&a!==void 0?a:""}),this.customTransformerRegistry=new Vv,this.allowedErrorProps=[],this.dedupe=i}return r.prototype.serialize=function(e){var t=new Map,n=mh(e,t,this,this.dedupe),i={json:n.transformedValue};n.annotations&&(i.meta=or(or({},i.meta),{values:n.annotations}));var o=fD(t,this.dedupe);return o&&(i.meta=or(or({},i.meta),{referentialEqualities:o})),i},r.prototype.deserialize=function(e){var t=e.json,n=e.meta,i=da(t);return n?.values&&(i=lD(i,n.values,this)),n?.referentialEqualities&&(i=cD(i,n.referentialEqualities)),i},r.prototype.stringify=function(e){return JSON.stringify(this.serialize(e))},r.prototype.parse=function(e){return this.deserialize(JSON.parse(e))},r.prototype.registerClass=function(e,t){this.classRegistry.register(e,t)},r.prototype.registerSymbol=function(e,t){this.symbolRegistry.register(e,t)},r.prototype.registerCustom=function(e,t){this.customTransformerRegistry.register(or({name:t},e))},r.prototype.allowErrorProps=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];(e=this.allowedErrorProps).push.apply(e,gD([],mD(t)))},r.defaultInstance=new r,r.serialize=r.defaultInstance.serialize.bind(r.defaultInstance),r.deserialize=r.defaultInstance.deserialize.bind(r.defaultInstance),r.stringify=r.defaultInstance.stringify.bind(r.defaultInstance),r.parse=r.defaultInstance.parse.bind(r.defaultInstance),r.registerClass=r.defaultInstance.registerClass.bind(r.defaultInstance),r.registerSymbol=r.defaultInstance.registerSymbol.bind(r.defaultInstance),r.registerCustom=r.defaultInstance.registerCustom.bind(r.defaultInstance),r.allowErrorProps=r.defaultInstance.allowErrorProps.bind(r.defaultInstance),r})(),yD=yh.serialize,bD=yh.deserialize;function zr(r,e){switch(r){case"raw":return e;case"superjson":return yD(e)}}function ji(r,e){switch(r){case"raw":return e;case"superjson":return bD(e)}}var Je=s.any(),vD=s.discriminatedUnion("type",[s.object({type:s.literal("communicationWarning"),warning:s.string()}),s.object({type:s.literal("keepAlive")}),s.object({type:s.literal("channelCreate"),endpoint:s.string(),channelId:s.number().int(),creationParameter:Je}),s.object({type:s.literal("channelSend"),channelId:s.number().int(),message:Je,ackId:s.number().int().optional()}),s.object({type:s.literal("channelAck"),channelId:s.number().int(),ackId:s.number().int()}),s.object({type:s.literal("rpcCall"),endpoint:s.string(),callId:s.number().int(),parameter:Je}),s.object({type:s.literal("signalSubscribe"),creationParameter:Je,endpoint:s.string(),subscribeId:s.number().int()}),s.object({type:s.literal("signalUnsubscribe"),subscribeId:s.number().int()}),s.object({type:s.literal("writableSignalSubscribe"),creationParameter:Je,endpoint:s.string(),subscribeId:s.number().int()}),s.object({type:s.literal("writableSignalUnsubscribe"),subscribeId:s.number().int()}),s.object({type:s.literal("writableSignalUpdate"),subscribeId:s.number().int(),patches:s.array(Je),tags:s.array(s.string())})]),DD=s.discriminatedUnion("type",[s.object({type:s.literal("communicationWarning"),warning:s.string()}),s.object({type:s.literal("keepAliveAck")}),s.object({type:s.literal("channelSend"),channelId:s.number().int(),message:Je,ackId:s.number().int().optional()}),s.object({type:s.literal("channelAck"),channelId:s.number().int(),ackId:s.number().int()}),s.object({type:s.literal("channelClose"),channelId:s.number().int()}),s.object({type:s.literal("channelError"),channelId:s.number().int(),error:xe}),s.object({type:s.literal("rpcResult"),callId:s.number().int(),result:Je}),s.object({type:s.literal("rpcError"),callId:s.number().int(),error:xe}),s.object({type:s.literal("signalUpdate"),subscribeId:s.number().int(),patches:s.array(Je),tags:s.array(s.string())}),s.object({type:s.literal("signalError"),subscribeId:s.number().int(),error:xe}),s.object({type:s.literal("writableSignalUpdate"),subscribeId:s.number().int(),patches:s.array(Je),tags:s.array(s.string())}),s.object({type:s.literal("writableSignalError"),subscribeId:s.number().int(),error:xe})]),fa=class{constructor(){this.disposed=!1}async[Symbol.asyncDispose](){if(this.disposed)throw new Error("Cannot dispose twice");this.disposed=!0}},Qi=class extends fa{parseIncomingMessage(e){return DD.parse(e)}send(e){let t=vD.parse(e);this.sendViaTransport(t)}onHavingOneOrMoreOpenCommunication(){}onHavingNoOpenCommunication(){}},wD=s.discriminatedUnion("success",[s.object({success:s.literal(!0)}),s.object({success:s.literal(!1),error:s.string()})]),Se;(function(r){r.Disconnected="DISCONNECTED",r.Connecting="CONNECTING",r.Connected="CONNECTED"})(Se||(Se={}));var ha=class r extends Qi{constructor(e,t,n,{abortSignal:i,parentLogger:o}={}){super(),this.url=e,this.receivedMessage=t,this.errored=n,this.ws=null,this.queuedMessages=[],this.status=Se.Disconnected,this.resolvedUrl=null,this.shouldRef=!1,this.resolveDisposed=null,this.abortSignal=i,this.logger=new H("WsClientTransport",o)}static createWsClientTransportFactory(e,{abortSignal:t}={}){return(n,i,o)=>new r(e,n,i,{abortSignal:t,parentLogger:o})}connect(){if(this.status!==Se.Disconnected){this.logger.warn("connect() called while not disconnected");return}if(this.disposed)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",{},_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`
|
|
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`
|
|
112
231
|
Cannot establish WebSocket connection because the transport has been disposed.
|
|
113
|
-
`);if(this.abortSignal!==void 0&&this.abortSignal.aborted)throw new Error(this.abortSignal.reason);this.status=
|
|
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`
|
|
114
233
|
WebSocket connection refused. This can happen if the server is not running or the client
|
|
115
234
|
is trying to connect to the wrong path. The server path that this client is
|
|
116
235
|
attempting to connect to is:
|
|
@@ -123,24 +242,24 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
123
242
|
2. The API server in LM Studio has started
|
|
124
243
|
|
|
125
244
|
3. The client is attempting to connect to the correct path
|
|
126
|
-
`;try{this.ws?.close()}catch{}this.status=
|
|
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`
|
|
127
246
|
Produced communication warning: ${e}
|
|
128
247
|
|
|
129
248
|
This is usually caused by communication protocol incompatibility. Please make sure you are
|
|
130
249
|
using the up-to-date versions of the SDK and LM Studio.
|
|
131
250
|
`,this.transport.send({type:"communicationWarning",warning:e}),this.producedCommunicationWarningsCount++,this.producedCommunicationWarningsCount>=5&&this.logger.errorText`
|
|
132
251
|
5 communication warnings have been produced. Further warnings will not be printed.
|
|
133
|
-
`)}updateOpenCommunicationsCount(){let e=this.openCommunicationsCount;this.openCommunicationsCount=this.openChannels.size+this.ongoingRpcs.size+this.openSignalSubscriptions.size+this.openWritableSignalSubscriptions.size,this.openCommunicationsCount===0&&e>0?this.transport.onHavingNoOpenCommunication():this.openCommunicationsCount===1&&e===0&&this.transport.onHavingOneOrMoreOpenCommunication()}receivedChannelSend(e){let
|
|
134
|
-
Received invalid message for channel: endpointName = ${
|
|
252
|
+
`)}updateOpenCommunicationsCount(){let e=this.openCommunicationsCount;this.openCommunicationsCount=this.openChannels.size+this.ongoingRpcs.size+this.openSignalSubscriptions.size+this.openWritableSignalSubscriptions.size,this.openCommunicationsCount===0&&e>0?this.transport.onHavingNoOpenCommunication():this.openCommunicationsCount===1&&e===0&&this.transport.onHavingOneOrMoreOpenCommunication()}receivedChannelSend(e){let r=this.openChannels.get(e.channelId);if(r===void 0){this.communicationWarning(`Received channelSend for unknown channel, channelId = ${e.channelId}`);return}let n=ws(r.endpoint.serialization,e.message),i=r.endpoint.toClientPacket.safeParse(n);if(!i.success){this.communicationWarning(j`
|
|
253
|
+
Received invalid message for channel: endpointName = ${r.endpoint.name}, message =
|
|
135
254
|
${n}. Zod error:
|
|
136
255
|
|
|
137
|
-
${
|
|
138
|
-
`);return}
|
|
139
|
-
Received invalid result for rpc, endpointName = ${
|
|
256
|
+
${it.prettyPrintZod("message",i.error)}
|
|
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
|
+
Received invalid result for rpc, endpointName = ${r.endpoint.name}, result =
|
|
140
259
|
${n}. Zod error:
|
|
141
260
|
|
|
142
|
-
${
|
|
143
|
-
`);return}
|
|
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`
|
|
144
263
|
Failed to apply patches to signal on signalUpdate. subscribeId = ${e.subscribeId}.
|
|
145
264
|
|
|
146
265
|
beforeValue = ${JSON.stringify(i,null,2)},
|
|
@@ -148,19 +267,19 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
148
267
|
patches = ${JSON.stringify(n,null,2)}.
|
|
149
268
|
|
|
150
269
|
Error: ${String(l)}
|
|
151
|
-
`);return}let a=
|
|
270
|
+
`);return}let a=r.endpoint.signalData.safeParse(s);if(!a.success){this.communicationWarning(j`
|
|
152
271
|
Received invalid signal patch data, subscribeId = ${e.subscribeId}
|
|
153
272
|
|
|
154
273
|
patches = ${n},
|
|
155
274
|
|
|
156
275
|
beforeValue = ${i},
|
|
157
276
|
|
|
158
|
-
afterValue = ${
|
|
277
|
+
afterValue = ${s}.
|
|
159
278
|
|
|
160
279
|
Zod error:
|
|
161
280
|
|
|
162
|
-
${
|
|
163
|
-
`);return}
|
|
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`
|
|
164
283
|
Failed to apply patches to writable signal on writableSignalUpdate. subscribeId =
|
|
165
284
|
${e.subscribeId}.
|
|
166
285
|
|
|
@@ -169,32 +288,32 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
169
288
|
patches = ${JSON.stringify(n,null,2)}.
|
|
170
289
|
|
|
171
290
|
Error: ${String(l)}
|
|
172
|
-
`)}let a=
|
|
291
|
+
`)}let a=r.endpoint.signalData.safeParse(s);if(!a.success){this.communicationWarning(j`
|
|
173
292
|
Received invalid writable signal patch data, subscribeId = ${e.subscribeId}
|
|
174
293
|
|
|
175
294
|
patches = ${n},
|
|
176
295
|
|
|
177
296
|
beforeValue = ${i},
|
|
178
297
|
|
|
179
|
-
afterValue = ${
|
|
298
|
+
afterValue = ${s}.
|
|
180
299
|
|
|
181
300
|
Zod error:
|
|
182
301
|
|
|
183
|
-
${
|
|
184
|
-
`);return}
|
|
302
|
+
${it.prettyPrintZod("value",a.error)}
|
|
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`
|
|
185
304
|
Received communication warning from the server: ${e.warning}
|
|
186
305
|
|
|
187
306
|
This is usually caused by communication protocol incompatibility. Please make sure you are
|
|
188
307
|
using the up-to-date versions of the SDK and LM Studio.
|
|
189
308
|
|
|
190
309
|
Note: This warning was received from the server and is printed on the client for convenience.
|
|
191
|
-
`}receivedKeepAliveAck(e){}async callRpc(e,t,{stack:n}={}){let i=this.backendInterface.getRpcEndpoint(e);if(i===void 0)throw new Error(`No Rpc endpoint with name ${e}`);let o=i.parameter.parse(t),a=zr(i.serialization,o),l=this.nextChannelId;this.nextChannelId++;let{promise:c,resolve:u,reject:h}=ee();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,t,n,{stack:i}={}){let o=this.backendInterface.getChannelEndpoint(e);if(o===void 0)throw new Error(`No channel endpoint with name ${e}`);let a=o.creationParameter.parse(t),l=zr(o.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:o,stack:i,...ia.create(h=>{let f=o.toServerPacket.parse(h),d=zr(o.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,t,{stack:n}={}){let i=this.backendInterface.getSignalEndpoint(e);if(i===void 0)throw new Error(`No signal endpoint with name ${e}`);let o=i.creationParameter.parse(t),a=zr(i.serialization,o);n=n??A(1);let l=Ue.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,t,{stack:n}={}){let i=this.backendInterface.getWritableSignalEndpoint(e);if(i===void 0)throw new Error(`No writable signal endpoint with name ${e}`);let o=i.creationParameter.parse(t),a=zr(i.serialization,o);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=>zr(i.serialization,g)),tags:p}),!0):(console.warn("writeUpstream called before the first update is received"),!1),[u,h]=Vo.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]()}},ma=class r extends Qi{constructor(e,t,n,i,o,a){super(),this.sendMessage=n,this.receivedMessage=i,this.errored=o,this.closed=!1,this.logger=new H("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)}),t.subscribeOnce(()=>{this.closed||(this.closed=!0,this.errored(new Error("Server closed the connection")))})}static createFactory(e,t,n){return(i,o,a)=>new r(e,t,n,i,o,a)}sendViaTransport(e){this.sendMessage(e)}};function bh(){let r;try{r=window}catch{r=void 0}return r!==void 0&&r.lmsHostedEnv!==void 0?r.lmsHostedEnv:null}function vh(r,e){let t=r,n=e;return new Rt().addChannelEndpoint("loadModel",{creationParameter:s.object({modelKey:s.string(),identifier:s.string().optional(),ttlMs:s.number().int().min(1).optional(),loadConfigStack:Ki}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("resolved"),info:n,ambiguous:s.array(s.string()).optional()}),s.object({type:s.literal("progress"),progress:s.number()}),s.object({type:s.literal("success"),info:t})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addRpcEndpoint("unloadModel",{parameter:s.object({identifier:s.string()}),returns:s.void()}).addRpcEndpoint("listLoaded",{parameter:s.undefined(),returns:s.array(t)}).addRpcEndpoint("getModelInfo",{parameter:s.object({specifier:Ye,throwIfNotFound:s.boolean()}),returns:t.optional()}).addRpcEndpoint("getLoadConfig",{parameter:s.object({specifier:Ye}),returns:X}).addChannelEndpoint("getOrLoad",{creationParameter:s.object({identifier:s.string(),loadTtlMs:s.number().int().min(1).optional(),loadConfigStack:Ki}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("alreadyLoaded"),info:t}),s.object({type:s.literal("startLoading"),identifier:s.string(),info:n}),s.object({type:s.literal("unloadingOtherJITModel"),info:$0}),s.object({type:s.literal("loadProgress"),progress:s.number()}),s.object({type:s.literal("loadSuccess"),info:t})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])})}function CD(){return new Rt().addChannelEndpoint("streamLogs",{creationParameter:s.void(),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("stop")})]),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("log"),log:Kb})])})}function _D(){return vh(pf,hf).addRpcEndpoint("embedString",{parameter:s.object({modelSpecifier:Ye,inputString:s.string()}),returns:s.object({embedding:s.array(s.number())})}).addRpcEndpoint("tokenize",{parameter:s.object({specifier:Ye,inputString:s.string()}),returns:s.object({tokens:s.array(s.number())})}).addRpcEndpoint("countTokens",{parameter:s.object({specifier:Ye,inputString:s.string()}),returns:s.object({tokenCount:s.number().int()})})}function ED(){return new Rt().addRpcEndpoint("getLocalFileAbsolutePath",{parameter:s.object({fileName:s.string()}),returns:s.object({path:s.string()})}).addRpcEndpoint("uploadFileBase64",{parameter:s.object({name:s.string(),contentBase64:s.string()}),returns:s.object({identifier:s.string(),fileType:of,sizeBytes:s.number().int()})}).addChannelEndpoint("retrieve",{creationParameter:s.object({query:s.string(),fileIdentifiers:s.array(s.string()),config:X}),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("stop")})]),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("onFileProcessList"),indices:s.array(s.number().int())}),s.object({type:s.literal("onFileProcessingStart"),index:s.number().int()}),s.object({type:s.literal("onFileProcessingEnd"),index:s.number().int()}),s.object({type:s.literal("onFileProcessingStepStart"),index:s.number().int(),step:Io}),s.object({type:s.literal("onFileProcessingStepProgress"),index:s.number().int(),step:Io,progress:s.number()}),s.object({type:s.literal("onFileProcessingStepEnd"),index:s.number().int(),step:Io}),s.object({type:s.literal("onSearchingStart")}),s.object({type:s.literal("onSearchingEnd")}),s.object({type:s.literal("result"),result:K0})])}).addChannelEndpoint("parseDocument",{creationParameter:s.object({fileIdentifier:s.string(),parseOpts:gf}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("parserLoaded"),parser:Zo}),s.object({type:s.literal("progress"),progress:s.number()}),s.object({type:s.literal("result"),content:s.string(),parser:Zo})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addRpcEndpoint("getDocumentParsingLibrary",{parameter:s.object({fileIdentifier:s.string()}),returns:s.object({library:s.string(),version:s.string()})})}function xD(){return vh(Go,Cf).addChannelEndpoint("predict",{creationParameter:s.object({modelSpecifier:Ye,history:dr,predictionConfigStack:Ki,fuzzyPresetIdentifier:s.string().optional(),ignoreServerSessionConfig:s.boolean().optional()}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("fragment"),fragment:Pf,logprobs:s.array(s.array(s.object({text:s.string(),logprob:s.number()}))).optional()}),s.object({type:s.literal("promptProcessingProgress"),progress:s.number()}),s.object({type:s.literal("toolCallGenerationStart"),toolCallId:s.string().optional()}),s.object({type:s.literal("toolCallGenerationNameReceived"),name:s.string()}),s.object({type:s.literal("toolCallGenerationArgumentFragmentGenerated"),content:s.string()}),s.object({type:s.literal("toolCallGenerationEnd"),toolCallRequest:An,rawContent:s.string().optional()}),s.object({type:s.literal("toolCallGenerationFailed"),error:xe,rawContent:s.string().optional()}),s.object({type:s.literal("success"),stats:Af,modelInfo:Go,loadModelConfig:X,predictionConfig:X})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addRpcEndpoint("applyPromptTemplate",{parameter:s.object({specifier:Ye,history:dr,predictionConfigStack:Ki,opts:wf}),returns:s.object({formatted:s.string()})}).addRpcEndpoint("tokenize",{parameter:s.object({specifier:Ye,inputString:s.string()}),returns:s.object({tokens:s.array(s.number())})}).addRpcEndpoint("countTokens",{parameter:s.object({specifier:Ye,inputString:s.string()}),returns:s.object({tokenCount:s.number().int()})}).addRpcEndpoint("preloadDraftModel",{parameter:s.object({specifier:Ye,draftModelKey:s.string()}),returns:s.void()})}function kD(){return new Rt().addChannelEndpoint("startToolUseSession",{creationParameter:s.object({pluginIdentifier:s.string(),pluginConfigSpecifier:Fd}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("sessionReady"),toolDefinitions:s.array(ar)}),s.object({type:s.literal("toolCallComplete"),callId:s.number(),result:Ce}),s.object({type:s.literal("toolCallError"),callId:s.number(),error:xe}),s.object({type:s.literal("toolCallStatus"),callId:s.number(),statusText:s.string()}),s.object({type:s.literal("toolCallWarn"),callId:s.number(),warnText:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("callTool"),callId:s.number(),name:s.string(),arguments:Ce}),s.object({type:s.literal("abortToolCall"),callId:s.number()}),s.object({type:s.literal("discardSession")})])}).addChannelEndpoint("generateWithGenerator",{creationParameter:s.object({pluginIdentifier:s.string(),pluginConfigSpecifier:Fd,tools:s.array(ar),history:dr}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("fragment"),fragment:Pf}),s.object({type:s.literal("promptProcessingProgress"),progress:s.number()}),s.object({type:s.literal("toolCallGenerationStart"),toolCallId:s.string().optional()}),s.object({type:s.literal("toolCallGenerationNameReceived"),name:s.string()}),s.object({type:s.literal("toolCallGenerationArgumentFragmentGenerated"),content:s.string()}),s.object({type:s.literal("toolCallGenerationEnd"),toolCallRequest:An}),s.object({type:s.literal("toolCallGenerationFailed")}),s.object({type:s.literal("success")})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addChannelEndpoint("registerDevelopmentPlugin",{creationParameter:s.object({manifest:Ja}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("ready"),clientIdentifier:s.string(),clientPasskey:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("end")})])}).addRpcEndpoint("reindexPlugins",{parameter:s.void(),returns:s.void()}).addChannelEndpoint("setPromptPreprocessor",{creationParameter:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("preprocess"),taskId:s.string(),input:ur,config:X,pluginConfig:X,globalPluginConfig:X,workingDirectoryPath:s.string().nullable(),enabledPluginInfos:s.array(Pd),pci:s.string(),token:s.string()}),s.object({type:s.literal("abort"),taskId:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("complete"),taskId:s.string(),processed:ur}),s.object({type:s.literal("aborted"),taskId:s.string()}),s.object({type:s.literal("error"),taskId:s.string(),error:xe})])}).addChannelEndpoint("setPredictionLoopHandler",{creationParameter:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("handlePredictionLoop"),taskId:s.string(),config:X,pluginConfig:X,globalPluginConfig:X,workingDirectoryPath:s.string().nullable(),enabledPluginInfos:s.array(Pd),pci:s.string(),token:s.string()}),s.object({type:s.literal("abort"),taskId:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("complete"),taskId:s.string()}),s.object({type:s.literal("aborted"),taskId:s.string()}),s.object({type:s.literal("error"),taskId:s.string(),error:xe})])}).addChannelEndpoint("setToolsProvider",{creationParameter:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("initSession"),pluginConfig:X,globalPluginConfig:X,workingDirectoryPath:s.string().nullable(),sessionId:s.string()}),s.object({type:s.literal("discardSession"),sessionId:s.string()}),s.object({type:s.literal("callTool"),sessionId:s.string(),callId:s.string(),toolName:s.string(),parameters:Ce}),s.object({type:s.literal("abortToolCall"),sessionId:s.string(),callId:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("sessionInitialized"),sessionId:s.string(),toolDefinitions:s.array(ar)}),s.object({type:s.literal("sessionInitializationFailed"),sessionId:s.string(),error:xe}),s.object({type:s.literal("toolCallComplete"),sessionId:s.string(),callId:s.string(),result:Ce}),s.object({type:s.literal("toolCallError"),sessionId:s.string(),callId:s.string(),error:xe}),s.object({type:s.literal("toolCallStatus"),sessionId:s.string(),callId:s.string(),statusText:s.string()}),s.object({type:s.literal("toolCallWarn"),sessionId:s.string(),callId:s.string(),warnText:s.string()})])}).addChannelEndpoint("setGenerator",{creationParameter:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("generate"),taskId:s.string(),input:dr,pluginConfig:X,globalPluginConfig:X,toolDefinitions:s.array(ar),workingDirectoryPath:s.string().nullable()}),s.object({type:s.literal("abort"),taskId:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("complete"),taskId:s.string()}),s.object({type:s.literal("aborted"),taskId:s.string()}),s.object({type:s.literal("error"),taskId:s.string(),error:xe}),s.object({type:s.literal("fragmentGenerated"),taskId:s.string(),content:s.string(),opts:Tf}),s.object({type:s.literal("toolCallGenerationStarted"),taskId:s.string(),toolCallId:s.string().optional()}),s.object({type:s.literal("toolCallGenerationNameReceived"),taskId:s.string(),toolName:s.string()}),s.object({type:s.literal("toolCallGenerationArgumentFragmentGenerated"),taskId:s.string(),content:s.string()}),s.object({type:s.literal("toolCallGenerationEnded"),taskId:s.string(),toolCallRequest:An}),s.object({type:s.literal("toolCallGenerationFailed"),taskId:s.string(),error:xe})])}).addRpcEndpoint("processingHandleUpdate",{parameter:s.object({pci:s.string(),token:s.string(),update:A0}),returns:s.void()}).addRpcEndpoint("processingHandleRequest",{parameter:s.object({pci:s.string(),token:s.string(),request:O0}),returns:s.object({response:B0})}).addRpcEndpoint("processingPullHistory",{parameter:s.object({pci:s.string(),token:s.string(),includeCurrent:s.boolean()}),returns:dr}).addRpcEndpoint("processingGetOrLoadTokenSource",{parameter:s.object({pci:s.string(),token:s.string()}),returns:s.object({tokenSourceIdentifier:L0})}).addRpcEndpoint("processingHasStatus",{parameter:s.object({pci:s.string(),token:s.string()}),returns:s.boolean()}).addRpcEndpoint("processingNeedsNaming",{parameter:s.object({pci:s.string(),token:s.string()}),returns:s.boolean()}).addRpcEndpoint("processingSuggestName",{parameter:s.object({pci:s.string(),token:s.string(),name:s.string()}),returns:s.void()}).addRpcEndpoint("processingSetSenderName",{parameter:s.object({pci:s.string(),token:s.string(),name:s.string()}),returns:s.void()}).addRpcEndpoint("setConfigSchematics",{parameter:s.object({schematics:Id}),returns:s.void()}).addRpcEndpoint("setGlobalConfigSchematics",{parameter:s.object({schematics:Id}),returns:s.void()}).addRpcEndpoint("pluginInitCompleted",{parameter:s.void(),returns:s.void()})}function FD(){return new Rt().addRpcEndpoint("searchModels",{parameter:s.object({opts:Gf}),returns:s.object({results:s.array(Z0)})}).addRpcEndpoint("getModelDownloadOptions",{parameter:s.object({modelSearchResultIdentifier:Zf}),returns:s.object({results:s.array(W0)})}).addChannelEndpoint("downloadModel",{creationParameter:s.object({downloadIdentifier:s.string()}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("downloadProgress"),update:Ro}),s.object({type:s.literal("startFinalizing")}),s.object({type:s.literal("success"),defaultIdentifier:s.string()})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addChannelEndpoint("downloadArtifact",{creationParameter:s.object({artifactOwner:Pn,artifactName:Tn,revisionNumber:s.number().int().nullable(),path:s.string()}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("downloadProgress"),update:Ro}),s.object({type:s.literal("startFinalizing")}),s.object({type:s.literal("success")})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addRpcEndpoint("installPluginDependencies",{parameter:s.object({pluginFolder:s.string()}),returns:s.void()}).addRpcEndpoint("getLocalArtifactFiles",{parameter:s.object({path:s.string()}),returns:s.object({fileList:q0})}).addChannelEndpoint("pushArtifact",{creationParameter:s.object({path:s.string(),description:s.string().max(1e3).optional(),makePrivate:s.boolean().optional(),writeRevision:s.boolean().optional(),overrides:Ce.optional()}),toServerPacket:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("message"),message:s.string()})])}).addChannelEndpoint("ensureAuthenticated",{creationParameter:s.void(),toServerPacket:s.void(),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("authenticationUrl"),url:s.string()}),s.object({type:s.literal("authenticated")})])}).addRpcEndpoint("loginWithPreAuthenticatedKeys",{parameter:s.object({keyId:s.string(),publicKey:s.string(),privateKey:s.string()}),returns:s.object({userName:s.string()})}).addChannelEndpoint("createArtifactDownloadPlan",{creationParameter:s.object({owner:Pn,name:Tn}),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")}),s.object({type:s.literal("commit")})]),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("planUpdated"),plan:Rd}),s.object({type:s.literal("planReady"),plan:Rd}),s.object({type:s.literal("downloadProgress"),update:Ro}),s.object({type:s.literal("startFinalizing")}),s.object({type:s.literal("success")})])})}function PD(){return new Rt().addRpcEndpoint("listDownloadedModels",{parameter:s.void(),returns:s.array(N0)}).addChannelEndpoint("alive",{creationParameter:s.void(),toServerPacket:s.void(),toClientPacket:s.void()}).addRpcEndpoint("notify",{parameter:sf,returns:s.void()}).addRpcEndpoint("version",{parameter:s.void(),returns:s.object({version:s.string(),build:s.number()})}).addRpcEndpoint("setExperimentFlag",{parameter:s.object({code:s.string(),value:s.boolean()}),returns:s.void()}).addRpcEndpoint("getExperimentFlags",{parameter:s.void(),returns:s.array(s.string())}).addRpcEndpoint("startHttpServer",{parameter:s.object({port:s.number().int().min(1).max(65535).optional(),cors:s.boolean().optional()}),returns:s.void()}).addRpcEndpoint("stopHttpServer",{parameter:s.void(),returns:s.void()})}function TD(r,e,t,n){let[i,o]=mt.create(),[a,l]=mt.create(),c=e.getApiIpcTunnel(r,{authVersion:1,clientIdentifier:t,clientPasskey:n},o,l);return ma.createFactory(i,a,c)}function AD(r,e,t,n){return pa.createAuthenticatedWsClientTransportFactory({url:Promise.resolve(e).then(i=>`${i}/${r}`),clientIdentifier:t,clientPasskey:n})}function RD(r,e,t,n,i,o,{errorDeserializer:a,verboseErrorMessage:l}={}){let c=bh();return c!==null?(e!==void 0&&o.debug("Ignoring wsAddress parameter when constructing the client because the client is running in a hosted environment. This is not an error."),new Xi(r,TD(t,c,n,i),{parentLogger:o,errorDeserializer:a,verboseErrorMessage:l})):new Xi(r,AD(t,e,n,i),{parentLogger:o,errorDeserializer:a,verboseErrorMessage:l})}var ga=class{constructor(e,t,n){this.diagnosticsPort=e,this.validator=t,this.logger=new H("Diagnostics",n)}unstable_streamLogs(e){let t=A(1);this.validator.validateMethodParamOrThrow("client.diagnostics","unstable_streamLogs","listener",s.function(),e,t);let n=this.diagnosticsPort.createChannel("streamLogs",void 0,void 0,{stack:t}),i=n.onMessage.subscribe(o=>{o.type==="log"&&e(o.log)});return()=>{i(),n.send({type:"stop"})}}};function ID(r){return s.object({identifier:s.string().optional(),config:r.optional(),signal:s.instanceof(AbortSignal).optional(),ttl:s.number().optional(),verbose:s.union([s.boolean(),cv]).optional(),onProgress:s.function().optional()})}var es=class{getLoadModelOptsSchema(){return this.loadModelOptsSchema===null&&(this.loadModelOptsSchema=ID(this.loadModelConfigSchema)),this.loadModelOptsSchema}constructor(e,t,n,i){this.client=e,this.port=t,this.logger=n,this.validator=i,this.loadModelOptsSchema=null}async load(e,t={}){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`,"load",["modelKey","opts"],[Vr,this.getLoadModelOptsSchema()],[e,t],n);let{identifier:i,signal:o,verbose:a="info",config:l,onProgress:c}=t,u=0,{promise:h,resolve:f,reject:d}=ee(),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,...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`
|
|
192
311
|
Verbose logging is enabled. To hide progress logs, set the "verbose" option to false in
|
|
193
312
|
client.llm.load.
|
|
194
|
-
`);let g=e,
|
|
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`
|
|
195
314
|
Multiple models found for key ${e}:
|
|
196
315
|
|
|
197
|
-
${
|
|
316
|
+
${b.ambiguous.map(D=>` - ${D}`).join(`
|
|
198
317
|
`)}
|
|
199
318
|
|
|
200
319
|
Using the first one.
|
|
@@ -202,176 +321,176 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
202
321
|
Start loading model ${g}...
|
|
203
322
|
`);break}case"success":{a&&this.logger.logAtLevel(p,j`
|
|
204
323
|
Successfully loaded model ${g} in ${Date.now()-m}ms
|
|
205
|
-
`),f(this.createDomainSpecificModel(this.port,
|
|
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`
|
|
206
325
|
Model path should not contain backslashes, even if you are on Windows. Use forward
|
|
207
326
|
slashes instead.
|
|
208
|
-
`,
|
|
209
|
-
Unloading other JIT model ${
|
|
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`
|
|
328
|
+
Unloading other JIT model ${y.info.modelKey}. (You can disable this behavior
|
|
210
329
|
by going to LM Studio -> Settings -> Developer -> Turn OFF JIT models auto-evict)
|
|
211
330
|
`);break}case"startLoading":{a&&(this.logger.logAtLevel(p,j`
|
|
212
331
|
Verbose logging is enabled. To hide progress logs, set the "verbose" option to
|
|
213
332
|
false in .model().
|
|
214
333
|
`),this.logger.logAtLevel(p,j`
|
|
215
334
|
Model ${e} is not loaded. Start loading...
|
|
216
|
-
`));break}case"loadProgress":{let{progress:
|
|
217
|
-
Successfully loaded model ${
|
|
218
|
-
`),f(this.createDomainSpecificModel(this.port,
|
|
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
|
+
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`
|
|
219
338
|
Your current JavaScript environment does not support reading files. If you can read the file
|
|
220
339
|
using other methods, please use "prepareImageBase64".
|
|
221
|
-
`);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:
|
|
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`
|
|
222
341
|
Your current JavaScript environment does not support reading files. If you can read the file
|
|
223
342
|
using other methods, please use "prepareFileBase64".
|
|
224
|
-
`);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:
|
|
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`
|
|
225
344
|
Found ${d.length} files need processing:
|
|
226
|
-
${d.map(
|
|
227
|
-
`);break;case"onFileProcessingStart":{if(d===null)throw new Error("onFileProcessList must be called before onFileProcessingStart");let
|
|
228
|
-
Start processing file: ${
|
|
345
|
+
${d.map(C=>C.name).join(", ")}
|
|
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`
|
|
347
|
+
Start processing file: ${C.name}
|
|
229
348
|
(${S.index+1}/${d.length})
|
|
230
|
-
`));break}case"onFileProcessingEnd":{if(d===null)throw new Error("onFileProcessList must be called before onFileProcessingEnd");let
|
|
231
|
-
File processed: ${
|
|
349
|
+
`));break}case"onFileProcessingEnd":{if(d===null)throw new Error("onFileProcessList must be called before onFileProcessingEnd");let C=u(S.index);L(i,"onFileProcessingEnd",n.onFileProcessingEnd,[C,d.indexOf(C),d]),c&&i.logAtLevel(l,j`
|
|
350
|
+
File processed: ${C.name}.
|
|
232
351
|
Time took: ${Date.now()-p[S.index]}ms
|
|
233
|
-
`);break}case"onFileProcessingStepStart":
|
|
234
|
-
> ${
|
|
235
|
-
`;
|
|
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)}%
|
|
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`
|
|
236
355
|
Finished searching in the vector database.
|
|
237
356
|
Time took: ${Date.now()-m}ms
|
|
238
|
-
`);break;case"result":{
|
|
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+=`
|
|
239
358
|
|
|
240
359
|
|
|
241
360
|
`+I.default.bgWhite.black(" (!) SUGGESTION ")+`
|
|
242
361
|
|
|
243
|
-
`+I.default.white(
|
|
362
|
+
`+I.default.white(t.suggestion)),t.cause!==void 0&&(r+=`
|
|
244
363
|
|
|
245
364
|
|
|
246
365
|
`+I.default.bgWhite.black(" (X) CAUSE ")+`
|
|
247
366
|
|
|
248
|
-
`+I.default.gray(
|
|
249
|
-
`);return
|
|
250
|
-
... (and ${e-
|
|
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(`
|
|
368
|
+
`);return t.length<e&&(r+=I.default.gray(`
|
|
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`
|
|
251
370
|
Here are your available models:
|
|
252
371
|
|
|
253
|
-
${
|
|
372
|
+
${eC(t,r)}
|
|
254
373
|
|
|
255
374
|
Run
|
|
256
375
|
|
|
257
376
|
${I.default.yellowBright("lms ls")}
|
|
258
377
|
|
|
259
378
|
to see a full list of loadable models
|
|
260
|
-
`,n));function
|
|
261
|
-
`);return
|
|
262
|
-
... (and ${e-
|
|
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(`
|
|
380
|
+
`);return t.length<e&&(r+=I.default.gray(`
|
|
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`
|
|
263
382
|
Here are your loaded models:
|
|
264
383
|
|
|
265
|
-
${
|
|
384
|
+
${Xp(t,r)}
|
|
266
385
|
|
|
267
386
|
Run
|
|
268
387
|
|
|
269
388
|
${I.default.yellowBright("lms ps")}
|
|
270
389
|
|
|
271
390
|
to see a full list of loaded models
|
|
272
|
-
`,n));
|
|
391
|
+
`,n));wn("generic.specificModelUnloaded",(t,e)=>Ee(I.default.bgRed.white(j`
|
|
273
392
|
This model has already been unloaded.
|
|
274
|
-
`),e));function
|
|
275
|
-
The model must be ${I.default.yellowBright(
|
|
276
|
-
`),
|
|
277
|
-
`)}
|
|
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))}
|
|
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
|
+
`)}wn("generic.noModelMatchingQuery",({loadedModelsSample:t,totalLoadedModels:e,query:r},n)=>Ee(j`
|
|
278
397
|
${I.default.bgRed.white(" No loaded model satisfies all requirements specified in the query. ")}
|
|
279
398
|
|
|
280
399
|
Loaded Models:
|
|
281
400
|
|
|
282
|
-
${
|
|
401
|
+
${Xp(t,e)}
|
|
283
402
|
|
|
284
403
|
Your query:
|
|
285
404
|
|
|
286
|
-
${
|
|
405
|
+
${tC(r)}
|
|
287
406
|
|
|
288
407
|
Run
|
|
289
408
|
|
|
290
409
|
${I.default.yellowBright("lms ps")}
|
|
291
410
|
|
|
292
411
|
to see a full list of loaded models with details
|
|
293
|
-
`,n));
|
|
412
|
+
`,n));wn("generic.domainMismatch",({actualDomain:t,expectedDomain:e,path:r},n)=>Ee(j`
|
|
294
413
|
${I.default.bgRed.white(" Model has wrong domain. ")}
|
|
295
414
|
|
|
296
|
-
Expecting ${I.default.greenBright(
|
|
297
|
-
`,n));function
|
|
298
|
-
`);return
|
|
299
|
-
... (and ${e-
|
|
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(`
|
|
417
|
+
`);return t.length<e&&(r+=I.default.gray(`
|
|
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`
|
|
300
419
|
Here are your available presets:
|
|
301
420
|
|
|
302
|
-
${
|
|
421
|
+
${rC(e,r)}
|
|
303
422
|
|
|
304
423
|
Note: To specify a preset in the SDK, you need to use its identifier (in parentheses). You
|
|
305
424
|
can get a preset's identifier by right-clicking on it and then select "Copy Preset
|
|
306
425
|
Identifier".
|
|
307
|
-
`));function
|
|
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`
|
|
308
427
|
This tool call guard has already set a result previously (${this.resultContainer[0].type}).
|
|
309
428
|
You cannot set a result more than once.
|
|
310
|
-
`,
|
|
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`
|
|
311
430
|
Duplicate tool (${g.name}) found in the tools array. The last tool with the same name
|
|
312
431
|
will be used.
|
|
313
|
-
`,m.set(g.name,g);do{let g=!0;
|
|
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`
|
|
314
433
|
The "handleInvalidToolRequest" callback has returned a result, but the tool request has
|
|
315
434
|
completely failed to parse, thus LM Studio cannot provide the result to the tool call.
|
|
316
435
|
Please avoid returning a result when the second parameter of the callback is undefined.
|
|
317
436
|
See the documentation for "handleInvalidToolRequest" for more information.
|
|
318
|
-
`:(
|
|
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`
|
|
319
438
|
The \`guardToolCall\` handler must call one of the methods on the controller
|
|
320
439
|
to allow or deny the tool call.
|
|
321
|
-
`,n);let
|
|
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`
|
|
322
441
|
{% for message in messages %}{{ message['content'] }}{% endfor %}
|
|
323
|
-
`,ns=class extends ts{constructor(e,t,n,i=new H("LLMModel")){super(e,t),this.validator=n,this.logger=i,this.internalKVConfigStack={layers:[]},this.internalIgnoreServerSessionConfig=void 0}internalPredict(e,t,n,i,o,a,l){let c=!1,u=!1,h=null,f=!1,d=!1,p=this.port.createChannel("predict",{modelSpecifier:this.specifier,history:e,predictionConfigStack:t,fuzzyPresetIdentifier:i.preset,ignoreServerSessionConfig:this.internalIgnoreServerSessionConfig},m=>{switch(m.type){case"fragment":{u||(u=!0,B(this.logger,"onFirstToken",i.onFirstToken,[])),B(this.logger,"onFragment",i.onPredictionFragment,[m.fragment]),o(m.fragment);break}case"promptProcessingProgress":{B(this.logger,"onPromptProcessingProgress",i.onPromptProcessingProgress,[m.progress]);break}case"toolCallGenerationStart":{h===null?h=0:h++,f=!1,d=!1,B(this.logger,"onToolCallGenerationStart",i.onToolCallRequestStart,[h,{toolCallId:m.toolCallId}]);break}case"toolCallGenerationNameReceived":{f=!0,B(this.logger,"onToolCallGenerationNameReceived",i.onToolCallRequestNameReceived,[h??-1,m.name]);break}case"toolCallGenerationArgumentFragmentGenerated":{d=!0,B(this.logger,"onToolCallGenerationArgumentFragmentGenerated",i.onToolCallRequestArgumentFragmentGenerated,[h??-1,m.content]);break}case"toolCallGenerationEnd":{f||B(this.logger,"onToolCallGenerationNameReceived",i.onToolCallRequestNameReceived,[h??-1,m.toolCallRequest.name]),d||B(this.logger,"onToolCallGenerationArgumentFragmentGenerated",i.onToolCallRequestArgumentFragmentGenerated,[h??-1,JSON.stringify(m.toolCallRequest.arguments??{},null,2)]),B(this.logger,"onToolCallGenerationEnd",i.onToolCallRequestEnd,[h??-1,{toolCallRequest:m.toolCallRequest,rawContent:m.rawContent}]);break}case"toolCallGenerationFailed":{let g=new cr(Gi(m.error).message,m.rawContent);B(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 t;typeof e.structured?.parse=="function"?t={type:"json",jsonSchema:xi(e.structured)}:t=e.structured;let n={...e,structured:t};return _v(n)}createZodParser(e){return t=>{try{return e.parse(JSON.parse(t))}catch(n){throw new Error("Failed to parse structured output: "+JSON.stringify(t),{cause:n})}}}complete(e,t={}){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow("model","complete",["prompt","opts"],[s.string(),_h],[e,t],n);let[i,o]=Eh(t),[a,l]=mt.create();o.signal!==void 0&&(o.signal.aborted?l():o.signal.addEventListener("abort",()=>{l()},{once:!0}));let c=yr.safeParse(i.structured),{ongoingPrediction:u,finished:h,failed:f,push:d}=rs.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:zn.buildPartialConfig({promptTemplate:{type:"jinja",jinjaPromptTemplate:{template:KD},stopStrings:[]}})}]},a,o,p=>d(p),(p,m,g,b)=>h(p,m,g,b),p=>f(p)),u}resolveCompletionContext(e){return{messages:[{role:"user",content:[{type:"text",text:e}]}]}}respond(e,t={}){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow("model","respond",["chat","opts"],[Zr,VD],[e,t],n);let[i,o]=mt.create(),[a,l,c]=WD(t);l.signal!==void 0&&(l.signal.aborted?o():l.signal.addEventListener("abort",()=>{o()},{once:!0}));let u=yr.safeParse(a.structured),{ongoingPrediction:h,finished:f,failed:d,push:p}=rs.create(o,u.success?this.createZodParser(u.data):null);return this.internalPredict(gt.from(e)._internalGetData(),Oo(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig(a)),i,l,m=>p(m),(m,g,b,y)=>f(m,g,b,y),m=>d(m)),h.then(m=>{B(this.logger,"onMessage",c.onMessage,[le.create("assistant",m.content)])},()=>{}),h}async act(e,t,n={}){let i=performance.now(),o=A(1);[e,n]=this.validator.validateMethodParamsOrThrow("model","act",["chat","opts"],[Zr,ZD],[e,n],o);let[a,{preset:l,...c}]=GD(n);if(a.structured!==void 0&&a.structured.type!=="none"&&t.length>0)throw pe("Structured output is currently not supported in .act() when there are tools.",o);if(a.structured!==void 0&&a.structured.parse!==void 0)throw pe("zod schema is not supported in .act().",o);if(a.rawTools!==void 0)throw pe("`rawTools` is not supported in act. Use `tools` instead",o);let u;t.length===0?u={type:"none"}:u={type:"toolArray",tools:t.map(ul)};let h=Oo(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig({...a,rawTools:u})),f=Oo(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig({...a,rawTools:{type:"none"}}));return await Ch(e,t,c,o,this.logger,i,async({allowTools:d,history:p,signal:m,handleFragment:g,handlePromptProcessingProgress:b,handleToolCallGenerationStart:y,handleToolCallGenerationNameReceived:D,handleToolCallGenerationArgumentFragmentGenerated:v,handleToolCallGenerationEnd:S,handleToolCallGenerationFailed:_,handlePredictionEnd:k,handleError:x})=>{let z=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":{b(w.progress);break}case"toolCallGenerationStart":{y(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":{_(Gi(w.error),w.rawContent);break}case"success":{k({stats:w.stats,modelInfo:w.modelInfo,loadModelConfig:w.loadModelConfig,predictionConfig:w.predictionConfig});break}}},{stack:o});m.aborted?z.send({type:"cancel"}):m.addEventListener("abort",()=>{z.send({type:"cancel"})},{once:!0}),z.onError.subscribeOnce(x)},({endPacket:d,content:p,nonReasoningContent:m,reasoningContent:g,predictionsPerformed:b})=>new Ln(p,g,m,d.stats,d.modelInfo,b,d.loadModelConfig,d.predictionConfig))}async getContextLength(){let e=A(1),t=await this.getLoadConfig(e);return qn.access(t,"contextLength")}async applyPromptTemplate(e,t={}){let n=A(1);return[e,t]=this.validator.validateMethodParamsOrThrow("model","applyPromptTemplate",["history","opts"],[Zr,wf],[e,t],n),(await this.port.callRpc("applyPromptTemplate",{specifier:this.specifier,history:gt.from(e)._internalGetData(),predictionConfigStack:this.internalKVConfigStack,opts:t},{stack:n})).formatted}async tokenize(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("model","tokenize","inputString",s.string().or(s.array(s.string())),e,t),Array.isArray(e)?(await Promise.all(e.map(n=>this.port.callRpc("tokenize",{specifier:this.specifier,inputString:n},{stack:t})))).map(n=>n.tokens):(await this.port.callRpc("tokenize",{specifier:this.specifier,inputString:e},{stack:t})).tokens}async countTokens(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("model","countTokens","inputString",s.string(),e,t),(await this.port.callRpc("countTokens",{specifier:this.specifier,inputString:e},{stack:t})).tokenCount}async unstable_preloadDraftModel(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("model","unstable_preloadDraftModel","draftModelKey",s.string(),e,t),await this.port.callRpc("preloadDraftModel",{specifier:this.specifier,draftModelKey:e},{stack:t})}},xa=class extends ns{constructor(e,t,n,i=new H("LLM")){let o={type:"instanceReference",instanceReference:t.instanceReference};super(e,o,n,i),this.identifier=t.identifier,this.path=t.path,this.modelKey=t.modelKey,this.format=t.format,this.displayName=t.displayName,this.sizeBytes=t.sizeBytes,this.vision=t.vision,this.trainedForToolUse=t.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 t=A(1);throw pe("This model has already been unloaded",t)}return e}},ka=class extends es{constructor(){super(...arguments),this.namespace="llm",this.defaultLoadConfig={},this.loadModelConfigSchema=e0}loadConfigToKVConfig(e){return wv.buildPartialConfig({contextLength:e.contextLength,"llama.evalBatchSize":e.evalBatchSize,"llama.acceleration.offloadRatio":e.gpu?.ratio,numCpuExpertLayersRatio:e.gpu?.numCpuExpertLayersRatio,"load.gpuSplitConfig":yf(e.gpu),"llama.flashAttention":e.flashAttention,"llama.ropeFrequencyBase":wn(e.ropeFrequencyBase,0,0),"llama.ropeFrequencyScale":wn(e.ropeFrequencyScale,0,0),"llama.keepModelInMemory":e.keepModelInMemory,seed:wn(e.seed,-1,0),"llama.useFp16ForKVCache":e.useFp16ForKVCache,"llama.tryMmap":e.tryMmap,numExperts:e.numExperts,"llama.kCacheQuantizationType":Gd({value:e.llamaKCacheQuantizationType,falseDefault:"f16"}),"llama.vCacheQuantizationType":Gd({value:e.llamaVCacheQuantizationType,falseDefault:"f16"})})}createDomainSpecificModel(e,t,n,i){return new xa(e,t,n,i)}createDomainDynamicHandle(e,t,n,i){return new ns(e,t,n,i)}},is=class{constructor(e,t,n,i){this.content=e,this.reasoningContent=t,this.nonReasoningContent=n,this.pluginIdentifier=i}},Fa=class r extends Hi{async collect(e){let t=e.map(({content:o})=>o).join(""),n=e.filter(({isStructural:o})=>!o).filter(({reasoningType:o})=>o==="reasoning").map(({content:o})=>o).join(""),i=e.filter(({isStructural:o})=>!o).filter(({reasoningType:o})=>o==="none").map(({content:o})=>o).join("");return new is(t,n,i,this.pluginIdentifier)}constructor(e,t){super(),this.pluginIdentifier=e,this.onCancel=t}static create(e,t){let n=new r(e,t);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()}},HD=s.object({onFirstToken:s.function().optional(),onPredictionFragment:s.function().optional(),onMessage:s.function().optional(),signal:s.instanceof(AbortSignal).optional(),pluginConfig:X.optional(),workingDirectory:s.string().optional()}),JD=Sh.extend({pluginConfig:X.optional(),workingDirectory:s.string().optional()}),ss=class{constructor(e,t,n,i,o=new H("LLMGeneratorHandle")){this.port=e,this.pluginIdentifier=t,this.validator=n,this.associatedPredictionProcess=i,this.logger=o,this.identifier=this.pluginIdentifier}getPluginConfigSpecifier(e,t,n){if(this.associatedPredictionProcess===null)return{type:"direct",config:e??Yf,workingDirectoryPath:t??void 0};if(e!==void 0)throw gr("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 $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`
|
|
324
443
|
You cannot provide a plugin config to the generator handle when it is associated with a
|
|
325
444
|
prediction process. The plugin config that was configured for the prediction process will
|
|
326
445
|
be used instead.
|
|
327
446
|
|
|
328
447
|
If you want to use a different plugin config, you will need to create a separate
|
|
329
448
|
GeneratorHandle instead.
|
|
330
|
-
`,n);if(
|
|
449
|
+
`,n);if(r!==void 0)throw Ir("Cannot use working directory with prediction process",j`
|
|
331
450
|
You cannot provide a working directory to the generator handle when it is associated with
|
|
332
451
|
a prediction process. The working directory that was configured for the prediction process
|
|
333
452
|
will be used instead.
|
|
334
453
|
|
|
335
454
|
If you want to use a different working directory, you will need to create a separate
|
|
336
455
|
GeneratorHandle instead.
|
|
337
|
-
`,n);return{type:"predictionProcess",pci:this.associatedPredictionProcess.pci,token:this.associatedPredictionProcess.token}}respond(e,t={}){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle","respond",["chat","opts"],[Zr,HD],[e,t],n);let{onFirstToken:i,onPredictionFragment:o,onMessage:a,signal:l,pluginConfig:c,workingDirectory:u}=t,h=!1,f=!1,d=new qo;l!==void 0&&(l.aborted?d.cancel():l.addEventListener("abort",()=>d.cancel(),{once:!0}));let{ongoingPrediction:p,finished:m,failed:g,push:b}=Fa.create(this.pluginIdentifier,()=>{d.cancel()}),y=this.port.createChannel("generateWithGenerator",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.getPluginConfigSpecifier(c,u,n),tools:[],history:gt.from(e)._internalGetData()},D=>{switch(D.type){case"fragment":{f||(f=!0,B(this.logger,"onFirstToken",i,[])),B(this.logger,"onPredictionFragment",o,[D.fragment]),b(D.fragment);break}case"success":{h=!0,m();break}}},{stack:n});return y.onError.subscribeOnce(D=>{h||(h=!0,g(D))}),d.subscribeOnce(()=>{h||y.send({type:"cancel"})}),p.then(D=>{B(this.logger,"onMessage",a,[le.create("assistant",D.content)])},()=>{}),p}async act(e,t,n={}){let i=performance.now(),o=A(1);[e,n]=this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle","act",["chat","opts"],[Zr,JD],[e,n],o);let{pluginConfig:a,workingDirectory:l,...c}=n,u=t.map(ul);return await Ch(e,t,c,o,this.logger,i,async({allowTools:h,history:f,signal:d,handleFragment:p,handlePromptProcessingProgress:m,handleToolCallGenerationStart:g,handleToolCallGenerationNameReceived:b,handleToolCallGenerationArgumentFragmentGenerated:y,handleToolCallGenerationEnd:D,handleToolCallGenerationFailed:v,handlePredictionEnd:S,handleError:_})=>{let k=this.port.createChannel("generateWithGenerator",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.getPluginConfigSpecifier(a,l,o),tools:h?u:[],history:f},x=>{switch(x.type){case"fragment":{p(x.fragment);break}case"promptProcessingProgress":{m(x.progress);break}case"toolCallGenerationStart":{g(x.toolCallId);break}case"toolCallGenerationNameReceived":{b(x.name);break}case"toolCallGenerationArgumentFragmentGenerated":{y(x.content);break}case"toolCallGenerationEnd":{D(x.toolCallRequest,void 0);break}case"toolCallGenerationFailed":{v(new Error("Tool call generation failed"),void 0);break}case"success":{S(void 0);break}}},{stack:o});d.aborted?k.send({type:"cancel"}):d.addEventListener("abort",()=>{k.send({type:"cancel"})},{once:!0}),k.onError.subscribeOnce(_)},({content:h,nonReasoningContent:f,reasoningContent:d})=>new is(h,d,f,this.pluginIdentifier))}},YD=s.function(),Nn=class{constructor(e,t,n,i,o){this.client=e,this.abortSignal=t,this.pluginConfig=n,this.globalPluginConfig=i,this.workingDirectoryPath=o}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})}},Pa=class extends Nn{constructor(e,t,n,i,o,a,l,c){super(e,o,t,n,i),this.toolDefinitions=a,this.connector=l,this.validator=c}getToolDefinitions(){return this.toolDefinitions}fragmentGenerated(e,t={}){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow("GeneratorController","fragmentGenerated",["content","opts"],[s.string(),Tf],[e,t],n),this.connector.fragmentGenerated(e,t)}toolCallGenerationStarted({toolCallId:e}={}){this.connector.toolCallGenerationStarted(e)}toolCallGenerationNameReceived(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationNameReceived","toolName",s.string(),e,t),this.connector.toolCallGenerationNameReceived(e)}toolCallGenerationArgumentFragmentGenerated(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationArgumentFragmentGenerated","content",s.string(),e,t),this.connector.toolCallGenerationArgumentFragmentGenerated(e)}toolCallGenerationEnded(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationEnded","toolCallRequest",An,e,t),this.connector.toolCallGenerationEnded(e)}toolCallGenerationFailed(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("GeneratorController","toolCallGenerationFailed","error",s.instanceof(Error),e,t),this.connector.toolCallGenerationFailed(e)}},QD=globalThis&&globalThis.__addDisposableResource||function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){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],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(o){return Promise.reject(o)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},XD=globalThis&&globalThis.__disposeResources||(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function o(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(o);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(o,function(l){return t(l),o()})}else i|=1}catch(l){t(l)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return o()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n});function ew(r){switch(typeof r){case"string":return r;case"number":return r.toString();case"boolean":return r?"true":"false";case"undefined":return"undefined";case"object":return r===null?"null":r instanceof Error?r.stack:JSON.stringify(r,null,2);case"bigint":return r.toString();case"symbol":return r.toString();case"function":return r.toString();default:return"unknown"}}function tw(...r){return r.map(ew).join(" ")}function qr(){return`${Date.now()}-${Math.random()}`}var os=class{constructor(e,t,n,i,o){this.pluginsPort=e,this.abortSignal=t,this.processingContextIdentifier=n,this.token=i,this.logger=o}handleUpdate(e){this.pluginsPort.callRpc("processingHandleUpdate",{pci:this.processingContextIdentifier,token:this.token,update:e}).catch(t=>{this.logger.error("Failed to send update",t)})}async handleRequest(e){let{response:t}=await this.pluginsPort.callRpc("processingHandleRequest",{pci:this.processingContextIdentifier,token:this.token,request:e});return t}async pullHistory(e){let t=await this.pluginsPort.callRpc("processingPullHistory",{pci:this.processingContextIdentifier,token:this.token,includeCurrent:e});return gt.createRaw(t,!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})}},as=class extends Nn{constructor(e,t,n,i,o,a,l,c){super(e,a.abortSignal,t,n,i),this.enabledPluginInfos=o,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 t=qr();return this.sendUpdate({type:"status.create",id:t,state:e}),new Ta(this.processingControllerHandle,e,t)}addCitations(e){if(Array.isArray(e))for(let t of e)this.createCitationBlock(t.content,{fileName:t.source.name,fileIdentifier:t.source.identifier});else for(let t of e.entries)this.createCitationBlock(t.content,{fileName:t.source.name,fileIdentifier:t.source.identifier})}createCitationBlock(e,t){let n=qr();return this.sendUpdate({type:"citationBlock.create",id:n,citedText:e,...t}),new Aa(this.processingControllerHandle,n)}createDebugInfoBlock(e){let t=qr();return this.sendUpdate({type:"debugInfoBlock.create",id:t,debugInfo:e}),new Ra(this.processingControllerHandle,t)}createContentBlock({roleOverride:e,includeInContext:t=!0,style:n,prefix:i,suffix:o}={}){let a=qr();return this.sendUpdate({type:"contentBlock.create",id:a,roleOverride:e,includeInContext:t,style:n,prefix:i,suffix:o}),new Ia(this.processingControllerHandle,a,e??"assistant")}debug(...e){this.createDebugInfoBlock(tw(...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:t,name:n,parameters:i}){let{result:o}=await _b(this.processingControllerHandle.sendRequest({type:"confirmToolCall",callId:e,pluginIdentifier:t,name:n,parameters:i}),this.abortSignal),a=o.type;switch(a){case"allow":return{type:"allow",toolArgsOverride:o.toolArgsOverride};case"deny":return{type:"deny",denyReason:o.denyReason};default:{let l=a;throw new Error(`Unexpected result type ${l}. This is a bug. Please report it.`)}}}createToolStatus(e,t){let n=qr();return this.sendUpdate({type:"toolStatus.create",id:n,callId:e,state:{status:t,customStatus:"",customWarnings:[]}}),new Oa(this.processingControllerHandle,n,t)}async startToolUseSession(){let e=this.enabledPluginInfos.filter(({hasToolsProvider:t})=>t).map(({identifier:t})=>t);return await this.client.plugins.startToolUseSessionUsingPredictionProcess(e,this.connector.processingContextIdentifier,this.connector.token)}},Ta=class r{constructor(e,t,n,i=0){this.handle=e,this.id=n,this.indentation=i,this.lastSubStatus=this,this.lastState=t}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 t=qr();this.handle.sendUpdate({type:"status.create",id:t,state:e,location:{type:"afterId",id:this.getNestedLastSubStatusBlockId()},indentation:this.indentation+1});let n=new r(this.handle,e,t,this.indentation+1);return this.lastSubStatus=n,n}},Aa=class{constructor(e,t){this.handle=e,this.id=t}},Ra=class{constructor(e,t){this.handle=e,this.id=t}},Ia=class{constructor(e,t,n){this.handle=e,this.id=t,this.role=n}appendText(e,{tokensCount:t,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:t,fromDraftModel:n,isStructural:i})}appendToolRequest({callId:e,toolCallRequestId:t,name:n,parameters:i,pluginIdentifier:o}){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:t,name:n,parameters:i,pluginIdentifier:o})}replaceToolRequest({callId:e,toolCallRequestId:t,name:n,parameters:i,pluginIdentifier:o}){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:t,name:n,parameters:i,pluginIdentifier:o})}appendToolResult({callId:e,toolCallRequestId:t,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:t,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 t={stack:[],error:void 0,hasError:!1};try{let n=QD(t,new Vi,!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 o=await e;return this.attachGenInfo({indexedModelIdentifier:o.modelInfo.path,identifier:o.modelInfo.identifier,loadModelConfig:o.loadConfig,predictionConfig:o.predictionConfig,stats:o.stats}),this.handle.abortSignal.throwIfAborted(),o}catch(n){t.error=n,t.hasError=!0}finally{XD(t)}}},Oa=class{constructor(e,t,n){this.handle=e,this.id=t,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})}},Ma=class extends Nn{constructor(e,t,n,i,o){super(e,t,n,i,o)}},ja=class{constructor(e,t){this.channel=e,this.taskId=t}fragmentGenerated(e,t){this.channel.send({type:"fragmentGenerated",taskId:this.taskId,content:e,opts:t})}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)})}},Ba=class{constructor(e,t,n,i){this.port=e,this.client=t,this.rootLogger=n,this.validator=i}setPromptPreprocessor(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","registerPromptPreprocessor","promptPreprocessor",s.function(),e,t);let n=new H("PromptPreprocessor",this.rootLogger);n.info("Register with LM Studio");let i=new Map,o=this.port.createChannel("setPromptPreprocessor",void 0,a=>{switch(a.type){case"preprocess":{let l=new H(`Request (${a.taskId.substring(0,6)})`,n);l.info("New preprocess request received.");let c=new AbortController,u=new os(this.port,c.signal,a.pci,a.token,l),h=le.createRaw(a.input,!1),f=new as(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=s.union([s.string(),s.custom(b=>b instanceof le)]).safeParse(d);if(!p.success)throw new Error("PromptPreprocessor returned an invalid value:"+Qe.prettyPrintZod("result",p.error));let m=p.data,g;if(typeof m=="string"){let b=h.asMutableCopy();b.replaceText(m),g=b.getRaw()}else g=m.getRaw();o.send({type:"complete",taskId:a.taskId,processed:g})}).catch(d=>{if(d.name==="AbortError"){n.info("Request successfully aborted."),o.send({type:"aborted",taskId:a.taskId});return}n.warn("Preprocessing failed.",d),o.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:t})}setPredictionLoopHandler(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","setPredictionLoopHandler","predictionLoopHandler",s.function(),e,t);let n=new H(" PredictionLoopHandler",this.rootLogger);n.info("Register with LM Studio");let i=new Map,o=this.port.createChannel("setPredictionLoopHandler",void 0,a=>{switch(a.type){case"handlePredictionLoop":{let l=new H(`Request (${a.taskId.substring(0,6)})`,n);l.info("New prediction loop handling request received.");let c=new AbortController,u=new os(this.port,c.signal,a.pci,a.token,l),h=new as(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(()=>{o.send({type:"complete",taskId:a.taskId})}).catch(f=>{if(f.name==="AbortError"){n.info("Request successfully aborted."),o.send({type:"aborted",taskId:a.taskId});return}n.warn("Generation failed.",f),o.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:t})}async setConfigSchematics(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","setConfigSchematics","configSchematics",s.instanceof(In),e,t),await this.port.callRpc("setConfigSchematics",{schematics:e.serialize()},{stack:t})}async setGlobalConfigSchematics(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","setGlobalConfigSchematics","globalConfigSchematics",s.instanceof(In),e,t),await this.port.callRpc("setGlobalConfigSchematics",{schematics:e.serialize()},{stack:t})}setToolsProvider(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","setToolsProvider","toolsProvider",s.function(),e,t),new H("Tools Prvdr.",this.rootLogger).info("Register with LM Studio");let i=new Map,o=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 Ma(this.client,u.signal,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath);e(f).then(d=>{let p=d.map(ul);h.discarded||(o.send({type:"sessionInitialized",sessionId:c,toolDefinitions:p}),h.tools=new Map(d.map(m=>[m.name,m])))},d=>{h.discarded||(o.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 H(`Tool (${a.toolName})`,this.rootLogger);let p={status(m){o.send({type:"toolCallStatus",sessionId:c,callId:f,statusText:m})},warn(m){o.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",o.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,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`
|
|
338
457
|
Tool call returned undefined. This is not expected as the model always expects
|
|
339
458
|
a result. If you don't want to return anything, you can just return a string
|
|
340
459
|
reporting that the tool call was successful. For example: "operation
|
|
341
460
|
successful." In this case, we will give the model string "${m}".
|
|
342
461
|
`}));try{JSON.stringify(m)}catch{m=j`
|
|
343
462
|
Error: Tool call completed but returned a value that cannot be serialized to JSON
|
|
344
|
-
`,
|
|
463
|
+
`,s.send({type:"toolCallWarn",sessionId:c,callId:f,warnText:j`
|
|
345
464
|
Tool call succeeded, but returned a value that is not JSON serializable. In
|
|
346
465
|
order to provide the result to the model, return values of tools must be JSON
|
|
347
466
|
serializable. In this case, we will give the model string "${m}".
|
|
348
|
-
`})}
|
|
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`
|
|
349
468
|
The generator has returned a value. This it not expected. You should report
|
|
350
469
|
generated content using method on the controller. The returned value will be
|
|
351
470
|
ignored.
|
|
352
|
-
`,o.send({type:"complete",taskId:a.taskId})},p=>{p.name==="AbortError"?(c.info("Request successfully aborted."),o.send({type:"aborted",taskId:a.taskId})):(o.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})}},rw=globalThis&&globalThis.__addDisposableResource||function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,i;if(t){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],t&&(i=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");i&&(n=function(){try{i.call(this)}catch(o){return Promise.reject(o)}}),r.stack.push({value:e,dispose:n,async:t})}else t&&r.stack.push({async:!0});return e},nw=globalThis&&globalThis.__disposeResources||(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var n,i=0;function o(){for(;n=e.stack.pop();)try{if(!n.async&&i===1)return i=0,e.stack.push(n),Promise.resolve().then(o);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return i|=2,Promise.resolve(a).then(o,function(l){return t(l),o()})}else i|=1}catch(l){t(l)}if(i===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return o()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var n=new Error(t);return n.name="SuppressedError",n.error=r,n.suppressed=e,n}),ls=class r{static async create(e,t,n,i,o){let a=new r(e,t,n,i);return await a.init(o),a}constructor(e,t,n,i){this.pluginsPort=e,this.pluginIdentifier=t,this.pluginConfigSpecifier=n,this.logger=i,this.status="initializing",this.poison=null,this.ongoingToolCalls=new Map,this.callIdGiver=new Wi(0)}async init(e){let{promise:t,resolve:n,reject:i}=ee(),o=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(Gi(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});o.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"}),o.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=o,await t}[Symbol.dispose](){if(this.status!=="disposed"){this.channel.send({type:"discardSession"}),this.status="disposed";let e=new Error("Session disposed by client.");for(let t of this.ongoingToolCalls.values())t.reject(e);this.poison=e}}makeTool(e){return Ov({name:e.function.name,description:e.function.description??"",pluginIdentifier:this.pluginIdentifier,parametersJsonSchema:e.function.parameters??{},implementation:async(t,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 o=this.callIdGiver.next(),{promise:a,resolve:l,reject:c}=ee(),u=rw(i,new Vi,!1);return this.ongoingToolCalls.set(o,{callId:o,resolve:l,reject:c,reportStatus:h=>n.status(h),reportWarning:h=>n.warn(h)}),u.register(()=>{this.ongoingToolCalls.delete(o)}),this.channel.send({type:"callTool",callId:o,name:e.function.name,arguments:t}),n.signal.addEventListener("abort",()=>{this.status!=="disposed"&&(this.channel.send({type:"abortToolCall",callId:o}),c(n.signal.reason))},{once:!0}),await a}catch(o){i.error=o,i.hasError=!0}finally{nw(i)}}})}},La=class r{static async createUsingPredictionProcess(e,t,n,i,o,a){let l=await Promise.allSettled(t.map(u=>ls.create(e,u,{type:"predictionProcess",pci:n,token:i},o,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){o.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 r(l.map(u=>u.value),o)}constructor(e,t){this.sessions=e,this.logger=t,this.tools=[],this.tools=e.flatMap(n=>n.tools)}[Symbol.dispose](){for(let e of this.sessions)try{e[Symbol.dispose]()}catch(t){this.logger.error("Failed to dispose a session.",t)}}},iw=s.object({pluginConfig:X.optional(),workingDirectory:s.string().optional()}),sw=s.object({manifest:Ja}),Na=class{constructor(e,t,n,i,o){this.port=e,this.client=t,this.validator=n,this.rootLogger=o,this.logger=new H("Plugins",i)}async registerDevelopmentPlugin(e){let t=A(1);this.validator.validateMethodParamOrThrow("plugins","registerDevelopmentPlugin","opts",sw,e,t);let{promise:n,resolve:i}=ee(),o=this.port.createChannel("registerDevelopmentPlugin",e,u=>{u.type==="ready"&&i({clientIdentifier:u.clientIdentifier,clientPasskey:u.clientPasskey})},{stack:t}),a=!1,l=async()=>{if(a)return;a=!0,o.send({type:"end"});let{promise:u,resolve:h}=ee();o.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 Ba(this.port,this.client,this.rootLogger,this.validator)}async internalStartToolUseSession(e,t,n){return await ls.create(this.port,e,t,this.logger)}async pluginTools(e,t={}){let n=A(1);return[e,t]=this.validator.validateMethodParamsOrThrow("plugins","pluginTools",["pluginIdentifier","opts"],[Lb,iw],[e,t],n),await this.internalStartToolUseSession(e,{type:"direct",config:t.pluginConfig??Yf,workingDirectoryPath:t.workingDirectory})}async startToolUseSessionUsingPredictionProcess(e,t,n,i){return await La.createUsingPredictionProcess(this.port,e,t,n,this.logger,i)}createGeneratorHandle(e){return new ss(this.port,e,this.validator,null,this.logger)}createGeneratorHandleAssociatedWithPredictionProcess(e,t,n){return new ss(this.port,e,this.validator,{pci:t,token:n},this.logger)}},ow=s.object({onStartFinalizing:s.function().optional(),onProgress:s.function().optional(),signal:s.instanceof(AbortSignal).optional()}),$a=class{constructor(e,t,n,i,o,a){this.owner=e,this.name=t,this.onPlanUpdated=n,this.channel=i,this.validator=o,this.onDisposed=a,this.readyDeferredPromise=ee(),this.isReadyBoolean=!1,this.currentDownload=null,this.errorReceivedBeforeDownloadStart=null,this.logger=new H(`ArtifactDownloadPlanner(${e}/${t})`),this.readyDeferredPromise.promise.catch(()=>{}),this.planValue={nodes:[{type:"artifact",owner:e,name:t,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,B(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 t=A(1);e=this.validator.validateMethodParamOrThrow("ArtifactDownloadPlanner","download","opts",ow,e,t);let{onProgress:n,onStartFinalizing:i,signal:o=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}=ee();return this.currentDownload={downloadFinished:()=>{l()},startFinalizing:()=>{B(this.logger,"onStartFinalizing",i,[])},progressUpdate:u=>{B(this.logger,"onProgress",n,[u])},downloadFailed:u=>{c(u)}},this.channel.send({type:"commit"}),o.aborted?this.channel.send({type:"cancel"}):o.addEventListener("abort",()=>{this.channel.send({type:"cancel"})}),await a.catch(u=>{throw o.aborted?o.reason:u})}},aw=s.object({onProgress:s.function().optional(),onStartFinalizing:s.function().optional(),signal:s.instanceof(AbortSignal).optional()}),Ua=class{constructor(e,t,n,i){this.repositoryPort=e,this.validator=t,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 t=A(1);this.validator.validateMethodParamOrThrow("ModelSearchResultDownloadOption","download","opts",aw,e,t);let{promise:n,resolve:i,reject:o}=ee(),a=this.repositoryPort.createChannel("downloadModel",{downloadIdentifier:this.data.downloadIdentifier},c=>{switch(c.type){case"downloadProgress":{B(this.logger,"onProgress",e.onProgress,[c.update]);break}case"startFinalizing":{B(this.logger,"onStartFinalizing",e.onStartFinalizing,[]);break}case"success":{i(c.defaultIdentifier);break}default:{let u=c;throw new Error(`Unexpected message type: ${u}`)}}},{stack:t});a.onError.subscribeOnce(c=>{e.signal?.aborted?o(e.signal.reason):o(c)}),a.onClose.subscribeOnce(()=>{e.signal?.aborted?o(e.signal.reason):o(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}},za=class{constructor(e,t,n,i){this.repositoryPort=e,this.validator=t,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(t=>new Ua(this.repositoryPort,this.validator,this.logger,t))}},lw=s.object({owner:s.string(),name:s.string(),revisionNumber:s.number(),path:s.string(),onProgress:s.function().optional(),onStartFinalizing:s.function().optional(),signal:s.instanceof(AbortSignal).optional()}),cw=s.object({path:s.string(),description:s.string().optional(),makePrivate:s.boolean().optional(),writeRevision:s.boolean().optional(),overrides:Ce.optional(),onMessage:s.function().optional()}),uw=s.object({onAuthenticationUrl:s.function()}),dw=s.object({keyId:s.string(),publicKey:s.string(),privateKey:s.string()});s.object({userName:s.string()});var fw=s.object({owner:s.string(),name:s.string(),onPlanUpdated:s.function().optional()}),qa=class{constructor(e,t,n){this.repositoryPort=e,this.validator=t,this.downloadPlanFinalizationRegistry=new FinalizationRegistry(({owner:i,name:o})=>{this.logger.warn(`
|
|
353
|
-
A download plan for artifact ${i}/${
|
|
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(`
|
|
472
|
+
A download plan for artifact ${i}/${s} has been garbage collected without being
|
|
354
473
|
disposed. Please make sure you are creating the download plan with the "using" keyword.
|
|
355
474
|
|
|
356
475
|
This is a memory leak and needs to be fixed.
|
|
357
|
-
`)}),this.logger=new
|
|
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`
|
|
358
477
|
Failed to construct LMStudioClient. The baseUrl passed in is invalid. Received: ${e}
|
|
359
|
-
`)}["ws:","wss:"].includes(
|
|
478
|
+
`)}["ws:","wss:"].includes(r.protocol)||this.logger.throw(j`
|
|
360
479
|
Failed to construct LMStudioClient. The baseUrl passed in must have protocol "ws" or "wss".
|
|
361
480
|
Received: ${e}
|
|
362
|
-
`),
|
|
481
|
+
`),r.search!==""&&this.logger.throw(j`
|
|
363
482
|
Failed to construct LMStudioClient. The baseUrl passed contains search parameters
|
|
364
|
-
("${
|
|
365
|
-
`),
|
|
366
|
-
Failed to construct LMStudioClient. The baseUrl passed contains a hash ("${
|
|
367
|
-
`),(
|
|
483
|
+
("${r.search}").
|
|
484
|
+
`),r.hash!==""&&this.logger.throw(j`
|
|
485
|
+
Failed to construct LMStudioClient. The baseUrl passed contains a hash ("${r.hash}").
|
|
486
|
+
`),(r.username!==""||r.password!=="")&&this.logger.throw(j`
|
|
368
487
|
Failed to construct LMStudioClient. The baseUrl passed contains a username or password. We
|
|
369
488
|
do not support these in the baseUrl. Received: ${e}
|
|
370
489
|
`),e.endsWith("/")&&this.logger.throw(j`
|
|
371
490
|
Failed to construct LMStudioClient. The baseUrl passed in must not end with a "/". If you
|
|
372
491
|
are reverse-proxying, you should remove the trailing slash from the baseUrl. Received:
|
|
373
492
|
${e}
|
|
374
|
-
`)}async isLocalhostWithGivenPortLMStudioServer(e){let
|
|
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`
|
|
375
494
|
${I.default.redBright("Failed to connect to LM Studio.")}
|
|
376
495
|
|
|
377
496
|
Is LM Studio running? If not, please start it by running:
|
|
@@ -388,7 +507,7 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
388
507
|
${I.default.white("(i) For more information, refer to the LM Studio documentation:")}
|
|
389
508
|
|
|
390
509
|
${I.default.gray("https://lmstudio.ai/docs/local-server")}
|
|
391
|
-
`}return Promise.any(
|
|
510
|
+
`}return Promise.any(Qv.map(this.isLocalhostWithGivenPortLMStudioServer)).then(r=>`ws://127.0.0.1:${r}`,()=>{throw Ee(j`
|
|
392
511
|
${I.default.redBright("Failed to connect to LM Studio.")}
|
|
393
512
|
|
|
394
513
|
Please make sure LM Studio is running on your machine.
|
|
@@ -403,7 +522,7 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
403
522
|
${I.default.white("(i) For more information, refer to the LM Studio documentation:")}
|
|
404
523
|
|
|
405
524
|
${I.default.gray("https://lmstudio.ai/docs/local-server")}
|
|
406
|
-
`,e)})}createPort(e,
|
|
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`
|
|
407
526
|
You cannot create a local LMStudioClient in a plugin context. To use LM Studio APIs, use
|
|
408
527
|
the "client" property attached to the Controllers.
|
|
409
528
|
|
|
@@ -424,7 +543,7 @@ export async function generate(ctl: GeneratorController) {
|
|
|
424
543
|
the LMStudioClient constructor:
|
|
425
544
|
|
|
426
545
|
${"const client = new LMStudioClient({ baseUrl: 'ws://<host_name>:<port>' });"}
|
|
427
|
-
`);this.logger=new
|
|
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.
|
|
428
547
|
|
|
429
548
|
Respond with ONLY a valid JSON object (no markdown, no extra text) in one of these formats:
|
|
430
549
|
{"action": "mouse_move", "x": number, "y": number, "reasoning": "explanation"}
|
|
@@ -433,7 +552,10 @@ Respond with ONLY a valid JSON object (no markdown, no extra text) in one of the
|
|
|
433
552
|
{"action": "keyboard_input", "text": "text to type", "reasoning": "explanation"}
|
|
434
553
|
{"action": "DONE", "reasoning": "explanation of what was accomplished"}
|
|
435
554
|
|
|
436
|
-
x and y are screen coordinates in pixels from the top-left corner. Return DONE only when the instruction is fully completed.`;function
|
|
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(`
|
|
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)
|
|
437
559
|
AI code assistant for your terminal
|
|
438
560
|
|
|
439
561
|
Usage: askii <command> [options]
|
|
@@ -473,21 +595,25 @@ Examples:
|
|
|
473
595
|
askii -p lmstudio --lmstudio-model "my-model" do "refactor index.ts"
|
|
474
596
|
askii control --ollama-model llava "open Notepad and type hello world"
|
|
475
597
|
askii control --yes --ollama-model llava "click the search bar and search for cats"
|
|
476
|
-
`)}async function
|
|
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:
|
|
477
599
|
\`\`\`
|
|
478
600
|
${a}
|
|
479
601
|
\`\`\`
|
|
480
602
|
|
|
481
|
-
Question: ${l}`:`Question: ${l}`;console.error(`ASKII is thinking... ${
|
|
482
|
-
ASKII Says: ${
|
|
483
|
-
`),console.log(u)}catch(u){console.error(`Error: ${u instanceof Error?u.message:"Unknown error"}`),process.exit(1)}}else if(e==="edit"){let
|
|
603
|
+
Question: ${l}`:`Question: ${l}`;console.error(`ASKII is thinking... ${Fn()}`);try{let u=await Pi(i,c);console.log(`
|
|
604
|
+
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:
|
|
484
606
|
\`\`\`
|
|
485
607
|
${a}
|
|
486
608
|
\`\`\`
|
|
487
609
|
|
|
488
610
|
Request: ${l}
|
|
489
611
|
|
|
490
|
-
Return only the updated code without explanation.`;console.error("ASKII is editing... (\u2022_\u2022)>\u2310\u25A0-\u25A0");try{let u=await
|
|
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(`
|
|
613
|
+
Workspace: ${a}
|
|
614
|
+
\`\`\`
|
|
615
|
+
${c}\`\`\`
|
|
616
|
+
`);let u=0,h=0,f=`You are ASKII, an AI agent that can create, modify, view, delete, rename, and list files in a workspace.
|
|
491
617
|
|
|
492
618
|
Current workspace structure:
|
|
493
619
|
\`\`\`
|
|
@@ -495,25 +621,28 @@ ${c}
|
|
|
495
621
|
\`\`\`
|
|
496
622
|
|
|
497
623
|
You have access to the following action types:
|
|
498
|
-
- {"type": "view", "path": "path/to/file"} - View file contents
|
|
624
|
+
- {"type": "view", "path": "path/to/file"} - View file contents, results sent back to you
|
|
625
|
+
- {"type": "list", "path": "path/to/folder"} - List files in a folder, results sent back to you
|
|
499
626
|
- {"type": "create", "path": "path/to/file", "content": "file content"}
|
|
500
627
|
- {"type": "modify", "path": "path/to/file", "oldContent": "text to replace", "newContent": "replacement text"}
|
|
628
|
+
- {"type": "rename", "path": "old/path", "newPath": "new/path"} - Rename or move a file
|
|
501
629
|
- {"type": "delete", "path": "path/to/file"}
|
|
502
630
|
|
|
503
|
-
Always respond with ONLY a valid JSON array containing the actions. You can request to view files to inspect them, and their contents will be sent back to you.`,d=
|
|
631
|
+
Always respond with ONLY a valid JSON array containing the actions. You can request to view files or list folders to inspect them, and their contents will be sent back to you.`,d=s;for(;h<i.maxRounds;){let p=h===0?`${f}
|
|
504
632
|
|
|
505
633
|
User request: ${d}`:`${f}
|
|
506
634
|
|
|
507
|
-
${d}`,m=await
|
|
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(`
|
|
636
|
+
`)}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:
|
|
508
637
|
${JSON.stringify(D,null,2)}
|
|
509
638
|
|
|
510
|
-
|
|
511
|
-
Completed ${u} actions! ${
|
|
512
|
-
`);let l=0;for(;l<i.maxRounds;){console.error(`Round ${l+1}/${i.maxRounds} \u2014 taking screenshot...`);let
|
|
639
|
+
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}
|
|
513
642
|
|
|
514
|
-
Analyze the screenshot and determine the next action.`:`Continuing instruction: ${
|
|
643
|
+
Analyze the screenshot and determine the next action.`:`Continuing instruction: ${s}
|
|
515
644
|
|
|
516
|
-
Analyze the updated screenshot and determine the next action, or return DONE if the instruction is complete.`;console.error("Asking AI...");let
|
|
517
|
-
Done! ${
|
|
518
|
-
Action: ${
|
|
519
|
-
`),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}`),
|
|
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_();
|