askii-cli 0.2.1 → 0.2.2
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 +16 -1
- package/dist/index.js +110 -103
- package/dist/index.js.map +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,62 +1,62 @@
|
|
|
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 Mh=Object.create;var gs=Object.defineProperty;var jh=Object.getOwnPropertyDescriptor;var Bh=Object.getOwnPropertyNames;var Lh=Object.getPrototypeOf,Nh=Object.prototype.hasOwnProperty;var J=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),$h=(r,e)=>{for(var t in e)gs(r,t,{get:e[t],enumerable:!0})},Uh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bh(e))!Nh.call(r,i)&&i!==t&&gs(r,i,{get:()=>e[i],enumerable:!(n=jh(e,i))||n.enumerable});return r};var Me=(r,e,t)=>(t=r!=null?Mh(Lh(r)):{},Uh(e||!r||!r.__esModule?gs(t,"default",{value:r,enumerable:!0}):t,r));var ys=J((Hn,bl)=>{(function(r,e){typeof Hn=="object"&&typeof bl<"u"?e(Hn):typeof define=="function"&&define.amd?define(["exports"],e):e(r.WHATWGFetch={})})(Hn,(function(r){"use strict";var e=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global||{},t={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(t.arrayBuffer)var i=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],o=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 C={next:function(){var P=w.shift();return{done:P===void 0,value:P}}};return t.iterable&&(C[Symbol.iterator]=function(){return C}),C}function u(w){this.map={},w instanceof u?w.forEach(function(C,P){this.append(P,C)},this):Array.isArray(w)?w.forEach(function(C){if(C.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+C.length);this.append(C[0],C[1])},this):w&&Object.getOwnPropertyNames(w).forEach(function(C){this.append(C,w[C])},this)}u.prototype.append=function(w,C){w=a(w),C=l(C);var P=this.map[w];this.map[w]=P?P+", "+C:C},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,C){this.map[a(w)]=l(C)},u.prototype.forEach=function(w,C){for(var P in this.map)this.map.hasOwnProperty(P)&&w.call(C,this.map[P],P,this)},u.prototype.keys=function(){var w=[];return this.forEach(function(C,P){w.push(P)}),c(w)},u.prototype.values=function(){var w=[];return this.forEach(function(C){w.push(C)}),c(w)},u.prototype.entries=function(){var w=[];return this.forEach(function(C,P){w.push([P,C])}),c(w)},t.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(C,P){w.onload=function(){C(w.result)},w.onerror=function(){P(w.error)}})}function d(w){var C=new FileReader,P=f(C);return C.readAsArrayBuffer(w),P}function p(w){var C=new FileReader,P=f(C),U=/charset=([A-Za-z0-9_-]+)/.exec(w.type),Z=U?U[1]:"utf-8";return C.readAsText(w,Z),P}function m(w){for(var C=new Uint8Array(w),P=new Array(C.length),U=0;U<C.length;U++)P[U]=String.fromCharCode(C[U]);return P.join("")}function g(w){if(w.slice)return w.slice(0);var C=new Uint8Array(w.byteLength);return C.set(new Uint8Array(w)),C.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(w){this.bodyUsed=this.bodyUsed,this._bodyInit=w,w?typeof w=="string"?this._bodyText=w:t.blob&&Blob.prototype.isPrototypeOf(w)?this._bodyBlob=w:t.formData&&FormData.prototype.isPrototypeOf(w)?this._bodyFormData=w:t.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)?this._bodyText=w.toString():t.arrayBuffer&&t.blob&&n(w)?(this._bodyArrayBuffer=g(w.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):t.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(w)||o(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):t.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},t.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(t.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)},t.formData&&(this.formData=function(){return this.text().then(S)}),this.json=function(){return this.text().then(JSON.parse)},this}var y=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function D(w){var C=w.toUpperCase();return y.indexOf(C)>-1?C:w}function v(w,C){if(!(this instanceof v))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');C=C||{};var P=C.body;if(w instanceof v){if(w.bodyUsed)throw new TypeError("Already read");this.url=w.url,this.credentials=w.credentials,C.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=C.credentials||this.credentials||"same-origin",(C.headers||!this.headers)&&(this.headers=new u(C.headers)),this.method=D(C.method||this.method||"GET"),this.mode=C.mode||this.mode||null,this.signal=C.signal||this.signal||(function(){if("AbortController"in e){var q=new AbortController;return q.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")&&(C.cache==="no-store"||C.cache==="no-cache")){var U=/([?&])_=[^&]*/;if(U.test(this.url))this.url=this.url.replace(U,"$1_="+new Date().getTime());else{var Z=/\?/;this.url+=(Z.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})};function S(w){var C=new FormData;return w.trim().split("&").forEach(function(P){if(P){var U=P.split("="),Z=U.shift().replace(/\+/g," "),q=U.join("=").replace(/\+/g," ");C.append(decodeURIComponent(Z),decodeURIComponent(q))}}),C}function _(w){var C=new u,P=w.replace(/\r?\n[\t ]+/g," ");return P.split("\r").map(function(U){return U.indexOf(`
|
|
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 x(w,C){if(!(this instanceof x))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(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 E=[301,302,303,307,308];x.redirect=function(w,C){if(E.indexOf(C)===-1)throw new RangeError("Invalid status code");return new x(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 x(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=x),r.Headers=u,r.Request=v,r.Response=x,r.fetch=z,Object.defineProperty(r,"__esModule",{value:!0})}))});var Il=J((e1,Rl)=>{"use strict";Rl.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 Ts=J((t1,Ml)=>{var on=Il(),Ol={};for(let r of Object.keys(on))Ol[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"]}};Ml.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 cm(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=Ol[r];if(e)return e;let t=1/0,n;for(let i of Object.keys(on)){let o=on[i],a=cm(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 Bl=J((r1,jl)=>{var ti=Ts();function um(){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 dm(r){let e=um(),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 fm(r,e){return function(t){return e(r(t))}}function hm(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=fm(ti[e[i].parent][i],n),i=e[i].parent;return n.conversion=t,n}jl.exports=function(r){let e=dm(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]=hm(a,e))}return t}});var Nl=J((n1,Ll)=>{var As=Ts(),pm=Bl(),kr={},mm=Object.keys(As);function gm(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 ym(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}mm.forEach(r=>{kr[r]={},Object.defineProperty(kr[r],"channels",{value:As[r].channels}),Object.defineProperty(kr[r],"labels",{value:As[r].labels});let e=pm(r);Object.keys(e).forEach(n=>{let i=e[n];kr[r][n]=ym(i),kr[r][n].raw=gm(i)})});Ll.exports=kr});var Wl=J((i1,Vl)=>{"use strict";var $l=(r,e)=>(...t)=>`\x1B[${r(...t)+e}m`,Ul=(r,e)=>(...t)=>{let n=r(...t);return`\x1B[${38+e};5;${n}m`},zl=(r,e)=>(...t)=>{let n=r(...t);return`\x1B[${38+e};2;${n[0]};${n[1]};${n[2]}m`},ri=r=>r,ql=(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})},Rs,Pr=(r,e,t,n)=>{Rs===void 0&&(Rs=Nl());let i=n?10:0,o={};for(let[a,l]of Object.entries(Rs)){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 bm(){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($l,"ansi16",ri,!1)),Fr(e.color,"ansi256",()=>Pr(Ul,"ansi256",ri,!1)),Fr(e.color,"ansi16m",()=>Pr(zl,"rgb",ql,!1)),Fr(e.bgColor,"ansi",()=>Pr($l,"ansi16",ri,!0)),Fr(e.bgColor,"ansi256",()=>Pr(Ul,"ansi256",ri,!0)),Fr(e.bgColor,"ansi16m",()=>Pr(zl,"rgb",ql,!0)),e}Object.defineProperty(Vl,"exports",{enumerable:!0,get:bm})});var Gl=J((s1,Zl)=>{"use strict";Zl.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 Jl=J((o1,Hl)=>{"use strict";var vm=require("os"),Kl=require("tty"),Re=Gl(),{env:oe}=process,_t;Re("no-color")||Re("no-colors")||Re("color=false")||Re("color=never")?_t=0:(Re("color")||Re("colors")||Re("color=true")||Re("color=always"))&&(_t=1);"FORCE_COLOR"in oe&&(oe.FORCE_COLOR==="true"?_t=1:oe.FORCE_COLOR==="false"?_t=0:_t=oe.FORCE_COLOR.length===0?1:Math.min(parseInt(oe.FORCE_COLOR,10),3));function Is(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Os(r,e){if(_t===0)return 0;if(Re("color=16m")||Re("color=full")||Re("color=truecolor"))return 3;if(Re("color=256"))return 2;if(r&&!e&&_t===void 0)return 0;let t=_t||0;if(oe.TERM==="dumb")return t;if(process.platform==="win32"){let n=vm.release().split(".");return Number(n[0])>=10&&Number(n[2])>=10586?Number(n[2])>=14931?3:2:1}if("CI"in oe)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(n=>n in oe)||oe.CI_NAME==="codeship"?1:t;if("TEAMCITY_VERSION"in oe)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(oe.TEAMCITY_VERSION)?1:0;if(oe.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in oe){let n=parseInt((oe.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(oe.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(oe.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(oe.TERM)||"COLORTERM"in oe?1:t}function Dm(r){let e=Os(r,r&&r.isTTY);return Is(e)}Hl.exports={supportsColor:Dm,stdout:Is(Os(!0,Kl.isatty(1))),stderr:Is(Os(!0,Kl.isatty(2)))}});var Ql=J((a1,Yl)=>{"use strict";var wm=(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},Sm=(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
|
|
4
4
|
`:`
|
|
5
5
|
`)+t,i=n+1,n=r.indexOf(`
|
|
6
|
-
`,i)}while(n!==-1);return o+=r.substr(i),o};
|
|
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
|
|
6
|
+
`,i)}while(n!==-1);return o+=r.substr(i),o};Yl.exports={stringReplaceAll:wm,stringEncaseCRLFWithFirstIndex:Sm}});var nc=J((l1,rc)=>{"use strict";var Cm=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,Xl=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,_m=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,Em=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,xm=new Map([["n",`
|
|
7
|
+
`],["r","\r"],["t"," "],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e","\x1B"],["a","\x07"]]);function tc(r){let e=r[0]==="u",t=r[1]==="{";return e&&!t&&r.length===5||r[0]==="x"&&r.length===3?String.fromCharCode(parseInt(r.slice(1),16)):e&&t?String.fromCodePoint(parseInt(r.slice(2,-1),16)):xm.get(r)||r}function km(r,e){let t=[],n=e.trim().split(/\s*,\s*/g),i;for(let o of n){let a=Number(o);if(!Number.isNaN(a))t.push(a);else if(i=o.match(_m))t.push(i[2].replace(Em,(l,c,u)=>c?tc(c):u));else throw new Error(`Invalid Chalk template style argument: ${o} (in style '${r}')`)}return t}function Fm(r){Xl.lastIndex=0;let e=[],t;for(;(t=Xl.exec(r))!==null;){let n=t[1];if(t[2]){let i=km(n,t[2]);e.push([n].concat(i))}else e.push([n])}return e}function ec(r,e){let t={};for(let i of e)for(let o of i.styles)t[o[0]]=i.inverse?null:o.slice(1);let n=r;for(let[i,o]of Object.entries(t))if(Array.isArray(o)){if(!(i in n))throw new Error(`Unknown Chalk style: ${i}`);n=o.length>0?n[i](...o):n[i]}return n}rc.exports=(r,e)=>{let t=[],n=[],i=[];if(e.replace(Cm,(o,a,l,c,u,h)=>{if(a)i.push(tc(a));else if(c){let f=i.join("");i=[],n.push(t.length===0?f:ec(r,t)(f)),t.push({inverse:l,styles:Fm(c)})}else if(u){if(t.length===0)throw new Error("Found extraneous } in Chalk template literal");n.push(ec(r,t)(i.join(""))),i=[],t.pop()}else i.push(h)}),n.push(i.join("")),t.length>0){let o=`Chalk template literal is missing ${t.length} closing bracket${t.length===1?"":"s"} (\`}\`)`;throw new Error(o)}return n.join("")}});var uc=J((c1,cc)=>{"use strict";var an=Wl(),{stdout:js,stderr:Bs}=Jl(),{stringReplaceAll:Pm,stringEncaseCRLFWithFirstIndex:Tm}=Ql(),{isArray:ni}=Array,sc=["ansi","ansi","ansi256","ansi16m"],Tr=Object.create(null),Am=(r,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 t=js?js.level:0;r.level=e.level===void 0?t:e.level},Ls=class{constructor(e){return oc(e)}},oc=r=>{let e={};return Am(e,r),e.template=(...t)=>lc(e.template,...t),Object.setPrototypeOf(e,ii.prototype),Object.setPrototypeOf(e.template,e),e.template.constructor=()=>{throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},e.template.Instance=Ls,e.template};function ii(r){return oc(r)}for(let[r,e]of Object.entries(an))Tr[r]={get(){let t=si(this,Ns(e.open,e.close,this._styler),this._isEmpty);return Object.defineProperty(this,r,{value:t}),t}};Tr.visible={get(){let r=si(this,this._styler,!0);return Object.defineProperty(this,"visible",{value:r}),r}};var ac=["rgb","hex","keyword","hsl","hsv","hwb","ansi","ansi256"];for(let r of ac)Tr[r]={get(){let{level:e}=this;return function(...t){let n=Ns(an.color[sc[e]][r](...t),an.color.close,this._styler);return si(this,n,this._isEmpty)}}};for(let r of ac){let e="bg"+r[0].toUpperCase()+r.slice(1);Tr[e]={get(){let{level:t}=this;return function(...n){let i=Ns(an.bgColor[sc[t]][r](...n),an.bgColor.close,this._styler);return si(this,i,this._isEmpty)}}}}var Rm=Object.defineProperties(()=>{},{...Tr,level:{enumerable:!0,get(){return this._generator.level},set(r){this._generator.level=r}}}),Ns=(r,e,t)=>{let n,i;return t===void 0?(n=r,i=e):(n=t.openAll+r,i=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:i,parent:t}},si=(r,e,t)=>{let n=(...i)=>ni(i[0])&&ni(i[0].raw)?ic(n,lc(n,...i)):ic(n,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(n,Rm),n._generator=r,n._styler=e,n._isEmpty=t,n},ic=(r,e)=>{if(r.level<=0||!e)return r._isEmpty?"":e;let t=r._styler;if(t===void 0)return e;let{openAll:n,closeAll:i}=t;if(e.indexOf("\x1B")!==-1)for(;t!==void 0;)e=Pm(e,t.close,t.open),t=t.parent;let o=e.indexOf(`
|
|
8
|
+
`);return o!==-1&&(e=Tm(e,i,n,o)),n+e+i},Ms,lc=(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 Ms===void 0&&(Ms=nc()),Ms(r,i.join(""))};Object.defineProperties(ii.prototype,Tr);var oi=ii();oi.supportsColor=js;oi.stderr=ii({level:Bs?Bs.level:0});oi.stderr.supportsColor=Bs;cc.exports=oi});var dc=J($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.generateRandomBase64=Om;var Im=require("crypto");function Om(r=18){return(0,Im.randomBytes)(r).toString("base64")}});var fc=J(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.readFileAsBase64=jm;var Mm=require("fs/promises");async function jm(r){return{success:!0,base64:await(0,Mm.readFile)(r,"base64")}}});var yc=J(ln=>{"use strict";var Vs=ln&&ln.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ln,"__esModule",{value:!0});ln.terminalSize=Nm;var Bm=require("child_process"),ai=Vs(require("fs")),Ar=Vs(require("process")),Lm=Vs(require("tty")),pc=80,mc=24,qs=(r,e,{shell:t,env:n}={})=>(0,Bm.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)}),gc=(r,e)=>{let{columns:t,rows:n}=li(r,e);if(!(Number.isNaN(t)||Number.isNaN(n))&&!(t===pc&&n===mc))return{columns:t,rows:n}};function Nm(){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:pc,rows:mc};return Ar.default.platform==="win32"?zs()??n:Ar.default.platform==="darwin"?hc()??zs()??n:hc()??zs()??$m()??n}var hc=()=>{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}=Lm.default.WriteStream(ai.default.openSync("/dev/tty",r));return{columns:e,rows:t}}catch{}},zs=()=>{try{let r=qs("tput",["cols"],{env:{TERM:"dumb",...Ar.default.env}}),e=qs("tput",["lines"],{env:{TERM:"dumb",...Ar.default.env}});if(r&&e)return gc(r,e)}catch{}},$m=()=>{try{let r=qs("resize",["-u"]).match(/\d+/g);if(r.length===2)return gc(r[0],r[1])}catch{}}});var st=J((h1,Dc)=>{"use strict";var bc=["nodebuffer","arraybuffer","fragments"],vc=typeof Blob<"u";vc&&bc.push("blob");Dc.exports={BINARY_TYPES:bc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:vc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var cn=J((p1,ci)=>{"use strict";var{EMPTY_BUFFER:Um}=st(),Ws=Buffer[Symbol.species];function zm(r,e){if(r.length===0)return Um;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 Ws(t.buffer,t.byteOffset,n):t}function wc(r,e,t,n,i){for(let o=0;o<i;o++)t[n+o]=r[o]^e[o&3]}function Sc(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function qm(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Zs(r){if(Zs.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Ws(r):ArrayBuffer.isView(r)?e=new Ws(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Zs.readOnly=!1),e}ci.exports={concat:zm,mask:wc,toArrayBuffer:qm,toBuffer:Zs,unmask:Sc};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");ci.exports.mask=function(e,t,n,i,o){o<48?wc(e,t,n,i,o):r.mask(e,t,n,i,o)},ci.exports.unmask=function(e,t){e.length<32?Sc(e,t):r.unmask(e,t)}}catch{}});var Ec=J((m1,_c)=>{"use strict";var Cc=Symbol("kDone"),Gs=Symbol("kRun"),Ks=class{constructor(e){this[Cc]=()=>{this.pending--,this[Gs]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Gs]()}[Gs](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Cc])}}};_c.exports=Ks});var dn=J((g1,Pc)=>{"use strict";var un=require("zlib"),xc=cn(),Vm=Ec(),{kStatusCode:kc}=st(),Wm=Buffer[Symbol.species],Zm=Buffer.from([0,0,255,255]),di=Symbol("permessage-deflate"),ot=Symbol("total-length"),Rr=Symbol("callback"),Et=Symbol("buffers"),Ir=Symbol("error"),ui,Hs=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 Vm(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[ot]=0,this._inflate[Et]=[],this._inflate.on("error",Km),this._inflate.on("data",Fc)}this._inflate[Rr]=n,this._inflate.write(e),t&&this._inflate.write(Zm),this._inflate.flush(()=>{let o=this._inflate[Ir];if(o){this._inflate.close(),this._inflate=null,n(o);return}let a=xc.concat(this._inflate[Et],this._inflate[ot]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ot]=0,this._inflate[Et]=[],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[ot]=0,this._deflate[Et]=[],this._deflate.on("data",Gm)}this._deflate[Rr]=n,this._deflate.write(e),this._deflate.flush(un.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=xc.concat(this._deflate[Et],this._deflate[ot]);t&&(o=new Wm(o.buffer,o.byteOffset,o.length-4)),this._deflate[Rr]=null,this._deflate[ot]=0,this._deflate[Et]=[],t&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,o)})}};Pc.exports=Hs;function Gm(r){this[Et].push(r),this[ot]+=r.length}function Fc(r){if(this[ot]+=r.length,this[di]._maxPayload<1||this[ot]<=this[di]._maxPayload){this[Et].push(r);return}this[Ir]=new RangeError("Max payload size exceeded"),this[Ir].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Ir][kc]=1009,this.removeListener("data",Fc),this.reset()}function Km(r){if(this[di]._inflate=null,this[Ir]){this[Rr](this[Ir]);return}r[kc]=1007,this[Rr](r)}});var Or=J((y1,fi)=>{"use strict";var{isUtf8:Tc}=require("buffer"),{hasBlob:Hm}=st(),Jm=[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 Ym(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Js(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 Qm(r){return Hm&&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:Qm,isValidStatusCode:Ym,isValidUTF8:Js,tokenChars:Jm};if(Tc)fi.exports.isValidUTF8=function(r){return r.length<24?Js(r):Tc(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?Js(e):r(e)}}catch{}});var to=J((b1,Bc)=>{"use strict";var{Writable:Xm}=require("stream"),Ac=dn(),{BINARY_TYPES:eg,EMPTY_BUFFER:Rc,kStatusCode:tg,kWebSocket:rg}=st(),{concat:Ys,toArrayBuffer:ng,unmask:ig}=cn(),{isValidStatusCode:sg,isValidUTF8:Ic}=Or(),hi=Buffer[Symbol.species],Ie=0,Oc=1,Mc=2,jc=3,Qs=4,Xs=5,pi=6,eo=class extends Xm{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||eg[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[rg]=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=Ie}_write(e,t,n){if(this._opcode===8&&this._state==Ie)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 Ie:this.getInfo(e);break;case Oc:this.getPayloadLength16(e);break;case Mc:this.getPayloadLength64(e);break;case jc:this.getMask();break;case Qs:this.getData(e);break;case Xs: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[Ac.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=Oc:this._payloadLength===127?this._state=Mc: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=jc:this._state=Qs}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Qs}getData(e){let t=Rc;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&&ig(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Xs,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Ac.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===Ie&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ie;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=Ys(n,t):this._binaryType==="arraybuffer"?i=ng(Ys(n,t)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Ie):(this._state=pi,setImmediate(()=>{this.emit("message",i,!0),this._state=Ie,this.startLoop(e)}))}else{let i=Ys(n,t);if(!this._skipUTF8Validation&&!Ic(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===Xs||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Ie):(this._state=pi,setImmediate(()=>{this.emit("message",i,!1),this._state=Ie,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Rc),this.end();else{let n=e.readUInt16BE(0);if(!sg(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&&!Ic(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=Ie;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ie):(this._state=pi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ie,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[tg]=i,a}};Bc.exports=eo});var io=J((D1,$c)=>{"use strict";var{Duplex:v1}=require("stream"),{randomFillSync:og}=require("crypto"),Lc=dn(),{EMPTY_BUFFER:ag,kWebSocket:lg,NOOP:cg}=st(),{isBlob:Mr,isValidStatusCode:ug}=Or(),{mask:Nc,toBuffer:Qt}=cn(),Oe=Symbol("kByteLength"),dg=Buffer.alloc(4),mi=8*1024,Xt,jr=mi,Be=0,fg=1,hg=2,ro=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=Be,this.onerror=cg,this[lg]=void 0}static frame(e,t){let n,i=!1,o=2,a=!1;t.mask&&(n=t.maskBuffer||dg,t.generateMask?t.generateMask(n):(jr===mi&&(Xt===void 0&&(Xt=Buffer.alloc(mi)),og(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[Oe]!==void 0?l=t[Oe]:(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?(Nc(e,n,u,o,l),[u]):(Nc(e,n,e,0,l),[u,e])):[u,e]}close(e,t,n,i){let o;if(e===void 0)o=ag;else{if(typeof e!="number"||!ug(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={[Oe]:o.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Be?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={[Oe]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};Mr(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Be?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={[Oe]:i,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};Mr(e)?this._state!==Be?this.enqueue([this.getBlobData,e,!1,a,n]):this.getBlobData(e,!1,a,n):this._state!==Be?this.enqueue([this.dispatch,e,!1,a,n]):this.sendFrame(r.frame(e,a),n)}send(e,t,n){let i=this._extensions[Lc.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={[Oe]:l,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:a};Mr(e)?this._state!==Be?this.enqueue([this.getBlobData,e,this._compress,u,n]):this.getBlobData(e,this._compress,u,n):this._state!==Be?this.enqueue([this.dispatch,e,this._compress,u,n]):this.dispatch(e,this._compress,u,n)}getBlobData(e,t,n,i){this._bufferedBytes+=n[Oe],this._state=hg,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(no,this,l,i);return}this._bufferedBytes-=n[Oe];let a=Qt(o);t?this.dispatch(a,t,n,i):(this._state=Be,this.sendFrame(r.frame(a,n),i),this.dequeue())}).catch(o=>{process.nextTick(pg,this,o,i)})}dispatch(e,t,n,i){if(!t){this.sendFrame(r.frame(e,n),i);return}let o=this._extensions[Lc.extensionName];this._bufferedBytes+=n[Oe],this._state=fg,o.compress(e,n.fin,(a,l)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");no(this,c,i);return}this._bufferedBytes-=n[Oe],this._state=Be,n.readOnly=!1,this.sendFrame(r.frame(l,n),i),this.dequeue()})}dequeue(){for(;this._state===Be&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Oe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Oe],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)}};$c.exports=ro;function no(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 pg(r,e,t){no(r,e,t),r.onerror(e)}});var Hc=J((w1,Kc)=>{"use strict";var{kForOnEventAttribute:fn,kListener:so}=st(),Uc=Symbol("kCode"),zc=Symbol("kData"),qc=Symbol("kError"),Vc=Symbol("kMessage"),Wc=Symbol("kReason"),Br=Symbol("kTarget"),Zc=Symbol("kType"),Gc=Symbol("kWasClean"),at=class{constructor(e){this[Br]=null,this[Zc]=e}get target(){return this[Br]}get type(){return this[Zc]}};Object.defineProperty(at.prototype,"target",{enumerable:!0});Object.defineProperty(at.prototype,"type",{enumerable:!0});var er=class extends at{constructor(e,t={}){super(e),this[Uc]=t.code===void 0?0:t.code,this[Wc]=t.reason===void 0?"":t.reason,this[Gc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Uc]}get reason(){return this[Wc]}get wasClean(){return this[Gc]}};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 at{constructor(e,t={}){super(e),this[qc]=t.error===void 0?null:t.error,this[Vc]=t.message===void 0?"":t.message}get error(){return this[qc]}get message(){return this[Vc]}};Object.defineProperty(Lr.prototype,"error",{enumerable:!0});Object.defineProperty(Lr.prototype,"message",{enumerable:!0});var hn=class extends at{constructor(e,t={}){super(e),this[zc]=t.data===void 0?null:t.data}get data(){return this[zc]}};Object.defineProperty(hn.prototype,"data",{enumerable:!0});var mg={addEventListener(r,e,t={}){for(let i of this.listeners(r))if(!t[fn]&&i[so]===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 at("open");o[Br]=this,gi(e,this,o)};else return;n[fn]=!!t[fn],n[so]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[so]===e&&!t[fn]){this.removeListener(r,t);break}}};Kc.exports={CloseEvent:er,ErrorEvent:Lr,Event:at,EventTarget:mg,MessageEvent:hn};function gi(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var oo=J((S1,Jc)=>{"use strict";var{tokenChars:pn}=Or();function Ve(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function gg(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?(Ve(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),Ve(t,r.slice(c,h),!0),u===44&&(Ve(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),Ve(t,l,p),u===44&&(Ve(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?Ve(e,d,t):(l===void 0?Ve(t,d,!0):n?Ve(t,l,d.replace(/\\/g,"")):Ve(t,l,d),Ve(e,a,t)),e}function yg(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(", ")}Jc.exports={format:yg,parse:gg}});var Di=J((E1,lu)=>{"use strict";var bg=require("events"),vg=require("https"),Dg=require("http"),Xc=require("net"),wg=require("tls"),{randomBytes:Sg,createHash:Cg}=require("crypto"),{Duplex:C1,Readable:_1}=require("stream"),{URL:ao}=require("url"),xt=dn(),_g=to(),Eg=io(),{isBlob:xg}=Or(),{BINARY_TYPES:Yc,CLOSE_TIMEOUT:kg,EMPTY_BUFFER:yi,GUID:Fg,kForOnEventAttribute:lo,kListener:Pg,kStatusCode:Tg,kWebSocket:ae,NOOP:eu}=st(),{EventTarget:{addEventListener:Ag,removeEventListener:Rg}}=Hc(),{format:Ig,parse:Og}=oo(),{toBuffer:Mg}=cn(),tu=Symbol("kAborted"),co=[8,13],lt=["CONNECTING","OPEN","CLOSING","CLOSED"],jg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,te=class r extends bg{constructor(e,t,n){super(),this._binaryType=Yc[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]),ru(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yc.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 _g({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),o=new Eg(e,this._extensions,n.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[ae]=this,o[ae]=this,e[ae]=this,i.on("conclude",Ng),i.on("drain",$g),i.on("error",Ug),i.on("message",zg),i.on("ping",qg),i.on("pong",Vg),o.onerror=Wg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",su),e.on("data",vi),e.on("end",ou),e.on("error",au),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[xt.extensionName]&&this._extensions[xt.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())}),iu(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){uo(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){uo(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){uo(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[xt.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:lt.indexOf("CONNECTING")});Object.defineProperty(te.prototype,"CONNECTING",{enumerable:!0,value:lt.indexOf("CONNECTING")});Object.defineProperty(te,"OPEN",{enumerable:!0,value:lt.indexOf("OPEN")});Object.defineProperty(te.prototype,"OPEN",{enumerable:!0,value:lt.indexOf("OPEN")});Object.defineProperty(te,"CLOSING",{enumerable:!0,value:lt.indexOf("CLOSING")});Object.defineProperty(te.prototype,"CLOSING",{enumerable:!0,value:lt.indexOf("CLOSING")});Object.defineProperty(te,"CLOSED",{enumerable:!0,value:lt.indexOf("CLOSED")});Object.defineProperty(te.prototype,"CLOSED",{enumerable:!0,value:lt.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[lo])return e[Pg];return null},set(e){for(let t of this.listeners(r))if(t[lo]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[lo]:!0})}})});te.prototype.addEventListener=Ag;te.prototype.removeEventListener=Rg;lu.exports=te;function ru(r,e,t,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:kg,protocolVersion:co[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,!co.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${co.join(", ")})`);let o;if(e instanceof ao)o=e;else try{o=new ao(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=Sg(16).toString("base64"),f=a?vg.request:Dg.request,d=new Set,p;if(i.createConnection=i.createConnection||(a?Lg:Bg),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 xt(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=Ig({[xt.extensionName]:p.offer()})),t.length){for(let g of t){if(typeof g!="string"||!jg.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[tu]||(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 ao(b,e)}catch{let S=new SyntaxError(`Invalid URL: ${b}`);bi(r,S);return}ru(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=Cg("sha1").update(h+Fg).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 x=g.headers["sec-websocket-extensions"];if(x!==void 0){if(!p){Ee(r,b,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let E;try{E=Og(x)}catch{Ee(r,b,"Invalid Sec-WebSocket-Extensions header");return}let z=Object.keys(E);if(z.length!==1||z[0]!==xt.extensionName){Ee(r,b,"Server indicated an extension that was not requested");return}try{p.accept(E[xt.extensionName])}catch{Ee(r,b,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[xt.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 Bg(r){return r.path=r.socketPath,Xc.connect(r)}function Lg(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Xc.isIP(r.host)?"":r.host),wg.connect(r)}function Ee(r,e,t){r._readyState=te.CLOSING;let n=new Error(t);Error.captureStackTrace(n,Ee),e.setHeader?(e[tu]=!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 uo(r,e,t){if(e){let n=xg(e)?e.size:Mg(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${lt[r.readyState]})`);process.nextTick(t,n)}}function Ng(r,e){let t=this[ae];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ae]!==void 0&&(t._socket.removeListener("data",vi),process.nextTick(nu,t._socket),r===1005?t.close():t.close(r,e))}function $g(){let r=this[ae];r.isPaused||r._socket.resume()}function Ug(r){let e=this[ae];e._socket[ae]!==void 0&&(e._socket.removeListener("data",vi),process.nextTick(nu,e._socket),e.close(r[Tg])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Qc(){this[ae].emitClose()}function zg(r,e){this[ae].emit("message",r,e)}function qg(r){let e=this[ae];e._autoPong&&e.pong(r,!this._isServer,eu),e.emit("ping",r)}function Vg(r){this[ae].emit("pong",r)}function nu(r){r.resume()}function Wg(r){let e=this[ae];e.readyState!==te.CLOSED&&(e.readyState===te.OPEN&&(e._readyState=te.CLOSING,iu(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function iu(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function su(){let r=this[ae];if(this.removeListener("close",su),this.removeListener("data",vi),this.removeListener("end",ou),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[ae]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Qc),r._receiver.on("finish",Qc))}function vi(r){this[ae]._receiver.write(r)||this.pause()}function ou(){let r=this[ae];r._readyState=te.CLOSING,r._receiver.end(),this.end()}function au(){let r=this[ae];this.removeListener("error",au),this.on("error",eu),r&&(r._readyState=te.CLOSING,this.destroy())}});var fu=J((k1,du)=>{"use strict";var x1=Di(),{Duplex:Zg}=require("stream");function cu(r){r.emit("close")}function Gg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function uu(r){this.removeListener("error",uu),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Kg(r,e){let t=!0,n=new Zg({...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(cu,n);return}let a=!1;r.once("error",function(c){a=!0,o(c)}),r.once("close",function(){a||o(i),process.nextTick(cu,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",Gg),n.on("error",uu),n}du.exports=Kg});var pu=J((F1,hu)=>{"use strict";var{tokenChars:Hg}=Or();function Jg(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&&Hg[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}hu.exports={parse:Jg}});var wu=J((T1,Du)=>{"use strict";var Yg=require("events"),wi=require("http"),{Duplex:P1}=require("stream"),{createHash:Qg}=require("crypto"),mu=oo(),tr=dn(),Xg=pu(),ey=Di(),{CLOSE_TIMEOUT:ty,GUID:ry,kWebSocket:ny}=st(),iy=/^[+/0-9A-Za-z]{22}==$/,gu=0,yu=1,vu=2,fo=class extends Yg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ty,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ey,...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=sy(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=gu}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===vu){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!==yu)if(this._state=yu,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",bu);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||!iy.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=Xg.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=mu.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[ny])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>gu)return gn(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Qg("sha1").update(t+ry).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=mu.format({[tr.extensionName]:[f]});u.push(`Sec-WebSocket-Extensions: ${d}`),h._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
|
|
9
9
|
`).join(`\r
|
|
10
|
-
`)),o.removeListener("error",
|
|
10
|
+
`)),o.removeListener("error",bu),h.setSocket(o,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(mn,this)})),l(h,i)}};Du.exports=fo;function sy(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function mn(r){r._state=vu,r.emit("close")}function bu(){this.destroy()}function gn(r,e,t,n){t=t||wi.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${wi.STATUS_CODES[e]}\r
|
|
11
11
|
`+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
|
|
12
12
|
`)+`\r
|
|
13
13
|
\r
|
|
14
|
-
`+t)}function rr(r,e,t,n,i,o){if(r.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,rr),r.emit("wsClientError",a,t,e)}else gn(t,n,i,o)}});var
|
|
15
|
-
|
|
16
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function
|
|
14
|
+
`+t)}function rr(r,e,t,n,i,o){if(r.listenerCount("wsClientError")){let a=new Error(i);Error.captureStackTrace(a,rr),r.emit("wsClientError",a,t,e)}else gn(t,n,i,o)}});var Cu=J((A1,Su)=>{"use strict";var ct=Di();ct.createWebSocketStream=fu();ct.Server=wu();ct.Receiver=to();ct.Sender=io();ct.WebSocket=ct;ct.WebSocketServer=ct.Server;Su.exports=ct});var _u=J(Nr=>{"use strict";var oy=Nr&&Nr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Nr,"__esModule",{value:!0});Nr.WebSocket=void 0;var ay=oy(Cu());Nr.WebSocket=ay.default});var Eu=J(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.WebSocket=We.terminalSize=We.readFileAsBase64=We.generateRandomBase64=void 0;var ly=dc();Object.defineProperty(We,"generateRandomBase64",{enumerable:!0,get:function(){return ly.generateRandomBase64}});var cy=fc();Object.defineProperty(We,"readFileAsBase64",{enumerable:!0,get:function(){return cy.readFileAsBase64}});var uy=yc();Object.defineProperty(We,"terminalSize",{enumerable:!0,get:function(){return uy.terminalSize}});var dy=_u();Object.defineProperty(We,"WebSocket",{enumerable:!0,get:function(){return dy.WebSocket}})});var Zn=Me(require("fs")),fl=Me(require("path"));function hl(r){let e="";try{let n=Zn.readdirSync(r).filter(i=>!i.startsWith(".")&&i!=="node_modules"&&i!=="dist");for(let i of n.slice(0,100)){let a=Zn.statSync(fl.join(r,i)).isDirectory();e+=`${i} [${a?"folder":"file"}]
|
|
15
|
+
`}}catch{}return e}function pl(r){try{let e=r.match(/\[[\s\S]*\]/);if(!e)throw new Error("No JSON array found in response");let t=JSON.parse(e[0]);if(!Array.isArray(t))throw new Error("Response is not an array");return t.filter(n=>!n.type||!n.path?!1:["view","create","modify","delete","rename","list"].includes(n.type))}catch(e){let t=e instanceof Error?e.message:"Unknown error";return console.error("Failed to parse workspace actions:",t),[]}}function Gn(r){return r.replace(/\\n/g,`
|
|
16
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function ml(r){let e=r.trim();return e.startsWith("```")&&(e=e.replace(/^```[a-z]*\n?/,"").replace(/\n?```$/,"").trim()),e}var gl=["(\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"],yl=["(\u0E51\u2022\uFE4F\u2022)","(\u30FB_\u30FB\u30FE","( \u02D8\u03C9\u02D8 )","(\xB4-\u03C9-`)","( \xB4 \u25BD ` )"];function Kn(){return gl[Math.floor(Math.random()*gl.length)]}function Xr(){return yl[Math.floor(Math.random()*yl.length)]}var en=Me(require("node:fs"),1),xs=require("node:path");var Dw=Me(ys(),1),vl="11434",Dl=`http://127.0.0.1:${vl}`,zh="0.6.3",qh=Object.defineProperty,Vh=(r,e,t)=>e in r?qh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,bs=(r,e,t)=>(Vh(r,typeof e!="symbol"?e+"":e,t),t),ws=class r extends Error{constructor(e,t){super(e),this.error=e,this.status_code=t,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,r)}},Ss=class{constructor(e,t,n){bs(this,"abortController"),bs(this,"itr"),bs(this,"doneCallback"),this.abortController=e,this.itr=t,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.")}},Cs=async r=>{if(r.ok)return;let e=`Error ${r.status}: ${r.statusText}`,t=null;if(r.headers.get("content-type")?.includes("application/json"))try{t=await r.json(),e=t.error||e}catch{console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await r.text()||e}catch{console.log("Failed to get text from error response")}throw new ws(e,r.status)};function Wh(){if(typeof window<"u"&&window.navigator){let r=navigator;return"userAgentData"in r&&r.userAgentData?.platform?`${r.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 Zh(r){if(r instanceof Headers){let e={};return r.forEach((t,n)=>{e[n]=t}),e}else return Array.isArray(r)?Object.fromEntries(r):r||{}}var Gh=(r,e)=>r[e],_s=async(r,e,t={})=>{let n={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${zh} (${Wh()})`};t.headers=Zh(t.headers);try{let o=new URL(e);if(o.protocol==="https:"&&o.hostname==="ollama.com"){let a=typeof process=="object"&&process!==null&&typeof process.env=="object"&&process.env!==null?Gh(process.env,"OLLAMA_API_KEY"):void 0;!(t.headers.authorization||t.headers.Authorization)&&a&&(t.headers.Authorization=`Bearer ${a}`)}}catch(o){console.error("error parsing url",o)}let i=Object.fromEntries(Object.entries(t.headers).filter(([o])=>!Object.keys(n).some(a=>a.toLowerCase()===o.toLowerCase())));return t.headers={...n,...i},r(e,t)},vs=async(r,e,t)=>{let n=await _s(r,e,{headers:t?.headers});return await Cs(n),n},vt=async(r,e,t,n)=>{let o=(l=>l!==null&&typeof l=="object"&&!Array.isArray(l))(t)?JSON.stringify(t):t,a=await _s(r,e,{method:"POST",body:o,signal:n?.signal,headers:n?.headers});return await Cs(a),a},Kh=async(r,e,t,n)=>{let i=await _s(r,e,{method:"DELETE",body:JSON.stringify(t),headers:n?.headers});return await Cs(i),i},Hh=async function*(r){let e=new TextDecoder("utf-8"),t="",n=r.getReader();for(;;){let{done:i,value:o}=await n.read();if(i)break;t+=e.decode(o,{stream:!0});let a=t.split(`
|
|
17
17
|
`);t=a.pop()??"";for(let l of a)try{yield JSON.parse(l)}catch{console.warn("invalid json: ",l)}}t+=e.decode();for(let i of t.split(`
|
|
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
|
|
18
|
+
`).filter(o=>o!==""))try{yield JSON.parse(i)}catch{console.warn("invalid json: ",i)}},Jh=r=>{if(!r)return Dl;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=vl);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},Yh=Object.defineProperty,Qh=(r,e,t)=>e in r?Yh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ds=(r,e,t)=>(Qh(r,typeof e!="symbol"?e+"":e,t),t),Es=class{constructor(e){Ds(this,"config"),Ds(this,"fetch"),Ds(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=Jh(e?.host??Dl)),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 vt(this.fetch,n,t,{signal:o.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let l=Hh(a.body),c=new Ss(o,l,()=>{let u=this.ongoingStreamedRequests.indexOf(c);u>-1&&this.ongoingStreamedRequests.splice(u,1)});return this.ongoingStreamedRequests.push(c),c}return await(await vt(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 Kh(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await vt(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await vs(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await vt(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await vt(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await vt(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await vs(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await vs(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 vt(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 vt(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},Sw=new Es;var Ew=Me(ys(),1),tn=class extends Es{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,xs.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,xs.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)}},xw=new tn;var s={};$h(s,{BRAND:()=>_p,DIRTY:()=>jt,EMPTY_PATH:()=>rp,INVALID:()=>L,NEVER:()=>lm,OK:()=>he,ParseStatus:()=>ue,Schema:()=>W,ZodAny:()=>St,ZodArray:()=>it,ZodBigInt:()=>Lt,ZodBoolean:()=>Nt,ZodBranded:()=>nn,ZodCatch:()=>Jt,ZodDate:()=>$t,ZodDefault:()=>Ht,ZodDiscriminatedUnion:()=>Qn,ZodEffects:()=>Ae,ZodEnum:()=>Gt,ZodError:()=>De,ZodFirstPartyTypeKind:()=>F,ZodFunction:()=>ei,ZodIntersection:()=>Vt,ZodIssueCode:()=>k,ZodLazy:()=>Wt,ZodLiteral:()=>Zt,ZodMap:()=>_r,ZodNaN:()=>xr,ZodNativeEnum:()=>Kt,ZodNever:()=>je,ZodNull:()=>zt,ZodNullable:()=>qe,ZodNumber:()=>Bt,ZodObject:()=>we,ZodOptional:()=>Pe,ZodParsedType:()=>R,ZodPipeline:()=>sn,ZodPromise:()=>Ct,ZodReadonly:()=>Yt,ZodRecord:()=>Xn,ZodSchema:()=>W,ZodSet:()=>Er,ZodString:()=>wt,ZodSymbol:()=>Sr,ZodTransformer:()=>Ae,ZodTuple:()=>ze,ZodType:()=>W,ZodUndefined:()=>Ut,ZodUnion:()=>qt,ZodUnknown:()=>nt,ZodVoid:()=>Cr,addIssueToContext:()=>T,any:()=>Ip,array:()=>Bp,bigint:()=>Fp,boolean:()=>Al,coerce:()=>am,custom:()=>Fl,date:()=>Pp,datetimeRegex:()=>xl,defaultErrorMap:()=>tt,discriminatedUnion:()=>Up,effect:()=>Xp,enum:()=>Jp,function:()=>Gp,getErrorMap:()=>vr,getParsedType:()=>Ue,instanceof:()=>xp,intersection:()=>zp,isAborted:()=>Jn,isAsync:()=>Dr,isDirty:()=>Yn,isValid:()=>Dt,late:()=>Ep,lazy:()=>Kp,literal:()=>Hp,makeIssue:()=>rn,map:()=>Wp,nan:()=>kp,nativeEnum:()=>Yp,never:()=>Mp,null:()=>Rp,nullable:()=>tm,number:()=>Tl,object:()=>Lp,objectUtil:()=>ks,oboolean:()=>om,onumber:()=>sm,optional:()=>em,ostring:()=>im,pipeline:()=>nm,preprocess:()=>rm,promise:()=>Qp,quotelessJson:()=>Xh,record:()=>Vp,set:()=>Zp,setErrorMap:()=>tp,strictObject:()=>Np,string:()=>Pl,symbol:()=>Tp,transformer:()=>Xp,tuple:()=>qp,undefined:()=>Ap,union:()=>$p,unknown:()=>Op,util:()=>G,void:()=>jp});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 ks;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ks||(ks={}));var R=G.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ue=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 k=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"]),Xh=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 ep=(r,e)=>{let t;switch(r.code){case k.invalid_type:r.received===R.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case k.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,G.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:t=`Unrecognized key(s) in object: ${G.joinValues(r.keys,", ")}`;break;case k.invalid_union:t="Invalid input";break;case k.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${G.joinValues(r.options)}`;break;case k.invalid_enum_value:t=`Invalid enum value. Expected ${G.joinValues(r.options)}, received '${r.received}'`;break;case k.invalid_arguments:t="Invalid function arguments";break;case k.invalid_return_type:t="Invalid function return type";break;case k.invalid_date:t="Invalid date";break;case k.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 k.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 k.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 k.custom:t="Invalid input";break;case k.invalid_intersection_types:t="Intersection results could not be merged";break;case k.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case k.not_finite:t="Number must be finite";break;default:t=e.defaultError,G.assertNever(r)}return{message:t}},tt=ep;var wl=tt;function tp(r){wl=r}function vr(){return wl}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}},rp=[];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===tt?void 0:tt].filter(i=>!!i)});r.common.issues.push(n)}var ue=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}),he=r=>({status:"valid",value:r}),Jn=r=>r.status==="aborted",Yn=r=>r.status==="dirty",Dt=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 Te=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}},Sl=(r,e)=>{if(Dt(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 Ue(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ue(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ue,ctx:{common:e.parent.common,data:e.data,parsedType:Ue(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:Ue(e)},i=this._parseSync({data:e,path:n.path,parent:n});return Sl(n,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ue(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return Dt(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=>Dt(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:Ue(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(Dr(i)?i:Promise.resolve(i));return Sl(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:k.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 Ae({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 Pe.create(this,this._def)}nullable(){return qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return it.create(this)}promise(){return Ct.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 Ae({...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}},np=/^c[^\s-]{8,}$/i,ip=/^[0-9a-z]+$/,sp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,op=/^[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,ap=/^[a-z0-9_-]{21}$/i,lp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cp=/^[-+]?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)?)??$/,up=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,dp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fs,fp=/^(?:(?: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])$/,hp=/^(?:(?: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])$/,pp=/^(([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]))$/,mp=/^(([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])$/,gp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_l="((\\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])))",bp=new RegExp(`^${_l}$`);function El(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 vp(r){return new RegExp(`^${El(r)}$`)}function xl(r){let e=`${_l}T${El(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 Dp(r,e){return!!((e==="v4"||!e)&&fp.test(r)||(e==="v6"||!e)&&pp.test(r))}function wp(r,e){if(!lp.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 Sp(r,e){return!!((e==="v4"||!e)&&hp.test(r)||(e==="v6"||!e)&&mp.test(r))}var wt=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:k.invalid_type,expected:R.string,received:o.parsedType}),L}let n=new ue,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:k.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:k.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:k.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):l&&T(i,{code:k.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")up.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"email",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Fs||(Fs=new RegExp(dp,"u")),Fs.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"emoji",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")op.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"uuid",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")ap.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"nanoid",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")np.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cuid",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")ip.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cuid2",code:k.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")sp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"ulid",code:k.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:k.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:k.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:k.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:k.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:k.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?xl(o).test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?bp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?vp(o).test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{code:k.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?cp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"duration",code:k.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?Dp(e.data,o.version)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"ip",code:k.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?wp(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"jwt",code:k.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?Sp(e.data,o.version)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"cidr",code:k.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?gp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"base64",code:k.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?yp.test(e.data)||(i=this._getOrReturnCtx(e,i),T(i,{validation:"base64url",code:k.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:k.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}};wt.create=r=>new wt({checks:[],typeName:F.ZodString,coerce:r?.coerce??!1,...V(r)});function Cp(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:k.invalid_type,expected:R.number,received:o.parsedType}),L}let n,i=new ue;for(let o of this._def.checks)o.kind==="int"?G.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:k.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:k.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:k.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Cp(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:k.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:k.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 ue;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:k.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:k.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:k.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:k.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:k.invalid_type,expected:R.boolean,received:n.parsedType}),L}return he(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:k.invalid_type,expected:R.date,received:o.parsedType}),L}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return T(o,{code:k.invalid_date}),L}let n=new ue,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),T(i,{code:k.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:k.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:k.invalid_type,expected:R.symbol,received:n.parsedType}),L}return he(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:k.invalid_type,expected:R.undefined,received:n.parsedType}),L}return he(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:k.invalid_type,expected:R.null,received:n.parsedType}),L}return he(e.data)}};zt.create=r=>new zt({typeName:F.ZodNull,...V(r)});var St=class extends W{constructor(){super(...arguments),this._any=!0}_parse(e){return he(e.data)}};St.create=r=>new St({typeName:F.ZodAny,...V(r)});var nt=class extends W{constructor(){super(...arguments),this._unknown=!0}_parse(e){return he(e.data)}};nt.create=r=>new nt({typeName:F.ZodUnknown,...V(r)});var je=class extends W{_parse(e){let t=this._getOrReturnCtx(e);return T(t,{code:k.invalid_type,expected:R.never,received:t.parsedType}),L}};je.create=r=>new je({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:k.invalid_type,expected:R.void,received:n.parsedType}),L}return he(e.data)}};Cr.create=r=>new Cr({typeName:F.ZodVoid,...V(r)});var it=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:k.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?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&&t.data.length<i.minLength.value&&(T(t,{code:k.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:k.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 Te(t,a,t.path,l)))).then(a=>ue.mergeArray(n,a));let o=[...t.data].map((a,l)=>i.type._parseSync(new Te(t,a,t.path,l)));return ue.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)}};it.create=(r,e)=>new it({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]=Pe.create(wr(n))}return new we({...r._def,shape:()=>e})}else return r instanceof it?new it({...r._def,type:wr(r.element)}):r instanceof Pe?Pe.create(wr(r.unwrap())):r instanceof qe?qe.create(wr(r.unwrap())):r instanceof ze?ze.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:k.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 je&&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 Te(i,f,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof je){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 Te(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=>ue.mergeObjectSync(n,u)):ue.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 Pe;)o=o._def.innerType;t[n]=o}return new r({...this._def,shape:()=>t})}keyof(){return kl(G.objectKeys(this.shape))}};we.create=(r,e)=>new we({shape:()=>r,unknownKeys:"strip",catchall:je.create(),typeName:F.ZodObject,...V(e)});we.strictCreate=(r,e)=>new we({shape:()=>r,unknownKeys:"strict",catchall:je.create(),typeName:F.ZodObject,...V(e)});we.lazycreate=(r,e)=>new we({shape:r,unknownKeys:"strip",catchall:je.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:k.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:k.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 rt=r=>r instanceof Wt?rt(r.schema):r instanceof Ae?rt(r.innerType()):r instanceof Zt?[r.value]:r instanceof Gt?r.options:r instanceof Kt?G.objectValues(r.enum):r instanceof Ht?rt(r._def.innerType):r instanceof Ut?[void 0]:r instanceof zt?[null]:r instanceof Pe?[void 0,...rt(r.unwrap())]:r instanceof qe?[null,...rt(r.unwrap())]:r instanceof nn||r instanceof Yt?rt(r.unwrap()):r instanceof Jt?rt(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:k.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:k.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=rt(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 Ps(r,e){let t=Ue(r),n=Ue(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=Ps(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=Ps(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=Ps(o.value,a.value);return l.valid?((Yn(o)||Yn(a))&&t.dirty(),{status:t.value,value:l.data}):(T(n,{code:k.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 ze=class r extends W{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:k.invalid_type,expected:R.array,received:n.parsedType}),L;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"}),L;!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"}),t.dirty());let o=[...n.data].map((a,l)=>{let c=this._def.items[l]||this._def.rest;return c?c._parse(new Te(n,a,n.path,l)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>ue.mergeArray(t,a)):ue.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};ze.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ze({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:k.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 Te(n,l,n.path,l)),value:a._parse(new Te(n,n.data[l],n.path,l)),alwaysSet:l in n.data});return n.common.async?ue.mergeObjectAsync(t,i):ue.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:wt.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:k.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 Te(n,l,n.path,[u,"key"])),value:o._parse(new Te(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:k.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:k.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:k.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 Te(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:k.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(),tt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:c}})}function i(l,c){return rn({data:l,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,vr(),tt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:c}})}let o={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Ct){let l=this;return he(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 he(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:ze.create(e).rest(nt.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||ze.create([]).rest(nt.create()),returns:t||nt.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:k.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 kl(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:k.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:k.invalid_enum_value,options:n}),L}return he(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=kl;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:k.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:k.invalid_enum_value,options:i}),L}return he(e.data)}get enum(){return this._def.values}};Kt.create=(r,e)=>new Kt({values:r,typeName:F.ZodNativeEnum,...V(e)});var Ct=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:k.invalid_type,expected:R.promise,received:t.parsedType}),L;let n=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return he(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Ct.create=(r,e)=>new Ct({type:r,typeName:F.ZodPromise,...V(e)});var Ae=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(!Dt(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=>Dt(a)?Promise.resolve(i.transform(a.value,o)).then(l=>({status:t.value,value:l})):L);G.assertNever(i)}};Ae.create=(r,e,t)=>new Ae({schema:r,typeName:F.ZodEffects,effect:e,...V(t)});Ae.createWithPreprocess=(r,e,t)=>new Ae({schema:e,effect:{type:"preprocess",transform:r},typeName:F.ZodEffects,...V(t)});var Pe=class extends W{_parse(e){return this._getType(e)===R.undefined?he(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Pe.create=(r,e)=>new Pe({innerType:r,typeName:F.ZodOptional,...V(e)});var qe=class extends W{_parse(e){return this._getType(e)===R.null?he(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qe.create=(r,e)=>new qe({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:k.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 _p=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=>(Dt(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 Cl(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Fl(r,e={},t){return r?St.create().superRefine((n,i)=>{let o=r(n);if(o instanceof Promise)return o.then(a=>{if(!a){let l=Cl(e,n),c=l.fatal??t??!0;i.addIssue({code:"custom",...l,fatal:c})}});if(!o){let a=Cl(e,n),l=a.fatal??t??!0;i.addIssue({code:"custom",...a,fatal:l})}}):St.create()}var Ep={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 xp=(r,e={message:`Input not instance of ${r.name}`})=>Fl(t=>t instanceof r,e),Pl=wt.create,Tl=Bt.create,kp=xr.create,Fp=Lt.create,Al=Nt.create,Pp=$t.create,Tp=Sr.create,Ap=Ut.create,Rp=zt.create,Ip=St.create,Op=nt.create,Mp=je.create,jp=Cr.create,Bp=it.create,Lp=we.create,Np=we.strictCreate,$p=qt.create,Up=Qn.create,zp=Vt.create,qp=ze.create,Vp=Xn.create,Wp=_r.create,Zp=Er.create,Gp=ei.create,Kp=Wt.create,Hp=Zt.create,Jp=Gt.create,Yp=Kt.create,Qp=Ct.create,Xp=Ae.create,em=Pe.create,tm=qe.create,rm=Ae.createWithPreprocess,nm=sn.create,im=()=>Pl().optional(),sm=()=>Tl().optional(),om=()=>Al().optional(),am={string:(r=>wt.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 lm=L;var Sn=Me(require("process"),1),I=Me(uc(),1),Qe=Me(Eu(),1);var ku=Symbol("Let zodToJsonSchema decide on which parser to use");var xu={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"},Fu=r=>typeof r=="string"?{...xu,name:r}:{...xu,...r};var Pu=r=>{let e=Fu(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 ho(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function K(r,e,t,n,i){r[e]=t,ho(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 Tu(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 Au(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 Ru(){return{type:"boolean"}}function Ci(r,e){return $(r.type._def,e)}var Iu=(r,e)=>$(r.innerType._def,e);function po(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>po(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 fy(r,e)}}var fy=(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 Ou(r,e){return{...$(r.innerType._def,e),default:r.defaultValue()}}function Mu(r,e){return e.effectStrategy==="input"?$(r.schema._def,e):re(e)}function ju(r){return{type:"string",enum:Array.from(r.values)}}var hy=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Bu(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(hy(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 Lu(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 mo,Le={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:()=>(mo===void 0&&(mo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),mo),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":Ne(t,"email",n.message,e);break;case"format:idn-email":Ne(t,"idn-email",n.message,e);break;case"pattern:zod":ge(t,Le.email,n.message,e);break}break;case"url":Ne(t,"uri",n.message,e);break;case"uuid":Ne(t,"uuid",n.message,e);break;case"regex":ge(t,n.regex,n.message,e);break;case"cuid":ge(t,Le.cuid,n.message,e);break;case"cuid2":ge(t,Le.cuid2,n.message,e);break;case"startsWith":ge(t,RegExp(`^${go(n.value,e)}`),n.message,e);break;case"endsWith":ge(t,RegExp(`${go(n.value,e)}$`),n.message,e);break;case"datetime":Ne(t,"date-time",n.message,e);break;case"date":Ne(t,"date",n.message,e);break;case"time":Ne(t,"time",n.message,e);break;case"duration":Ne(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":{ge(t,RegExp(go(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Ne(t,"ipv4",n.message,e),n.version!=="v4"&&Ne(t,"ipv6",n.message,e);break}case"base64url":ge(t,Le.base64url,n.message,e);break;case"jwt":ge(t,Le.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&ge(t,Le.ipv4Cidr,n.message,e),n.version!=="v4"&&ge(t,Le.ipv6Cidr,n.message,e);break}case"emoji":ge(t,Le.emoji(),n.message,e);break;case"ulid":{ge(t,Le.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ne(t,"binary",n.message,e);break}case"contentEncoding:base64":{K(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ge(t,Le.base64,n.message,e);break}}break}case"nanoid":ge(t,Le.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function go(r,e){return e.patternStrategy==="escape"?my(r):r}var py=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function my(r){let e="";for(let t=0;t<r.length;t++)py.has(r[t])||(e+="\\"),e+=r[t];return e}function Ne(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 ge(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:Nu(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):K(r,"pattern",Nu(e,n),t,n)}function Nu(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
|
|
19
19
|
]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
|
|
20
20
|
]))`;continue}}if(t.s&&n[c]==="."){i+=a?`${n[c]}\r
|
|
21
21
|
`:`[${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(`
|
|
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 $u(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 Uu(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 zu(r){return r.target==="openAi"?void 0:{not:re({...r,currentPath:[...r.currentPath,"not"]})}}function qu(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var yn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Wu(r,e){if(e.target==="openApi3")return Vu(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 Vu(r,e)}var Vu=(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 Zu(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 Gu(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",ho(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 Ku(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=yy(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=gy(r,e);return a!==void 0&&(n.additionalProperties=a),n}function gy(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 yy(r){try{return r.isOptional()}catch{return!0}}var Hu=(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 Ju=(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 Yu(r,e){return $(r.type._def,e)}function Qu(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 Xu(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 ed(r){return{not:re(r)}}function td(r){return re(r)}var rd=(r,e)=>$(r.innerType._def,e);var nd=(r,e,t)=>{switch(e){case F.ZodString:return _i(r,t);case F.ZodNumber:return Gu(r,t);case F.ZodObject:return Ku(r,t);case F.ZodBigInt:return Au(r,t);case F.ZodBoolean:return Ru();case F.ZodDate:return po(r,t);case F.ZodUndefined:return ed(t);case F.ZodNull:return qu(t);case F.ZodArray:return Tu(r,t);case F.ZodUnion:case F.ZodDiscriminatedUnion:return Wu(r,t);case F.ZodIntersection:return Bu(r,t);case F.ZodTuple:return Xu(r,t);case F.ZodRecord:return Ei(r,t);case F.ZodLiteral:return Lu(r,t);case F.ZodEnum:return ju(r);case F.ZodNativeEnum:return Uu(r);case F.ZodNullable:return Zu(r,t);case F.ZodOptional:return Hu(r,t);case F.ZodMap:return $u(r,t);case F.ZodSet:return Qu(r,t);case F.ZodLazy:return()=>r.getter()._def;case F.ZodPromise:return Yu(r,t);case F.ZodNaN:case F.ZodNever:return zu(t);case F.ZodEffects:return Mu(r,t);case F.ZodAny:return re(t);case F.ZodUnknown:return td(t);case F.ZodDefault:return Ou(r,t);case F.ZodBranded:return Ci(r,t);case F.ZodReadonly:return rd(r,t);case F.ZodCatch:return Iu(r,t);case F.ZodPipeline:return Ju(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!==ku)return l}if(n&&!t){let l=by(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=nd(r,r.typeName,e),a=typeof o=="function"?$(o(),e):o;if(a&&vy(r,e,a),e.postProcess){let l=e.postProcess(a,r,e);return i.jsonSchema=a,l}return i.jsonSchema=a,a}var by=(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}},vy=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var xi=(r,e)=>{let t=Pu(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 Dy(r){return typeof r=="object"&&r!==null&&typeof r.get=="function"&&typeof r.subscribe=="function"}var Pt=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(Dy(this))return $e.deriveFrom([this],e);let n=this;if(n.get!==void 0){if(n.get()===$e.NOT_AVAILABLE)return $e.createWithoutInitialValue(a=>n.subscribe(l=>{ft(l)&&a(e(l))}));let o=n;return $e.create(e(o.get()),a=>o.subscribe(l=>{a(e(l))}),t)}return $e.createWithoutInitialValue(i=>this.subscribe(o=>{ft(o)&&i(e(o))}),t)}},Cn=class r extends Pt{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 qa=Symbol.for("immer-nothing"),vn=Symbol.for("immer-draftable"),Y=Symbol.for("immer-state"),Gd=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=Gd[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 Xe(r){return r?Kd(r)||Array.isArray(r)||!!r[vn]||!!r.constructor?.[vn]||$n(r)||Un(r):!1}var wy=Object.prototype.constructor.toString();function Kd(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)===wy}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 yo(r,e){return pr(r)===2?r.get(e):r[e]}function Hd(r,e,t){let n=pr(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function Sy(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 le(r){return r.copy_||r.base_}function jo(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=Kd(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 Va(r,e=!1){return us(r)||hr(r)||!Xe(r)||(pr(r)>1&&(r.set=r.add=r.clear=r.delete=Cy),Object.freeze(r),e&&Object.values(r).forEach(t=>Va(t,!0))),r}function Cy(){ie(2)}function us(r){return Object.isFrozen(r)}var Bo={};function mr(r){let e=Bo[r];return e||ie(0,r),e}function Jd(r,e){Bo[r]||(Bo[r]=e)}var En;function Ui(){return En}function _y(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function id(r,e){e&&(mr("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function Lo(r){No(r),r.drafts_.forEach(Ey),r.drafts_=null}function No(r){r===En&&(En=r.parent_)}function sd(r){return En=_y(En,r)}function Ey(r){let e=r[Y];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function od(r,e){e.unfinalizedDrafts_=e.drafts_.length;let t=e.drafts_[0];return r!==void 0&&r!==t?(t[Y].modified_&&(Lo(e),ie(4)),Xe(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,[]),Lo(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==qa?r:void 0}function zi(r,e,t){if(us(e))return e;let n=e[Y];if(!n)return Gr(e,(i,o)=>ad(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)=>ad(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 ad(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(Hd(t,n,c),hr(c))r.canAutoFreeze_=!1;else return}else a&&t.add(i);if(Xe(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_&&Va(e,t)}function xy(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=Wa;t&&(i=[n],o=xn);let{revoke:a,proxy:l}=Proxy.revocable(i,o);return n.draft_=l,n.revoke_=a,l}var Wa={get(r,e){if(e===Y)return r;let t=le(r);if(!_n(t,e))return ky(r,t,e);let n=t[e];return r.finalized_||!Xe(n)?n:n===bo(r.base_,e)?(vo(r),r.copy_[e]=kn(n,r)):n},has(r,e){return e in le(r)},ownKeys(r){return Reflect.ownKeys(le(r))},set(r,e,t){let n=Yd(le(r),e);if(n?.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){let i=bo(le(r),e),o=i?.[Y];if(o&&o.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(Sy(t,i)&&(t!==void 0||_n(r.base_,e)))return!0;vo(r),dt(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 bo(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,vo(r),dt(r)):delete r.assigned_[e],r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){let t=le(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(Wa,(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),Wa.set.call(this,r[0],e,t,r[0])};function bo(r,e){let t=r[Y];return(t?le(t):r)[e]}function ky(r,e,t){let n=Yd(e,t);return n?"value"in n?n.value:n.get?.call(r.draft_):void 0}function Yd(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 dt(r){r.modified_||(r.modified_=!0,r.parent_&&dt(r.parent_))}function vo(r){r.copy_||(r.copy_=jo(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var Fy=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(Xe(e)){let o=sd(this),a=kn(e,void 0),l=!0;try{i=t(a),l=!1}finally{l?Lo(o):No(o)}return id(o,n),od(i,o)}else if(!e||typeof e!="object"){if(i=t(e),i===void 0&&(i=e),i===qa&&(i=void 0),this.autoFreeze_&&Va(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){Xe(r)||ie(8),hr(r)&&(r=Py(r));let e=sd(this),t=kn(r,void 0);return t[Y].isManual_=!0,No(e),t}finishDraft(r,e){let t=r&&r[Y];(!t||!t.isManual_)&&ie(9);let{scope_:n}=t;return id(n,e),od(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):xy(r,e);return(e?e.scope_:Ui()).drafts_.push(t),t}function Py(r){return hr(r)||ie(10,r),Qd(r)}function Qd(r){if(!Xe(r)||us(r))return r;let e=r[Y],t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=jo(r,e.scope_.immer_.useStrictShallowCopy_)}else t=jo(r,!0);return Gr(t,(n,i)=>{Hd(t,n,Qd(i))}),e&&(e.finalized_=!1),t}function Ty(){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 le(this[Y]).size}has(c){return le(this[Y]).has(c)}set(c,u){let h=this[Y];return a(h),(!le(h).has(c)||le(h).get(c)!==u)&&(t(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[Y];return a(u),t(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[Y];a(c),le(c).size&&(t(c),dt(c),c.assigned_=new Map,Gr(c.base_,u=>{c.assigned_.set(u,!1)}),c.copy_.clear())}forEach(c,u){let h=this[Y];le(h).forEach((f,d,p)=>{c.call(u,this.get(d),d,this)})}get(c){let u=this[Y];a(u);let h=le(u).get(c);if(u.finalized_||!Xe(h)||h!==u.base_.get(c))return h;let f=kn(h,u);return t(u),u.copy_.set(c,f),f}keys(){return le(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 le(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),dt(u),u.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let u=this[Y];return a(u),o(u),dt(u),u.copy_.delete(c)||(u.drafts_.has(c)?u.copy_.delete(u.drafts_.get(c)):!1)}clear(){let c=this[Y];a(c),le(c).size&&(o(c),dt(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(Xe(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(le(l)))}Jd("MapSet",{proxyMap_:e,proxySet_:i})}function Ay(){process.env.NODE_ENV!=="production"&&Gd.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=yo(b,D),_=yo(y,D),x=v?_n(b,D)?e:t:n;if(S===_&&x===e)return;let E=p.concat(D);m.push(x===n?{op:x,path:E}:{op:x,path:E,value:_}),g.push(x===t?{op:n,path:E}:x===n?{op:t,path:E,value:f(S)}:{op:e,path:E,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===qa?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 x=pr(y),E=g[_];typeof E!="string"&&typeof E!="number"&&(E=""+E),(x===0||x===1)&&(E==="__proto__"||E==="constructor")&&ie(19),typeof y=="function"&&E==="prototype"&&ie(19),y=yo(y,E),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(!Xe(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}Jd("Patches",{applyPatches_:u,generatePatches_:i,generateReplacementPatches_:c})}var ke=new Fy;ke.produce;var Ry=ke.produceWithPatches.bind(ke);ke.setAutoFreeze.bind(ke);ke.setUseStrictShallowCopy.bind(ke);var $o=ke.applyPatches.bind(ke);ke.createDraft.bind(ke);ke.finishDraft.bind(ke);Ty();Ay();function $r(...r){return r.filter(e=>e!==void 0).reduce((e,t)=>e.concat(t),[])}function ld(r){return[{op:"replace",path:[],value:r}]}function Za(r,e){let t=(n,i)=>{r(()=>[n,ld(n)],$r(e?.(),i))};return t.withProducer=(n,i)=>{r(o=>{let[a,l]=Ry(o,n);if(ft(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,ld(a)]},$r(e?.(),i))},t.withPatchUpdater=(n,i)=>{r(n,$r(e?.(),i))},t.withPatches=(n,i)=>{r(o=>[$o(o,n),n],$r(e?.(),i))},t.withValueAndPatches=(n,i,o)=>{r(()=>[n,i],$r(e?.(),o))},t}var Iy=(r,e)=>r===e,Fn=class r extends Pt{static create(e,t=Iy){let n=new r(e,t),o=Za((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 ft(r){return r!==$e.NOT_AVAILABLE}var $e=class r extends Pt{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();ft(h)&&a(h)})),c=o();return ft(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(ft(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(Za((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(ft(t)&&e(t))return t;let{promise:n,resolve:i}=ee(),o=this.subscribe(a=>{ft(a)&&e(a)&&(i(a),o())});return await n}},Oy=[41343,52993,16141,39414,22931],bn=Symbol(),pt=class r extends Pt{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}},Uo=class extends Pt{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
23
|
`).slice(2+r).join(`
|
|
24
|
-
`):""}function
|
|
24
|
+
`):""}function Do(r,e){if(Sn.default.env.LMS_KEEP_INTERNAL_STACK)return;let t=r.stack??"";r.stack=(t.substring(0,t.indexOf(`
|
|
25
25
|
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,r(i));return n};return Ti.exports=e,Ti.exports.default=e,Ti.exports}var Ai={exports:{}}
|
|
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(`
|
|
26
|
+
`+e).trimEnd()}var Wi=class{constructor(e=0){this.nextId=e}next(){let e=this.nextId;return this.nextId++,e}};function My(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var ki={exports:{}},Fi={exports:{}},wo,cd;function jy(){return cd||(cd=1,wo=({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")}),wo}var So,ud;function Xd(){if(ud)return So;ud=1;let r=jy();return So=e=>typeof e=="string"?e.replace(r(),""):e,So}var Pi={exports:{}},dd;function By(){if(dd)return Pi.exports;dd=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 Co,fd;function Ly(){return fd||(fd=1,Co=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}),Co}var hd;function ds(){if(hd)return Fi.exports;hd=1;let r=Xd(),e=By(),t=Ly(),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:{}},pd;function Ny(){if(pd)return Ti.exports;pd=1;let r=ds(),e=t=>{let n=0;for(let i of t.split(`
|
|
27
|
+
`))n=Math.max(n,r(i));return n};return Ti.exports=e,Ti.exports.default=e,Ti.exports}var Ai={exports:{}},$y={topLeft:"\u250C",topRight:"\u2510",bottomRight:"\u2518",bottomLeft:"\u2514",vertical:"\u2502",horizontal:"\u2500"},Uy={topLeft:"\u2554",topRight:"\u2557",bottomRight:"\u255D",bottomLeft:"\u255A",vertical:"\u2551",horizontal:"\u2550"},zy={topLeft:"\u256D",topRight:"\u256E",bottomRight:"\u256F",bottomLeft:"\u2570",vertical:"\u2502",horizontal:"\u2500"},qy={topLeft:"\u250F",topRight:"\u2513",bottomRight:"\u251B",bottomLeft:"\u2517",vertical:"\u2503",horizontal:"\u2501"},Vy={topLeft:"\u2553",topRight:"\u2556",bottomRight:"\u255C",bottomLeft:"\u2559",vertical:"\u2551",horizontal:"\u2500"},Wy={topLeft:"\u2552",topRight:"\u2555",bottomRight:"\u255B",bottomLeft:"\u2558",vertical:"\u2502",horizontal:"\u2550"},Zy={topLeft:"+",topRight:"+",bottomRight:"+",bottomLeft:"+",vertical:"|",horizontal:"-"},Gy={single:$y,double:Uy,round:zy,bold:qy,singleDouble:Vy,doubleSingle:Wy,classic:Zy},md;function Ky(){if(md)return Ai.exports;md=1;let r=Gy;return Ai.exports=r,Ai.exports.default=r,Ai.exports}var Ri={exports:{}},gd;function Hy(){if(gd)return Ri.exports;gd=1;let r=/[\p{Lu}]/u,e=/[\p{Ll}]/u,t=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,i=/[_.\- ]+/,o=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,b=!1,y=!1;for(let D=0;D<d.length;D++){let v=d[D];g&&r.test(v)?(d=d.slice(0,D)+"-"+d.slice(D),g=!1,y=b,b=!0,D++):b&&y&&e.test(v)?(d=d.slice(0,D-1)+"-"+d.slice(D-1),y=b,b=!1,g=!0):(g=p(v)===v&&m(v)!==v,y=b,b=m(v)===v&&p(v)!==v)}return d},u=(d,p)=>(t.lastIndex=0,d.replace(t,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(y=>y.trim()).filter(y=>y.length).join("-"):d=d.trim(),d.length===0)return"";let m=p.locale===!1?y=>y.toLowerCase():y=>y.toLocaleLowerCase(p.locale),g=p.locale===!1?y=>y.toUpperCase():y=>y.toLocaleUpperCase(p.locale);return d.length===1?p.pascalCase?g(d):m(d):(d!==m(d)&&(d=c(d,m,g)),d=d.replace(o,""),p.preserveConsecutiveUppercase?d=u(d,m):d=m(d),p.pascalCase&&(d=g(d.charAt(0))+d.slice(1)),h(d,g))};return Ri.exports=f,Ri.exports.default=f,Ri.exports}var _o,yd;function Jy(){if(yd)return _o;yd=1;let r=ds();function e(i,o){if(!i)return i;o=o||{};let a=o.align||"center";if(a==="left")return i;let l=o.split||`
|
|
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"})},_o=e;function t(i,o){return Math.floor((i-o)/2)}function n(i,o){return i-o}return _o}var Bi={exports:{}},Eo,bd;function Yy(){return bd||(bd=1,Eo={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]}),Eo}var xo,vd;function ef(){if(vd)return xo;vd=1;let r=Yy(),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"]}};xo=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]},xo}var ko,Dd;function Qy(){if(Dd)return ko;Dd=1;let r=ef();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 ko=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},ko}var Fo,wd;function Xy(){if(wd)return Fo;wd=1;let r=ef(),e=Qy(),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)})}),Fo=t,Fo}Bi.exports;var Sd;function eb(){return Sd||(Sd=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=Xy());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 Po,Cd;function tb(){if(Cd)return Po;Cd=1;let r=ds(),e=Xd(),t=eb(),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,x=r(e(b[b.length-1]));for(let[E,z]of v.entries()){let w=r(z);if(x+w<=D?b[b.length-1]+=z:(b.push(z),x=0),n.has(z)&&(S=!0,_=v.slice(E+1).join("").startsWith(u)),S){_?z===o&&(S=!1,_=!1):z===c&&(S=!1);continue}x+=w,x===D&&E<v.length-1&&(b.push(""),x=0)}!x&&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,_,x=d(b),E=[""];for(let[w,C]of b.split(" ").entries()){D.trim!==!1&&(E[E.length-1]=E[E.length-1].trimStart());let P=r(E[E.length-1]);if(w!==0&&(P>=y&&(D.wordWrap===!1||D.trim===!1)&&(E.push(""),P=0),(P>0||D.trim===!1)&&(E[E.length-1]+=" ",P++)),D.hard&&x[w]>y){let U=y-P,Z=1+Math.floor((x[w]-U-1)/y);Math.floor((x[w]-1)/y)<Z&&E.push(""),p(E,C,y);continue}if(P+x[w]>y&&P>0&&x[w]>0){if(D.wordWrap===!1&&P<y){p(E,C,y);continue}E.push("")}if(P+x[w]>y&&D.wordWrap===!1){p(E,C,y);continue}E[E.length-1]+=C}D.trim!==!1&&(E=E.map(m));let z=[...E.join(`
|
|
29
29
|
`)];for(let[w,C]of z.entries()){if(v+=C,n.has(C)){let{groups:U}=new RegExp(`(?:\\${a}(?<code>\\d+)m|\\${u}(?<uri>.*)${o})`).exec(z.slice(w).join(""))||{groups:{}};if(U.code!==void 0){let Z=Number.parseFloat(U.code);S=Z===i?void 0:Z}else U.uri!==void 0&&(_=U.uri.length===0?void 0:U.uri)}let P=t.codes.get(Number(S));z[w+1]===`
|
|
30
30
|
`?(_&&(v+=f("")),S&&P&&(v+=h(P))):C===`
|
|
31
|
-
`&&(S&&P&&(v+=h(S)),_&&(v+=f(_)))}return v};return
|
|
31
|
+
`&&(S&&P&&(v+=h(S)),_&&(v+=f(_)))}return v};return Po=(b,y,D)=>String(b).normalize().replace(/\r\n/g,`
|
|
32
32
|
`).split(`
|
|
33
33
|
`).map(v=>g(v,y,D)).join(`
|
|
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 _ of v)if(!D[_]||typeof D[_]!="string")throw new TypeError(`Invalid border style: ${_}`);S=D}return S},d=(D,v,S)=>{let _="",
|
|
36
|
-
`),ye=Math.max(..._e.map(be=>r(be)));for(let be of _e){let Q;switch(_){case"center":Q=c.repeat((z-ye)/2)+be;break;case"right":Q=c.repeat(z-ye)+be;break;default:Q=be;break}P.push(Q)}}
|
|
34
|
+
`),Po}var _d;function rb(){if(_d)return ki.exports;_d=1;let r=ds(),e=I.default,t=Ny(),n=Ky(),i=Hy(),o=Jy(),a=tb(),l=`
|
|
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 _ of v)if(!D[_]||typeof D[_]!="string")throw new TypeError(`Invalid border style: ${_}`);S=D}return S},d=(D,v,S)=>{let _="",x=r(D);switch(S){case"left":_=D+v.slice(x);break;case"right":_=v.slice(x)+D;break;default:v=v.slice(x),v.length%2===1?(v=v.slice(Math.floor(v.length/2)),_=v.slice(1)+D+v):(v=v.slice(v.length/2),_=v+D+v);break}return _},p=(D,v,S,_)=>{D=o(D,{align:_});let x=D.split(l),E=t(D),z=S-v.left-v.right;if(E>z){let P=[];for(let U of x){let Z=a(U,z,{hard:!0}),_e=o(Z,{align:_}).split(`
|
|
36
|
+
`),ye=Math.max(..._e.map(be=>r(be)));for(let be of _e){let Q;switch(_){case"center":Q=c.repeat((z-ye)/2)+be;break;case"right":Q=c.repeat(z-ye)+be;break;default:Q=be;break}P.push(Q)}}x=P}_==="center"&&E<z?x=x.map(P=>c.repeat((z-E)/2)+P):_==="right"&&E<z&&(x=x.map(P=>c.repeat(z-E)+P));let w=c.repeat(v.left),C=c.repeat(v.right);return x=x.map(P=>w+P+C),x=x.map(P=>{if(S-r(P)>0)switch(_){case"center":return P+c.repeat(S-r(P));case"right":return P+c.repeat(S-r(P));default:return P+c.repeat(S-r(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)),b=D=>m(D)?e.hex(D):e[D],y=D=>m(D)?e.bgHex(D):e[i(["bg",D])];return ki.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 _=f(v.borderStyle),x=h(v.padding),E=h(v.margin),z=ve=>{let N=v.borderColor?b(v.borderColor)(ve):ve;return v.dimBorder?e.dim(N):N},w=ve=>v.backgroundColor?y(v.backgroundColor)(ve):ve,C=u()-1,P=t(a(D,C-S,{hard:!0,trim:!1}))+x.left+x.right,U=v.title&&v.title.slice(0,C-4-E.left-E.right);if(U&&(U=` ${U} `,r(U)>P&&(P=r(U))),E.left&&E.right&&P+S+E.left+E.right>C){let N=(C-P-S)/(E.left+E.right);E.left=Math.max(0,Math.floor(E.left*N)),E.right=Math.max(0,Math.floor(E.right*N))}P=Math.min(P,C-S-E.left-E.right),D=p(D,x,P,v.textAlignment);let Z=c.repeat(E.left);if(v.float==="center"){let ve=Math.max((C-P-S)/2,0);Z=c.repeat(ve)}else if(v.float==="right"){let ve=Math.max(C-P-E.right-S,0);Z=c.repeat(ve)}let q=_.horizontal.repeat(P),_e=z(l.repeat(E.top)+Z+_.topLeft+(U?d(U,q,v.titleAlignment):q)+_.topRight),ye=z(Z+_.bottomLeft+q+_.bottomRight+l.repeat(E.bottom)),be=z(_.vertical),Q=l,Qr=D.split(l).map(ve=>Z+be+w(ve)+be).join(Q);return _e+Q+Qr+Q+ye},ki.exports._borderStyles=n,ki.exports}var nb=rb(),ib=My(nb);function gr(r,e,t){return me(I.default.redBright(r)+`
|
|
37
37
|
|
|
38
|
-
`+e,t)}function
|
|
38
|
+
`+e,t)}function me(r,e){if(Sn.default.browser||Sn.default.env.LMS_NO_FANCY_ERRORS||(0,Qe.terminalSize)().columns<80){let t=new Error(r);return e===void 0?Do(t,""):Do(t,e),t}else{e!==void 0&&(r+=`
|
|
39
39
|
|
|
40
40
|
|
|
41
41
|
`+I.default.bgWhite.black(" </> STACK TRACE ")+`
|
|
42
42
|
|
|
43
43
|
`+I.default.gray(e));let t=new Error(`
|
|
44
|
-
`+
|
|
45
|
-
`,i+1))!==-1;)t.push(n.substring(i+1,o)),e.push(t),t=[],i=o;t.push(n.substring(i+1))}return e.push(t),e}function
|
|
44
|
+
`+ib(r,{padding:1,margin:1,borderColor:"redBright",title:"Error"}));return Object.defineProperty(t,"lmstudioRawError",{value:r,enumerable:!1}),Do(t,""),t}}var Ed=new WeakMap;function j(r,...e){if(e.length+1!==r.length)throw new Error("text called with the wrong number of arguments.");let t=Ed.get(r);t===void 0&&(t=vb(r),Ed.set(r,t));for(let n=0;n<e.length;n++)if(typeof e[n]=="object")if(typeof e[n].stack=="string")t[n*2+1]=e[n].stack;else try{t[n*2+1]=JSON.stringify(e[n])}catch{t[n*2+1]="[Object failed to stringify]"}else t[n*2+1]=String(e[n]);return t.join("")}function sb(r){return r.replace(/^\n+/,"")}function ob(r){return r.replace(/[\n ]+$/,"")}function ab(r){return r.replace(/^ +/,"")}function lb(r){return r.replace(/ +$/,"")}function cb(r){let e=[],t=[];for(let n of r){let i=-1,o;for(;(o=n.indexOf(`
|
|
45
|
+
`,i+1))!==-1;)t.push(n.substring(i+1,o)),e.push(t),t=[],i=o;t.push(n.substring(i+1))}return e.push(t),e}function ub(r){let e=0;for(let t of r)if(t===" ")e++;else return e;return 1/0}function db(r){let e=r[0],t=ub(e);return t===1/0?r.length===1?1/0:e.length:t}function fb(r){let e=1/0;for(let t of r)e=Math.min(e,db(t));return e}function hb(r,e){return r.length<e?"":r.slice(e)}function pb(r,e){for(let t of r)t[0]=hb(t[0],e)}function mb(r){if(r.length!==1)return!1;for(let e of r[0])if(e!==" ")return!1;return!0}function gb(r){let e=r.map(mb),t=[],n=[];for(let i=0;i<r.length;i++){if(e[i]){n.length!==0&&(t.push(n),n=[]);continue}if(n.length!==0){let o=lb(n[n.length-1]),a=ab(r[i][0]);n[n.length-1]=o+" "+a,n.push(...r[i].slice(1))}else n.push(...r[i])}return n.length!==0&&t.push(n),t}function yb(r){let e=[];if(r.length===0)return[""];e.push(...r[0]);for(let t=1;t<r.length;t++)e[e.length-1]+=`
|
|
46
46
|
|
|
47
|
-
`+r[t][0],e.push(...r[t].slice(1));return e}function
|
|
47
|
+
`+r[t][0],e.push(...r[t].slice(1));return e}function bb(r){let e=[];for(let t=0;t<r.length;t++)e.push(r[t]),t<r.length-1&&e.push("");return e}function vb(r){let e=[...r];e[0]=sb(e[0]),e[e.length-1]=ob(e[e.length-1]);let t=cb(e),n=fb(t);pb(t,n);let i=gb(t);return bb(yb(i))}var Zi=class{constructor(e,t){this.data=e,this.mutable=t}_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
48
|
Cannot modify immutable ${this.getClassName()} instance. Use asMutableCopy() to get a
|
|
49
49
|
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}
|
|
50
|
+
`)}};var zo=class r extends Pt{static{this.NOT_AVAILABLE=$e.NOT_AVAILABLE}applyOptimisticUpdates(e){for(let t of this.queuedUpdates)[e]=t.updater(e);return e}updateOptimisticValue(e){let t=this.innerSignal.get();ft(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=$e.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=Za(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 Db(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 wb(r){return new Promise((e,t)=>{if(r.aborted){t(r.reason);return}r.addEventListener("abort",()=>{t(r.reason)},{once:!0})})}function Sb(r,e){return Promise.race([r,wb(e)])}var Cb=["HSA_OVERRIDE_GFX_VERSION"],_b=s.enum(Cb),Eb=s.record(_b,s.string()),xb=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Pn=s.string().regex(xb),kb=/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/,Tn=s.string().regex(kb),Fb=/^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])$/u,xd=s.string().regex(Fb,{message:"Invalid file name"}),Pb=/^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ])(?:\/[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(?<![. ]))*$/u;s.string().regex(Pb,{message:"Invalid relative path"});var Tb=s.object({type:s.literal("huggingface"),user:xd,repo:xd}),tf=s.discriminatedUnion("type",[Tb]),Ab=s.enum(["baseModel","draftModel","custom"]),rf=s.object({purpose:Ab}),Rb=s.object({type:s.literal("model"),...rf.shape,modelKeys:s.array(s.string().min(1)),sources:s.array(tf)}),Ib=s.object({type:s.literal("artifact"),...rf.shape,owner:Pn,name:Tn}),Ob=s.discriminatedUnion("type",[Rb,Ib]),Ga=s.object({owner:Pn,name:Tn.min(1,"Name is required").max(100,"Name too long"),revision:s.number().int().optional(),dependencies:s.array(Ob).optional(),tags:s.array(s.string()).optional()}),Mb=/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:[-.][a-z0-9]+)*$/,jb=s.string().regex(Mb,{message:"Invalid artifact identifier format. Expected 'owner/name'."}),Bb=s.object({type:s.literal("model"),...Ga.shape}),Lb=s.enum(["ecmascript","node","mcpBridge"]),Ka=s.object({type:s.literal("plugin"),runner:Lb,...Ga.shape}),Nb=s.object({type:s.literal("preset"),...Ga.shape});s.discriminatedUnion("type",[Ka,Nb,Bb]);var $b=s.enum(["plugin","preset","model"]),nf=s.object({title:s.string(),description:s.string().optional(),noAutoDismiss:s.boolean().optional()}),sf=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:sf}),Ub=s.object({id:s.string().optional(),type:s.literal("function"),arguments:s.record(Ce).optional(),name:s.string()}),An=s.discriminatedUnion("type",[Ub]),of=s.object({type:s.literal("toolCallRequest"),toolCallRequest:An});s.object({content:s.string(),toolCallId:s.string().optional()});var af=s.object({type:s.literal("toolCallResult"),content:s.string(),toolCallId:s.string().optional()});s.discriminatedUnion("type",[Li,Ni,of,af]);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,of]))}),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(af)})]),dr=s.object({messages:s.array(ur)}),zb=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()}),qb=s.enum(["red","green","blue","yellow","orange","purple","default"]),Vb=qb,Wb=s.discriminatedUnion("type",[s.object({type:s.literal("llm.prediction.input"),modelPath:s.string(),modelIdentifier:s.string(),input:s.string()})]),Zb=s.object({timestamp:s.number(),data:Wb}),lf=s.union([s.number().min(0).max(1),s.literal("max"),s.literal("off")]),Gb=s.enum(["evenly","favorMainGpu"]),cf=s.object({ratio:lf.optional(),mainGpu:s.number().int().optional(),splitStrategy:Gb.optional(),disabledGpus:s.array(s.number().int()).optional()}),qo=["f32","f16","q8_0","q4_0","q4_1","iq4_nl","q5_0","q5_1"],Kb=s.enum(qo),Hb=s.union([s.literal(8),s.literal(6),s.literal(4),s.literal(3),s.literal(2)]),Jb=s.union([s.literal(32),s.literal(64),s.literal(128)]),Yb=s.object({enabled:s.boolean(),bits:Hb,groupSize:Jb,quantizedStart:s.number().int().nonnegative()}),Qb=s.object({gpu:cf.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(qo).or(s.literal(!1)).optional(),llamaVCacheQuantizationType:s.enum(qo).or(s.literal(!1)).optional()}),Xb=s.object({gpu:cf.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"]),e0=s.object({name:s.string(),bits:s.number().int()}),Ha=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:e0.optional()}),uf=Ha.extend({identifier:s.string(),instanceReference:s.string()}),df=s.object({maxContextLength:s.number().int()}),t0=s.object({contextLength:s.number().int()}),ff=s.object({type:s.literal("embedding")}).extend(Ha.shape).extend(df.shape),hf=s.object({type:s.literal("embedding")}).extend(uf.shape).extend(df.shape).extend(t0.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"}),Ja=s.object({domain:Rn.optional(),identifier:Vr.optional(),path:Vr.optional(),vision:s.boolean().optional()}),Je=s.discriminatedUnion("type",[s.object({type:s.literal("query"),query:Ja}),s.object({type:s.literal("instanceReference"),instanceReference:s.string()})]),r0=[s.object({code:s.literal("generic.specificModelUnloaded")}),s.object({code:s.literal("generic.noModelMatchingQuery"),query:Ja,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()})],n0=[],i0=s.discriminatedUnion("code",[...n0,...r0]);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(i0).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 pf(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 pf(n,r),r.displayData!==void 0&&(n.displayData=r.displayData),t!==void 0?r.stack!==void 0?n.stack=`Error: ${e}
|
|
51
51
|
${t}
|
|
52
52
|
- Caused By: ${r.stack}`:n.stack=`Error: ${e}
|
|
53
53
|
${t}`:r.stack!==void 0?n.stack=`Error: ${e}
|
|
54
54
|
${n.stack.substring(r.stack.indexOf(`
|
|
55
55
|
`)+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,t,n,i,o){let a=n.safeParse(i);if(a.success)return a.data;throw
|
|
56
|
+
- Caused By: `+r.stack:n.message+=` - caused by error without stack (${r.title})`,n}var Vo=s.object({library:s.string(),version:s.string()}),mf=s.object({parserId:Vo.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 s0=["evenly","priorityOrder","custom"],o0=s.enum(s0),a0={strategy:"evenly",disabledGpus:[],priority:[],customRatio:[]},l0=s.object({strategy:o0,disabledGpus:s.array(s.number().int().min(0)),priority:s.array(s.number().int().min(0)),customRatio:s.array(s.number().min(0))});function gf(r){return{strategy:r?.splitStrategy=="favorMainGpu"?"priorityOrder":r?.splitStrategy??"evenly",disabledGpus:r?.disabledGpus??[],priority:r?.mainGpu?[r.mainGpu]:[],customRatio:[]}}var yf=s.object({key:s.string(),value:s.any()}),X=s.object({fields:s.array(yf)}),c0=s.enum(["currentlyEditing","currentlyLoaded","apiOverride","conversationSpecific","conversationGlobal","preset","serverSession","httpServerRequestOverride","completeModeFormatting","instance","userModelDefault","virtualModel","modelDefault","hardware"]),u0=s.object({layerName:c0,config:X}),Ki=s.object({layers:s.array(u0)}),d0=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()})])}),bf=s.discriminatedUnion("type",[s.object({type:s.literal("default")}),s.object({type:s.literal("customLabel"),label:s.string(),color:s.optional(Vb)}),s.object({type:s.literal("thinking"),ended:s.boolean().optional(),title:s.string().optional()})]),f0=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:f0.optional()})})]);s.array(ar);var vf=s.discriminatedUnion("type",[s.object({type:s.literal("none")}),s.object({type:s.literal("toolArray"),tools:s.array(ar).optional(),force:s.boolean().optional()})]),Df=s.object({omitBosToken:s.boolean().optional(),omitEosToken:s.boolean().optional(),toolDefinitions:s.array(ar).optional()}),h0=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 wf=s.object({vision:s.boolean(),trainedForToolUse:s.boolean(),maxContextLength:s.number().int()}),p0=s.object({contextLength:s.number().int()}),Sf=s.object({type:s.literal("llm")}).extend(Ha.shape).extend(wf.shape),Wo=s.object({type:s.literal("llm")}).extend(uf.shape).extend(wf.shape).extend(p0.shape),Cf=s.enum(["passThrough","removeSpecial","snakeCase","camelCase"]),yr=s.custom(r=>typeof r?.parse=="function","Expected a zod schema"),m0=s.object({beforeSystem:s.string(),afterSystem:s.string(),beforeUser:s.string(),afterUser:s.string(),beforeAssistant:s.string(),afterAssistant:s.string()}),g0=s.object({template:s.string()}),y0=s.enum(["manual","jinja"]),_f=s.object({type:y0,manualPromptTemplate:m0.optional(),jinjaPromptTemplate:g0.optional(),stopStrings:s.array(s.string())}),b0=s.enum(["none","json","gbnf"]),Ya=s.object({type:b0,jsonSchema:Ce.optional(),gbnfGrammar:s.string().optional()}),Ef=s.enum(["stopAtLimit","truncateMiddle","rollingWindow"]),xf=s.object({enabled:s.boolean(),startString:s.string(),endString:s.string()}),Qa=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:Ef.optional(),structured:s.union([yr,Ya]).optional(),rawTools:vf.optional(),toolNaming:Cf.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:_f.optional(),draftModel:s.string().optional(),speculativeDecodingNumDraftTokensExact:s.number().int().min(1).optional(),speculativeDecodingMinDraftLengthToConsider:s.number().int().min(0).optional(),speculativeDecodingMinContinueDraftingProbability:s.number().optional(),reasoningParsing:xf.optional(),raw:X.optional()});s.object({...Qa.shape,structured:Ya.optional()});var v0=s.object({version:s.union([s.literal(0),s.literal(1),s.literal(2)]),learningRate:s.number(),targetEntropy:s.number()}),D0=s.union([s.number(),s.literal("-inf")]),w0=s.array(s.tuple([s.number(),D0])),kf=s.enum(["none","reasoning","reasoningStartTag","reasoningEndTag"]),Ff=s.object({content:s.string(),tokensCount:s.number().int(),containsDrafted:s.boolean(),reasoningType:kf,isStructural:s.boolean()}),Pf=s.object({tokenCount:s.number().int().optional(),containsDrafted:s.boolean().optional(),reasoningType:kf.optional(),isStructural:s.boolean().optional()}),S0=s.enum(["userStopped","modelUnloaded","failed","eosFound","stopStringFound","toolCalls","maxPredictedTokensReached","contextLengthReached"]),Tf=s.object({stopReason:S0,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()}),C0=s.object({indexedModelIdentifier:s.string(),identifier:s.string(),loadModelConfig:X,predictionConfig:X,stats:Tf}),_0=s.discriminatedUnion("type",[s.object({type:s.literal("beforeId"),id:s.string()}),s.object({type:s.literal("afterId"),id:s.string()})]),E0=s.enum(["waiting","loading","done","error","canceled"]),Af=s.object({status:E0,text:s.string()}),Xa=s.object({type:s.literal("status.create"),id:s.string(),state:Af,location:_0.optional(),indentation:s.number().int().optional()}),el=s.object({type:s.literal("status.update"),id:s.string(),state:Af}),tl=s.object({type:s.literal("status.remove"),id:s.string()}),rl=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()}),nl=s.object({type:s.literal("debugInfoBlock.create"),id:s.string(),debugInfo:s.string()}),Rf=s.object({type:s.literal("contentBlock.create"),id:s.string(),includeInContext:s.boolean(),roleOverride:s.enum(["user","assistant","system","tool"]).optional(),style:bf.optional(),prefix:s.string().optional(),suffix:s.string().optional()}),If=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()}),Of=s.object({type:s.literal("contentBlock.appendToolResult"),id:s.string(),callId:s.number().int(),toolCallRequestId:s.string().optional(),content:s.string()}),Mf=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()}),jf=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()}),Bf=s.object({type:s.literal("contentBlock.replaceText"),id:s.string(),text:s.string()}),x0=s.object({type:s.literal("contentBlock.setPrefix"),id:s.string(),prefix:s.string()}),k0=s.object({type:s.literal("contentBlock.setSuffix"),id:s.string(),suffix:s.string()}),Lf=s.object({type:s.literal("contentBlock.attachGenInfo"),id:s.string(),genInfo:C0}),Nf=s.object({type:s.literal("contentBlock.setStyle"),id:s.string(),style:bf}),F0=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()})]),$f=s.object({status:F0,customStatus:s.string(),customWarnings:s.array(s.string())}),Uf=s.object({type:s.literal("toolStatus.create"),id:s.string(),callId:s.number().int(),state:$f}),zf=s.object({type:s.literal("toolStatus.update"),id:s.string(),state:$f}),qf=s.object({type:s.literal("toolStatus.argumentFragment"),id:s.string(),content:s.string()}),Vf=s.object({type:s.literal("setSenderName"),name:s.string()}),P0=s.discriminatedUnion("type",[Xa,el,tl,rl,nl,Rf,If,Mf,jf,Of,Bf,x0,k0,Lf,Nf,Uf,zf,qf,Vf]);s.discriminatedUnion("type",[Xa,el,tl,rl,nl,Rf,If,Bf,Mf,jf,Of,Lf,Nf,Uf,zf,qf,Vf]);var T0=s.object({type:s.literal("confirmToolCall"),callId:s.number().int(),pluginIdentifier:s.string().optional(),name:s.string(),parameters:s.record(s.any())}),A0=s.object({type:s.literal("textInput"),prompt:s.string()}),R0=s.discriminatedUnion("type",[T0,A0]),I0=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()})])}),O0=s.object({type:s.literal("textInput"),result:s.string()}),M0=s.discriminatedUnion("type",[I0,O0]);s.object({modelTag:s.string().optional(),ignoreUserConfig:s.boolean().optional()});s.discriminatedUnion("type",[Xa,el,tl,rl,nl]);var j0=s.discriminatedUnion("type",[s.object({type:s.literal("model"),identifier:s.string()}),s.object({type:s.literal("generator"),pluginIdentifier:s.string()})]),B0=s.discriminatedUnion("type",[Sf,ff]),L0=s.discriminatedUnion("type",[Wo,hf]),kd=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()})]),Fd=s.object({identifier:s.string(),isDev:s.boolean(),isTrusted:s.boolean(),hasPromptPreprocessor:s.boolean(),hasPredictionLoopHandler:s.boolean(),hasToolsProvider:s.boolean(),hasGenerator:s.boolean()}),Pd=s.object({displayName:s.string(),sizeBytes:s.number(),quantName:s.string().optional(),compatibilityType:fs}),Td=s.enum(["pending","fetching","satisfied","completed"]),N0=s.discriminatedUnion("type",[s.object({type:s.literal("artifact"),owner:Pn,name:Tn,state:Td,artifactType:$b.optional(),sizeBytes:s.number().int().optional(),dependencyNodes:s.array(s.number().int())}),s.object({type:s.literal("model"),state:Td,resolvedSources:s.number().int().optional(),totalSources:s.number().int().optional(),alreadyOwned:Pd.optional(),selected:Pd.optional()})]),Ad=s.object({nodes:s.array(N0),downloadSizeBytes:s.number().int()}),$0=s.object({relativePath:s.string(),sizeBytes:s.number().int()}),U0=s.object({files:s.array($0),usedIgnoreFile:s.string().nullable()}),To=s.object({downloadedBytes:s.number().int(),totalBytes:s.number().int(),speedBytesPerSecond:s.number()}),z0=s.enum(["fullGPUOffload","partialGPUOffload","fitWithoutGPU","willNotFit"]),q0=s.object({quantization:s.string().optional(),name:s.string(),sizeBytes:s.number().int(),fitEstimation:z0,recommended:s.boolean().optional(),downloadIdentifier:s.string(),indexedModelIdentifier:s.string()}),Wf=s.discriminatedUnion("type",[s.object({type:s.literal("catalog"),identifier:s.string()}),s.object({type:s.literal("hf"),identifier:s.string()})]),V0=s.object({name:s.string(),identifier:Wf,exact:s.boolean().optional(),staffPick:s.boolean().optional()}),Zf=s.object({searchTerm:s.string().optional(),limit:s.number().int().positive().max(25).optional(),compatibilityTypes:s.array(fs).optional()}),W0=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()}),Z0=s.object({entries:s.array(W0)});s.object({content:s.string(),score:s.number(),citation:zb});var Gf=s.discriminatedUnion("type",[s.object({type:s.literal("recursive-v1"),chunkSize:s.number().int(),chunkOverlap:s.number().int()})]),Ao=s.enum(["loading","chunking","embedding"]),G0=s.enum(["unknown","integratedGpu","dedicatedGpu"]),K0=s.object({name:s.string(),deviceId:s.number().int(),totalMemoryBytes:s.number().int(),type:G0});s.object({key:s.string(),name:s.string(),accelerators:s.array(K0)});var H0=s.object({shortKey:s.string(),fullKey:s.string(),typeKey:s.string(),typeParams:Ce,defaultValue:Ce}),Rd=s.object({fields:s.array(H0),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")]),J0=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()}),Y0=s.object({key:s.string(),sources:s.array(tf)}),il=s.object({type:s.literal("setJinjaVariable"),variable:s.string()}),Q0=s.object({type:s.literal("prependSystemPrompt"),content:s.string()}),X0=s.object({type:s.literal("appendSystemPrompt"),content:s.string()}),sl=s.object({key:s.string(),displayName:s.string(),description:s.string()}),ev=sl.extend({type:s.literal("boolean"),defaultValue:s.boolean(),effects:s.array(s.discriminatedUnion("type",[il,Q0,X0]))}),tv=sl.extend({type:s.literal("string"),defaultValue:s.string(),effects:s.array(s.discriminatedUnion("type",[il]))}),rv=sl.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",[il]))}),nv=s.discriminatedUnion("type",[ev,tv,rv]),iv=s.object({type:s.literal("equals"),key:s.string(),value:Ce}),sv=s.discriminatedUnion("type",[iv]),ov=s.object({message:s.string(),conditions:s.array(sv),fields:s.array(yf).optional()});s.object({model:s.string().regex(/^[^/]+\/[^/]+$/),base:s.union([s.string(),s.array(Y0)]),tags:s.array(s.string().max(100)).optional(),config:s.object({load:X.optional(),operation:X.optional()}).optional(),metadataOverrides:J0.optional(),customFields:s.array(nv).optional(),suggestions:s.array(ov).optional()});var av=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 lv(r){return r?.isSimpleLogger===!0}var cv=I.default.greenBright("I"),uv=I.default.yellowBright("W"),dv=I.default.redBright("E"),fv=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=[],lv(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?cv:i,o=o===void 0?uv:o,a=a===void 0?dv:a,l=l===void 0?fv: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})}},Id,Od=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(Od),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[Id]="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*[(Id=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===Od)break;yield n,e++}await this.promiseFinal,await Promise.resolve()}},Ye=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,t,n,i,o){let a=n.safeParse(i);if(a.success)return a.data;throw me(`${e}
|
|
58
58
|
|
|
59
|
-
${r.prettyPrintZod(t,a.error)}`,this.attachStack?o:void 0)}validateMultipleOrThrow(e,t,n,i,o){let a=n.map((c,u)=>c.safeParse(i[u])),l=a.map((c,u)=>({result:c,index:u,rootObjectName:t[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
|
|
59
|
+
${r.prettyPrintZod(t,a.error)}`,this.attachStack?o:void 0)}validateMultipleOrThrow(e,t,n,i,o){let a=n.map((c,u)=>c.safeParse(i[u])),l=a.map((c,u)=>({result:c,index:u,rootObjectName:t[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 me(`${u}
|
|
60
60
|
|
|
61
61
|
${l.map(({error:h,rootObjectName:f})=>r.prettyPrintZod(f,h)).join(`
|
|
62
62
|
`)}`,this.attachStack?o:void 0)}}validateMethodParamOrThrow(e,t,n,i,o,a){let l=I.default.yellowBright(j`
|
|
@@ -67,24 +67,24 @@ ${l.map(({error:h,rootObjectName:f})=>r.prettyPrintZod(f,h)).join(`
|
|
|
67
67
|
${e}(${I.default.redBright(t)})
|
|
68
68
|
`);return this.validateOrThrow(`Invalid parameter(s) when constructing ${a}`,t,n,i,o)}validateConstructorParamsOrThrow(e,t,n,i,o){return this.validateMultipleOrThrow(a=>{let l=t.map((u,h)=>a.has(h)?I.default.redBright(u):u);return`Invalid parameter(s) when constructing ${I.default.yellowBright(j`
|
|
69
69
|
${e}(${l.join(", ")})
|
|
70
|
-
`)}:`},t,n,i,o)}},
|
|
70
|
+
`)}:`},t,n,i,o)}},Kf=new Ye,pe=class{constructor(e,t,n,i,o){this.filesNamespace=e,this.identifier=t,this.type=n,this.sizeBytes=i,this.name=o,this.parsedIdentifier=Db(t)}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"}},ol=s.object({role:s.enum(["user","assistant","system"]).optional(),content:s.string().optional(),images:s.array(s.instanceof(pe)).optional()}),hv=s.array(ol);function pv(r){return!Array.isArray(r.content)}function mv(r){return!("messages"in r)}function Zo(r){let{role:e,content:t,images:n}=r,i=[];if(n===void 0||n.length===0)t===void 0&&i.push({type:"text",text:""});else for(let o of n)i.push({type:"file",identifier:o.identifier,name:o.name,fileType:o.type,sizeBytes:o.sizeBytes});return t!==void 0&&i.push({type:"text",text:t}),{role:e??"user",content:i}}var mt=class r extends Zi{getClassName(){return"Chat"}create(e,t){return new r(e,t)}cloneData(e){return dr.parse(e)}constructor(e,t){super(e,t)}static empty(){return new r({messages:[]},!0)}static from(e){let t=A(1);if(Kf.validateMethodParamOrThrow("Chat","from","initializer",Zr,e,t),e instanceof r)return e.asMutableCopy();if(typeof e=="string"){let n=r.empty();return n.append("user",e),n}return Array.isArray(e)?new r({messages:e.map(Zo)},!0):mv(e)?new r({messages:[Zo(e)]},!0):new r(e,!1).asMutableCopy()}static createRaw(e,t){return new r(e,t)}getRaw(){return this.data}append(...e){if(this.guardMutable(),e.length===1){let[t]=e,n=ce.from(t),i=n._internalToMutable();this.data.messages.push(i._internalGetData())}else{let[t,n,i={}]=e;if(t==="user"||t==="system"||t==="assistant"){let o=[{type:"text",text:n}];if(i.images!==void 0)for(let a of i.images)o.push({type:"file",name:a.name,identifier:a.identifier,sizeBytes:a.sizeBytes,fileType:a.type});this.data.messages.push({role:t,content:o})}else throw new Error(j`
|
|
71
71
|
Unsupported role for append() API with [role, content] parameters: ${t}.
|
|
72
72
|
Supported roles are 'user', 'system', and 'assistant'.
|
|
73
|
-
`)}}withAppended(...e){let t=this.asMutableCopy();return t.append(...e),t}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
|
|
73
|
+
`)}}withAppended(...e){let t=this.asMutableCopy();return t.append(...e),t}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 ce.createRaw(e,!0)}getAllFiles(e){return this.data.messages.flatMap(t=>t.content.filter(n=>n.type==="file")).map(t=>new pe(e.files,t.identifier,t.fileType,t.sizeBytes,t.name))}*files(e){for(let t of this.data.messages)for(let n of t.content)n.type==="file"&&(yield new pe(e.files,n.identifier,n.fileType,n.sizeBytes,n.name))}hasFiles(){return this.data.messages.some(e=>e.content.some(t=>t.type==="file"))}at(e){let t=e;if(e<0&&(t=this.data.messages.length+e),t<0||t>=this.data.messages.length)throw new Error(j`
|
|
74
74
|
Tried to access the message at index ${e}, but the history only has
|
|
75
75
|
${this.data.messages.length} messages.
|
|
76
|
-
`);return
|
|
76
|
+
`);return ce.createRaw(this.data.messages[t],this.mutable)}getMessagesArray(){return this.data.messages.map(e=>ce.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 ce.createRaw(e,this.mutable)}consumeFiles(e,t){this.guardMutable();let n=[];for(let i of this.data.messages)n.push(...ce.createRaw(i,!0).consumeFiles(e,t));return n}async consumeFilesAsync(e,t){this.guardMutable();let n=[];for(let i of this.data.messages)n.push(...await ce.createRaw(i,!0).consumeFilesAsync(e,t));return n}getSystemPrompt(){return this.data.messages.filter(e=>e.role==="system").map(e=>e.content.filter(t=>t.type==="text").map(t=>t.text).join(" ")).join(`
|
|
77
77
|
|
|
78
|
-
`)}replaceSystemPrompt(e){this.guardMutable(),this.data.messages=this.data.messages.filter(t=>t.role!=="system"),this.data.messages.unshift({role:"system",content:[{type:"text",text:e}]})}filterInPlace(e){this.guardMutable(),this.data.messages=this.data.messages.filter(t=>e(
|
|
79
|
-
`+this.data.messages.map(e=>
|
|
78
|
+
`)}replaceSystemPrompt(e){this.guardMutable(),this.data.messages=this.data.messages.filter(t=>t.role!=="system"),this.data.messages.unshift({role:"system",content:[{type:"text",text:e}]})}filterInPlace(e){this.guardMutable(),this.data.messages=this.data.messages.filter(t=>e(ce.createRaw(t,!0)))}toString(){return`Chat {
|
|
79
|
+
`+this.data.messages.map(e=>ce.createRaw(e,!1).toString().split(`
|
|
80
80
|
`).map(n=>" "+n).join(`
|
|
81
81
|
`)).join(`
|
|
82
82
|
`)+`
|
|
83
|
-
}`}},Zr=s.union([s.instanceof(
|
|
83
|
+
}`}},Zr=s.union([s.instanceof(mt),dr,s.string(),hv,ol]),ce=class r extends Zi{getClassName(){return"ChatMessage"}create(e,t){return new r(e,t)}cloneData(e){return ur.parse(e)}constructor(e,t){super(e,t)}static create(e,t){return new r(ur.parse({role:e,content:[{type:"text",text:t}]}),!0)}static from(e){let t=A(1);return Kf.validateMethodParamOrThrow("ChatMessage","from","initializer",gv,e,t),e instanceof r?e.asMutableCopy():typeof e=="string"?new r(ur.parse({role:"user",content:[{type:"text",text:e}]}),!0):pv(e)?new r(Zo(e),!0):new r(e,!0)}static createRaw(e,t){return new r(e,t)}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(t=>new pe(e.files,t.identifier,t.fileType,t.sizeBytes,t.name))}*files(e){for(let t of this.getFileParts())yield new pe(e.files,t.identifier,t.fileType,t.sizeBytes,t.name)}consumeFiles(e,t){this.guardMutable();let n=[],i=new Set;for(let[o,a]of this.data.content.entries()){if(a.type!=="file")continue;let l=new pe(e.files,a.identifier,a.fileType,a.sizeBytes,a.name);t(l)&&(n.push(l),i.add(o))}return this.data.content=this.data.content.filter((o,a)=>!i.has(a)),n}async consumeFilesAsync(e,t){this.guardMutable();let n=[],i=new Set;for(let[o,a]of this.data.content.entries()){if(a.type!=="file")continue;let l=new pe(e.files,a.identifier,a.fileType,a.sizeBytes,a.name);await t(l)&&(n.push(l),i.add(o))}return this.data.content=this.data.content.filter((o,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 t=this.data;throw new Error(`Unhandled role in switch statement: ${t.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 t=this.data;throw new Error(`Unhandled role in switch statement: ${t.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(t=>t.type!=="text")];break;case"tool":throw new Error(`Cannot replace text in a message with role "${this.data.role}"`);default:{let t=this.data;throw new Error(`Unhandled role in switch statement: ${t.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(t=>{switch(t.type){case"text":return t.text;case"file":return`<file ${t.name}>`;case"toolCallRequest":return t.toolCallRequest.name+`(${JSON.stringify(t.toolCallRequest.arguments)})`;case"toolCallResult":return t.content;default:{let n=t;throw new Error(`Unknown part type: ${n.type}`)}}}).join(" ");return e.includes(`
|
|
84
84
|
`)?this.data.role+`:
|
|
85
85
|
`+e.split(`
|
|
86
86
|
`).map(t=>" "+t).join(`
|
|
87
|
-
`):this.data.role+": "+e}},
|
|
87
|
+
`):this.data.role+": "+e}},gv=s.union([s.instanceof(ce),ol,s.string(),ur]),Go=class{constructor(e){this.baseSchema=e,this.valueTypes=new Map}valueType(e,t){if(this.valueTypes.has(e))throw new Error(`ValueType with key ${e} already exists`);return this.valueTypes.set(e,{paramType:s.object({...this.baseSchema,...t.paramType}),schemaMaker:t.schemaMaker,effectiveEquals:t.effectiveEquals,stringify:t.stringify}),this}build(){return new Ko(new Map(this.valueTypes))}},Ko=class{constructor(e){this.valueTypes=e}getSchema(e,t){let n=this.valueTypes.get(e);if(n===void 0)throw new Error(`Cannot find value type ${e}`);return n.schemaMaker(n.paramType.parse(t))}parseParamTypes(e,t){return this.valueTypes.get(e).paramType.parse(t)}effectiveEquals(e,t,n,i){return this.valueTypes.get(e).effectiveEquals(n,i,t)}stringify(e,t,n,i){return this.valueTypes.get(e).stringify(i,t,n)}},Ji=class r{constructor(e){this.valueTypeLibrary=e,this.fields=new Map,this.extensionPrefixes=[]}field(e,t,n,i){let a=this.valueTypeLibrary.getSchema(t,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:t,valueTypeParams:n,schema:this.valueTypeLibrary.getSchema(t,n),fullKey:e,defaultValue:i}),this}extension(e){return this.extensionPrefixes.push(`${e}.`),this}scope(e,t){let n=t(new r(this.valueTypeLibrary));for(let[i,{valueTypeKey:o,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:o,valueTypeParams:a,schema:l,fullKey:u,defaultValue:c})}return this.extensionPrefixes.push(...n.extensionPrefixes.map(i=>`${e}.${i}`)),this}build(){return new In(this.valueTypeLibrary,this.fields,this.extensionPrefixes)}},Yi=Symbol("createParsedKVConfig"),In=class r{constructor(e,t,n){this.valueTypeLibrary=e,this.fields=t,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 t=this.fields.get(e);if(t===void 0){let n=[...this.fields.keys()],i=n.slice(0,10).map(o=>`- ${o}`).join(`
|
|
88
88
|
`);throw n.length>10&&(i+=`
|
|
89
89
|
... and ${n.length-10} more`),new Error(`Cannot access key ${e}. Key does not exist in the schematics. Available keys:
|
|
90
90
|
|
|
@@ -92,25 +92,25 @@ ${l.map(({error:h,rootObjectName:f})=>r.prettyPrintZod(f,h)).join(`
|
|
|
92
92
|
`);throw n.length>10&&(i+=`
|
|
93
93
|
... and ${n.length-10} more`),new Error(`Cannot access full key ${e}. Full key does not exist in the schematics. Availablekeys:
|
|
94
94
|
|
|
95
|
-
`+i)}return t}getSchemaForKey(e){return this.obtainField(e).schema}parseField(e,t){if(t===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(t);if(!n.success)throw new Error(`Field with key ${e.fullKey} does not satisfy the schema:`+n.error.message);return n.data}parseFieldWithoutDefault(e,t){if(t===void 0)return;let n=e.schema.safeParse(t);if(!n.success)throw new Error(`Field with key ${e.fullKey} does not satisfy the schema:`+n.error.message);return n.data}access(e,t){let n=this.obtainField(t);return this.parseField(n,e.fields.find(i=>i.key===n.fullKey)?.value)}accessByFullKey(e,t){let n=this.obtainFieldByFullKey(t);return this.parseField(n,e.fields.find(i=>i.key===n.fullKey)?.value)}accessPartial(e,t){let n=this.obtainField(t);return this.parseFieldWithoutDefault(n,e.fields.find(i=>i.key===n.fullKey)?.value)}sliced(...e){let t=e.map(i=>i.endsWith("*")?{type:"prefix",value:i.substring(0,i.length-1)}:{type:"exact",value:i}),n=new Map;for(let[i,o]of this.fields.entries())for(let a of t)(a.type==="exact"&&i===a.value||a.type==="prefix"&&i.startsWith(a.value))&&n.set(i,o);return new r(this.valueTypeLibrary,n,this.extensionPrefixes)}scoped(e){let t=new Map;for(let[n,i]of this.fields.entries())n.startsWith(`${e}.`)&&t.set(n.substring(e.length+1),i);return new r(this.valueTypeLibrary,t,this.extensionPrefixes)}union(e){let t=new Map;for(let[n,i]of this.fields.entries())t.set(n,i);for(let[n,i]of e.fields.entries()){if(t.has(n))throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: "+n);t.set(n,i)}return new r(this.valueTypeLibrary,t,[...this.extensionPrefixes,...e.extensionPrefixes])}flattenBaseKey(){let e=new Map;for(let t of this.fields.values())e.set(t.fullKey,t);return new r(this.valueTypeLibrary,e,this.extensionPrefixes)}parseToMap(e){let t=
|
|
96
|
-
`),e)}var
|
|
95
|
+
`+i)}return t}getSchemaForKey(e){return this.obtainField(e).schema}parseField(e,t){if(t===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(t);if(!n.success)throw new Error(`Field with key ${e.fullKey} does not satisfy the schema:`+n.error.message);return n.data}parseFieldWithoutDefault(e,t){if(t===void 0)return;let n=e.schema.safeParse(t);if(!n.success)throw new Error(`Field with key ${e.fullKey} does not satisfy the schema:`+n.error.message);return n.data}access(e,t){let n=this.obtainField(t);return this.parseField(n,e.fields.find(i=>i.key===n.fullKey)?.value)}accessByFullKey(e,t){let n=this.obtainFieldByFullKey(t);return this.parseField(n,e.fields.find(i=>i.key===n.fullKey)?.value)}accessPartial(e,t){let n=this.obtainField(t);return this.parseFieldWithoutDefault(n,e.fields.find(i=>i.key===n.fullKey)?.value)}sliced(...e){let t=e.map(i=>i.endsWith("*")?{type:"prefix",value:i.substring(0,i.length-1)}:{type:"exact",value:i}),n=new Map;for(let[i,o]of this.fields.entries())for(let a of t)(a.type==="exact"&&i===a.value||a.type==="prefix"&&i.startsWith(a.value))&&n.set(i,o);return new r(this.valueTypeLibrary,n,this.extensionPrefixes)}scoped(e){let t=new Map;for(let[n,i]of this.fields.entries())n.startsWith(`${e}.`)&&t.set(n.substring(e.length+1),i);return new r(this.valueTypeLibrary,t,this.extensionPrefixes)}union(e){let t=new Map;for(let[n,i]of this.fields.entries())t.set(n,i);for(let[n,i]of e.fields.entries()){if(t.has(n))throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: "+n);t.set(n,i)}return new r(this.valueTypeLibrary,t,[...this.extensionPrefixes,...e.extensionPrefixes])}flattenBaseKey(){let e=new Map;for(let t of this.fields.values())e.set(t.fullKey,t);return new r(this.valueTypeLibrary,e,this.extensionPrefixes)}parseToMap(e){let t=ut(e),n=new Map;for(let[i,o]of this.fields.entries()){let a=t.get(o.fullKey),l=this.parseField(o,a);n.set(i,l)}return n}parseToMapWithFullKey(e){let t=ut(e),n=new Map;for(let i of this.fields.values()){let o=t.get(i.fullKey),a=this.parseField(i,o);n.set(i.fullKey,a)}return n}parseToMapPartial(e){let t=ut(e),n=new Map;for(let[i,o]of this.fields.entries()){let a=t.get(o.fullKey),l=this.parseFieldWithoutDefault(o,a);l!==void 0&&n.set(i,l)}return n}parse(e){return Jo[Yi](this.parseToMap(e))}parsePartial(e){return Yo[Yi](this.parseToMapPartial(e))}buildFullConfig(e){return{fields:Array.from(this.fields.entries()).map(([t,n])=>{let i=this.parseField(n,e[t]);return{key:n.fullKey,value:i}})}}buildPartialConfig(e){return{fields:Object.entries(e).filter(([t,n])=>n!==void 0).map(([t,n])=>{let i=this.obtainField(t);return{key:i.fullKey,value:this.parseField(i,n)}})}}createBuildPartialConfigInput(){return{}}configBuilder(){return new Ho(this.fields)}clone(){return new r(this.valueTypeLibrary,new Map(this.fields),this.extensionPrefixes)}withTypeParamOverride(e,t){let n=this.obtainField(e),i=this.clone();return i.fields.set(e,{...n,valueTypeParams:t(n.valueTypeParams),schema:this.valueTypeLibrary.getSchema(n.valueTypeKey,t(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 X.transform(t=>{let n=new Set;return{fields:t.fields.filter(i=>{if(this.extensionPrefixes.some(l=>i.key.startsWith(l)))return!0;if(n.has(i.key))return!1;let o=e.get(i.key);return o===void 0||!o.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 t=this.fields.get(e);return t===void 0?null:t.valueTypeKey}getValueTypeParam(e){let t=this.fields.get(e);return t===void 0?null:t.valueTypeParams}getValueTypeParamByFullKey(e){let t=this.getFullKeyMap().get(e);if(t===void 0)throw new Error(`Field with key ${e} does not exist in the schematics`);return t.valueTypeParams}hasFullKey(e){return this.getFullKeyMap().get(e)!==void 0}filterConfig(e,t){let n=this.getFullKeyMap();return{fields:e.fields.filter(i=>{let o=n.get(i.key);return o===void 0?!1:t!==void 0?t(o.fullKey,{type:o.valueTypeKey,param:o.valueTypeParams}):!0})}}filterStack(e){return{layers:e.layers.map(t=>({layerName:t.layerName,config:this.filterConfig(t.config)}))}}twoWayFilterConfig(e,t){let n=[],i=[],o=this.getFullKeyMap();for(let a of e.fields){let l=o.get(a.key),c=l!==void 0;l!==void 0&&t!==void 0&&(c=t(l.fullKey,{type:l.valueTypeKey,param:l.valueTypeParams})),c?n.push(a):i.push(a)}return[{fields:n},{fields:i}]}filterFullKeys(e){let t=this.getFullKeyMap();return e.filter(n=>t.has(n))}configEffectiveEquals(e,t){let n=ut(e),i=ut(t);for(let o of this.fields.values()){let a=n.get(o.fullKey),l=i.get(o.fullKey);if(a===void 0){if(l===void 0)continue;return!1}this.valueTypeLibrary.effectiveEquals(o.valueTypeKey,o.valueTypeParams,a,l)}return!0}fieldEffectiveEquals(e,t,n){let i=this.obtainField(e);return this.valueTypeLibrary.effectiveEquals(i.valueTypeKey,i.valueTypeParams,i.schema.parse(t),i.schema.parse(n))}fieldEffectiveEqualsWithFullKey(e,t,n){let o=this.getFullKeyMap().get(e);if(o===void 0)throw new Error(`Field with key ${e} does not exist in the schematics`);return this.valueTypeLibrary.effectiveEquals(o.valueTypeKey,o.valueTypeParams,o.schema.parse(t),o.schema.parse(n))}makeInternalFieldStringifyOpts(e){return{t:e.t??((t,n)=>n),desiredLength:e.desiredLength}}stringifyField(e,t,n={}){let i=this.obtainField(e);return this.valueTypeLibrary.stringify(i.valueTypeKey,i.valueTypeParams,this.makeInternalFieldStringifyOpts(n),t)}tryStringifyFieldWithFullKey(e,t,n){let o=this.getFullKeyMap().get(e);return o===void 0?null:this.valueTypeLibrary.stringify(o.valueTypeKey,o.valueTypeParams,this.makeInternalFieldStringifyOpts(n),t)}apply(e,t){let n=this.filterConfig(t);return Hf([e,n])}unApply(e,t){let n=this.filterConfig(t),i=ut(n),o=new Map(ut(e)),a=this.getFullKeyMap();for(let[l,c]of i.entries()){let u=a.get(l);if(u===void 0)continue;let h=o.get(l);if(h!==void 0){if(!this.valueTypeLibrary.effectiveEquals(u.valueTypeKey,u.valueTypeParams,c,h))continue;o.delete(l)}}return al(o)}*iterateFieldsOfConfig(e){let t=this.getFullKeyMap();for(let{key:n,value:i}of e.fields)t.get(n)!==void 0&&(yield[n,i])}*fullKeys(){let e=this.getFullKeyMap();for(let t of e.keys())yield t}effectiveCompareConfig(e,t,n={}){let{fieldFilter:i}=n,o=ut(e),a=ut(t),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=o.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,t])=>({shortKey:e,fullKey:t.fullKey,typeKey:t.valueTypeKey,typeParams:t.valueTypeParams,defaultValue:t.defaultValue})),extensionPrefixes:this.extensionPrefixes}}hasFieldsWithPrefix(e){for(let t of this.fields.values())if(t.fullKey.startsWith(e))return!0;return!1}static deserialize(e,t){let n=new Map(t.fields.map(i=>{let o=e.parseParamTypes(i.typeKey,i.typeParams),a=e.getSchema(i.typeKey,o);return[i.shortKey,{valueTypeKey:i.typeKey,valueTypeParams:o,schema:a,fullKey:i.fullKey,defaultValue:a.parse(i.defaultValue)}]}));return new r(e,n,t.extensionPrefixes??[])}static tryDeserialize(e,t){let n=new Map,i=[];for(let o of t.fields)try{let a=e.parseParamTypes(o.typeKey,o.typeParams),l=e.getSchema(o.typeKey,a);n.set(o.shortKey,{valueTypeKey:o.typeKey,valueTypeParams:a,schema:l,fullKey:o.fullKey,defaultValue:l.parse(o.defaultValue)})}catch(a){i.push({fullKey:o.fullKey,error:sr(a)})}return{schematics:new r(e,n,t.extensionPrefixes??[]),errors:i}}},Ho=class{constructor(e){this.fieldDefs=e,this.fields=new Map}with(e,t){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,t),this}build(){return al(this.fields)}},Jo=class r{constructor(e){this.configMap=e}static[Yi](e){return new r(e)}get(e){return this.configMap.get(e)}},Yo=class r{constructor(e){this.configMap=e}static[Yi](e){return new r(e)}get(e){return this.configMap.get(e)}has(e){return this.configMap.has(e)}};function ut(r){return new Map(r.fields.map(e=>[e.key,e.value]))}function al(r){return{fields:Array.from(r.entries()).map(([e,t])=>({key:e,value:t}))}}function Hf(r){let e=new Map;for(let t of r)for(let{key:n,value:i}of t.fields)e.set(n,i);return al(e)}var Jf={fields:[]};function Md(r,e){return{layers:[{layerName:r,config:e}]}}function Ro(r,e,t){return{layers:[...r.layers,{layerName:e,config:t}]}}function Ke(r,e){if(r===e)return!0;if(typeof r!="object"||typeof e!="object"||r===null||e===null||Array.isArray(r)!==Array.isArray(e))return!1;if(Array.isArray(r)){if(r.length!==e?.length)return!1;for(let i=0;i<r.length;i++)if(!Ke(r[i],e[i]))return!1;return!0}let t=new Set(Object.keys(r)),n=new Set(Object.keys(e));if(t.size!==n.size)return!1;for(let i of t)if(!n.has(i)||!Ke(r[i],e[i]))return!1;return!0}function Qo(r,e){return r===void 0||r===""?e??'""':JSON.stringify(r)}function Ur(r,e){return Qo(r?.replace(/\\n/g,`
|
|
96
|
+
`),e)}var Yf=new Go({displayName:s.string().optional(),hint:s.string().optional(),modelCentric:s.boolean().optional(),nonConfigurable:s.boolean().optional(),engineDoesNotSupport:s.boolean().optional(),machineDependent:s.boolean().optional(),warning:s.string().optional(),subtitle:s.string().optional(),isExperimental:s.boolean().optional(),dependencies:s.array(d0).optional()}).valueType("numeric",{paramType:{min:s.number().optional(),max:s.number().optional(),step:s.number().optional(),int:s.boolean().optional(),precision:s.number().int().nonnegative().optional(),slider:s.object({min:s.number(),max:s.number(),step:s.number()}).optional(),shortHand:s.string().optional()},schemaMaker:({min:r,max:e,int:t,precision:n})=>{let i=s.number();if(r!==void 0&&(i=i.min(r)),e!==void 0&&(i=i.max(e)),t){if(n!==void 0)throw new Error("Cannot specify both int and precision.");i=i.int()}return i},effectiveEquals:(r,e)=>r===e,stringify:(r,{int:e,precision:t})=>e?String(Math.round(r)):r.toFixed(t??2)}).valueType("string",{paramType:{minLength:s.number().optional(),maxLength:s.number().optional(),isParagraph:s.boolean().optional(),isProtected:s.boolean().optional(),isToken:s.boolean().optional(),placeholder:s.string().optional()},schemaMaker:({minLength:r,maxLength:e})=>{let t=s.string();return r!==void 0&&(t=t.min(r)),e!==void 0&&(t=t.max(e)),t},effectiveEquals:(r,e)=>r===e,stringify:(r,{isParagraph:e,isProtected:t},{t:n,desiredLength:i})=>{if(t)return"********";if(e)return r===""?n("config:customInputs.string.emptyParagraph","<Empty>"):i===void 0||r.length<=i?r:r.slice(0,Math.floor(i/2))+" ... "+r.slice(-Math.ceil(i/2));{let o=Qo(r);return i===void 0||o.length<=i?o:o.slice(0,Math.floor(i/2))+"..."+o.slice(-Math.ceil(i/2))}}}).valueType("select",{paramType:{options:s.array(s.object({value:s.string().nonempty(),displayName:s.string()}).or(s.string())).refine(r=>{let e=new Set;for(let t of r){let n=typeof t=="string"?t:t.value;if(e.has(n))return!1;e.add(n)}return!0},{message:"Duplicate values in options."})},schemaMaker:({options:r})=>{let e=new Set(r.map(t=>typeof t=="string"?t:t.value));return s.string().refine(t=>e.has(t))},effectiveEquals:(r,e)=>r===e,stringify:r=>r}).valueType("boolean",{paramType:{},schemaMaker:()=>s.boolean(),effectiveEquals:(r,e)=>r===e,stringify:r=>r?"ON":"OFF"}).valueType("stringArray",{paramType:{maxNumItems:s.number().optional(),allowEmptyStrings:s.boolean().optional()},schemaMaker:({maxNumItems:r,allowEmptyStrings:e})=>{let t=s.string();e||(t=t.min(1));let n=s.array(t);return r!==void 0&&(n=n.max(r)),n},effectiveEquals:(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),stringify:(r,e,{t,desiredLength:n})=>{let i=r.map(a=>Qo(a));if(i.length===0)return t("config:customInputs.stringArray.empty","<Empty>");if(i.length<=2||n===void 0)return i.join(", ");let o=i[0].length+i[1].length+6;for(let a=1;a<i.length-1;a++)if(o+=i[a].length+2,o>=n)return i.slice(0,a).join(", ")+", ..."+i[i.length-1];return i.join(", ")}});Yf.build();var Qf=Yf.valueType("checkboxNumeric",{paramType:{min:s.number().optional(),max:s.number().optional(),step:s.number().optional(),int:s.boolean().optional(),uncheckedHint:s.string().optional(),precision:s.number().int().nonnegative().optional(),slider:s.object({min:s.number(),max:s.number(),step:s.number()}).optional()},schemaMaker:({min:r,max:e,int:t,precision:n})=>{let i=s.number();if(r!==void 0&&(i=i.min(r)),e!==void 0&&(i=i.max(e)),t){if(n!==void 0)throw new Error("Cannot specify both int and precision.");i=i.int()}return s.object({checked:s.boolean(),value:i})},effectiveEquals:(r,e)=>r.checked!==e.checked?!1:r.checked?r.value===e.value:!0,stringify:(r,{int:e,precision:t},{t:n})=>r.checked?e?String(Math.round(r.value)):r.value.toFixed(t??2):n("config:customInputs.checkboxNumeric.off","OFF")}).valueType("numericArray",{paramType:{min:s.number().optional(),max:s.number().optional(),int:s.boolean().optional()},schemaMaker:({min:r,max:e,int:t})=>{let n=s.number();return r!==void 0&&(n=n.min(r)),e!==void 0&&(n=n.max(e)),t&&(n=n.int()),s.array(n)},effectiveEquals:(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),stringify:(r,{int:e})=>r.map(t=>String(e?Math.round(t):t)).join(", ")}).valueType("contextOverflowPolicy",{paramType:{},schemaMaker:()=>Ef,effectiveEquals:(r,e)=>r===e,stringify:(r,e,{t})=>{switch(r){case"stopAtLimit":return t("config:customInputs.contextOverflowPolicy.stopAtLimit","Stop At Limit");case"truncateMiddle":return t("config:customInputs.contextOverflowPolicy.truncateMiddle","Truncate Middle");case"rollingWindow":return t("config:customInputs.contextOverflowPolicy.rollingWindow","Rolling Window")}}}).valueType("context",{paramType:{},schemaMaker:()=>s.array(h0),effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("contextLength",{paramType:{max:s.number().optional()},schemaMaker:()=>s.number().int().positive(),effectiveEquals:(r,e)=>r===e,stringify:(r,{max:e})=>e===void 0?String(r):`${r}/${e}`}).valueType("modelIdentifier",{paramType:{domain:s.array(Rn).optional()},schemaMaker:()=>s.string(),effectiveEquals:(r,e)=>r===e,stringify:r=>r}).valueType("llmPromptTemplate",{paramType:{},schemaMaker:()=>_f,effectiveEquals:(r,e)=>{if(r.type!==e.type||r.stopStrings.length!==e.stopStrings.length||!r.stopStrings.every((t,n)=>t===e.stopStrings[n]))return!1;switch(r.type){case"jinja":return r.jinjaPromptTemplate?.template===e.jinjaPromptTemplate?.template;case"manual":return r.manualPromptTemplate?.beforeSystem===e.manualPromptTemplate?.beforeSystem&&r.manualPromptTemplate?.afterSystem===e.manualPromptTemplate?.afterSystem&&r.manualPromptTemplate?.beforeUser===e.manualPromptTemplate?.beforeUser&&r.manualPromptTemplate?.afterUser===e.manualPromptTemplate?.afterUser&&r.manualPromptTemplate?.beforeAssistant===e.manualPromptTemplate?.beforeAssistant&&r.manualPromptTemplate?.afterAssistant===e.manualPromptTemplate?.afterAssistant;default:{let t=r.type;throw new Error("Unknown template type: "+t)}}},stringify:(r,e,{t,desiredLength:n})=>{switch(r.type){case"jinja":{let i=`${t("config:customInputs.llmPromptTemplate.type","Type")}: ${t("config:customInputs.llmPromptTemplate.types.jinja/label","Jinja")}
|
|
97
97
|
${t("config:customInputs.llmPromptTemplate.jinja.template/label","Template")}: `;if(n===void 0)return i+r.jinjaPromptTemplate?.template;let o=i.length,a=Math.min(100,n-o),l=r.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`${t("config:customInputs.llmPromptTemplate.type","Type")}: ${t("config:customInputs.llmPromptTemplate.types.manual/label","Manual")}
|
|
98
98
|
${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeSystem/label","Before System")}: ${Ur(r.manualPromptTemplate?.beforeSystem)}
|
|
99
99
|
${t("config:customInputs.llmPromptTemplate.manual.subfield.afterSystem/label","After System")}: ${Ur(r.manualPromptTemplate?.afterSystem)}
|
|
100
100
|
${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeUser/label","Before User")}: ${Ur(r.manualPromptTemplate?.beforeUser)}
|
|
101
101
|
${t("config:customInputs.llmPromptTemplate.manual.subfield.afterUser/label","After User")}: ${Ur(r.manualPromptTemplate?.afterUser)}
|
|
102
102
|
${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeAssistant/label","Before Assistant")}: ${Ur(r.manualPromptTemplate?.beforeAssistant)}
|
|
103
|
-
${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label","After Assistant")}: ${Ur(r.manualPromptTemplate?.afterAssistant)}`;default:{let i=r.type;throw new Error("Unknown template type: "+i)}}}}).valueType("llmReasoningParsing",{paramType:{},schemaMaker:()=>
|
|
103
|
+
${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label","After Assistant")}: ${Ur(r.manualPromptTemplate?.afterAssistant)}`;default:{let i=r.type;throw new Error("Unknown template type: "+i)}}}}).valueType("llmReasoningParsing",{paramType:{},schemaMaker:()=>xf,effectiveEquals:(r,e)=>r.startString===e.startString&&r.endString===e.endString,stringify:r=>JSON.stringify(r,null,2)}).valueType("llamaStructuredOutput",{paramType:{},schemaMaker:()=>Ya,effectiveEquals:(r,e)=>r.type==="json"&&e.type==="json"?Ke(r,e):r.type==="none"&&e.type==="none",stringify:r=>JSON.stringify(r,null,2)}).valueType("speculativeDecodingDraftModel",{paramType:{},schemaMaker:()=>s.string(),effectiveEquals:(r,e)=>r===e,stringify:(r,e,{t})=>r===""?t("config:customInputs.speculativeDecodingDraftModel.off","OFF"):r}).valueType("toolUse",{paramType:{},schemaMaker:()=>vf,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("toolNaming",{paramType:{},schemaMaker:()=>Cf,effectiveEquals:(r,e)=>r===e,stringify:r=>r}).valueType("llamaAccelerationOffloadRatio",{paramType:{numLayers:s.number().optional()},schemaMaker:()=>lf,effectiveEquals:(r,e)=>(r==="max"?1:r==="off"?0:r)===(e==="max"?1:e==="off"?0:e),stringify:(r,{numLayers:e},{t})=>{if(r==="max"||r===1){let n=t("config:customInputs.llamaAccelerationOffloadRatio.max","MAX");return e!==0?`${n} (${e})`:n}return r==="off"||r===0?t("config:customInputs.llamaAccelerationOffloadRatio.off","OFF"):e!==void 0?String(Math.round(e*r)):(r*100).toFixed(0)+"%"}}).valueType("llamaMirostatSampling",{paramType:{},schemaMaker:()=>v0,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("llamaLogitBias",{paramType:{},schemaMaker:()=>w0,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("llamaCacheQuantizationType",{paramType:{},schemaMaker:()=>s.object({checked:s.boolean(),value:Kb}),effectiveEquals:(r,e)=>r.checked!==e.checked?!1:r.checked?r.value===e.value:!0,stringify:(r,e,{t})=>r.checked?r.value:t("config:customInputs.llamaCacheQuantizationType.off","OFF")}).valueType("mlxKvCacheQuantizationType",{paramType:{},schemaMaker:()=>Yb,effectiveEquals:(r,e)=>r.enabled!==e.enabled?!1:r.enabled?r.bits===e.bits&&r.groupSize===e.groupSize&&r.quantizedStart===e.quantizedStart:!0,stringify:r=>JSON.stringify(r,null,2)}).valueType("retrievalChunkingMethod",{paramType:{},schemaMaker:()=>Gf,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("envVars",{paramType:{},schemaMaker:()=>Eb,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).valueType("gpuSplitConfig",{paramType:{},schemaMaker:()=>l0,effectiveEquals:(r,e)=>Ke(r,e),stringify:r=>JSON.stringify(r,null,2)}).build(),Tt=new Ji(Qf).extension("ext.virtualModel.customField").field("envVars","envVars",{},{}).scope("llm.prediction",r=>r.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
104
|
`,beforeAssistant:"AI: ",afterAssistant:`
|
|
105
105
|
`,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",r=>r.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",t=>t.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",r=>r.field("gpuSplitConfig","gpuSplitConfig",{},
|
|
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
|
|
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",r=>r.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",t=>t.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",r=>r.field("gpuSplitConfig","gpuSplitConfig",{},a0).field("gpuStrictVramCap","boolean",{},!1)).scope("embedding.load",r=>r.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",t=>t.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",r=>r.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(),Hr=Tt.scoped("llm.prediction"),zn=Hr.sliced("temperature","maxPredictedTokens","promptTemplate","systemPrompt","seed","contextPrefill","tools","toolNaming","reasoning.*");zn.union(Hr.sliced("llama.*","contextOverflowPolicy","stopStrings","toolCallStopStrings","structured","topKSampling","repeatPenalty","minPSampling","topPSampling","logProbs","speculativeDecoding.draftModel","speculativeDecoding.minContinueDraftingProbability","speculativeDecoding.minDraftLengthToConsider","speculativeDecoding.maxTokensToDraft","speculativeDecoding.numReuseTokens"));zn.union(Hr.sliced("mlx.*","contextOverflowPolicy","stopStrings","toolCallStopStrings","structured","repeatPenalty","minPSampling","topPSampling","topKSampling","speculativeDecoding.draftModel","speculativeDecoding.numDraftTokensExact"));zn.union(Hr.sliced("transformers.*"));zn.union(Hr.sliced("onnx.*","repeatPenalty","topPSampling","topKSampling"));var Jr=Tt.scoped("llm.load").union(Tt.sliced("envVars")),qn=Jr.sliced("contextLength","seed","envVars"),Xf=Tt.sliced("llama.load.*","load.*"),yv=qn.union(Jr.sliced("llama.*","load.*","offloadKVCacheToGpu")).union(Xf);qn.union(Jr.sliced("mlx.*"));qn.union(Jr.sliced("transformers.*"));qn.union(Jr.sliced("onnx.*"));var bv=Jr.sliced("numExperts","numCpuExpertLayersRatio"),vv=yv.union(bv),eh=Tt.scoped("embedding.load").union(Tt.sliced("load.*")),th=eh.sliced("contextLength","seed"),Dv=Tt.scoped("retrieval"),wv=th.union(eh.sliced("llama.*")).union(Xf);new Ji(Qf).build();function ir(r,e){if(r!==void 0)return r===!1?{checked:!1,value:e}:{checked:!0,value:r}}function Sv(r){let e=Hr.buildPartialConfig({temperature:r.temperature,contextOverflowPolicy:r.contextOverflowPolicy,maxPredictedTokens:ir(r.maxTokens,1),stopStrings:r.stopStrings,toolCallStopStrings:r.toolCallStopStrings,structured:r.structured,tools:r.rawTools,toolNaming:r.toolNaming,topKSampling:r.topKSampling,repeatPenalty:ir(r.repeatPenalty,1.1),minPSampling:ir(r.minPSampling,.05),topPSampling:ir(r.topPSampling,.95),"llama.xtcProbability":ir(r.xtcProbability,0),"llama.xtcThreshold":ir(r.xtcThreshold,0),logProbs:ir(r.logProbs,0),"llama.cpuThreads":r.cpuThreads,promptTemplate:r.promptTemplate,"speculativeDecoding.draftModel":r.draftModel,"speculativeDecoding.numDraftTokensExact":r.speculativeDecodingNumDraftTokensExact,"speculativeDecoding.minDraftLengthToConsider":r.speculativeDecodingMinDraftLengthToConsider,"speculativeDecoding.minContinueDraftingProbability":r.speculativeDecodingMinContinueDraftingProbability,"reasoning.parsing":r.reasoningParsing});return r.raw!==void 0?Hf([r.raw,e]):e}var Ze={},de={},jd;function lr(){if(jd)return de;jd=1;var r=de.ValidationError=function(g,b,y,D,v,S){if(Array.isArray(D)?(this.path=D,this.property=D.reduce(function(x,E){return x+l(E)},"instance")):D!==void 0&&(this.property=D),g&&(this.message=g),y){var _=y.$id||y.id;this.schema=_||y}b!==void 0&&(this.instance=b),this.name=v,this.argument=S,this.stack=this.toString()};r.prototype.toString=function(){return this.property+" "+this.message};var e=de.ValidatorResult=function(g,b,y,D){this.instance=g,this.schema=b,this.options=y,this.path=D.path,this.propertyPath=D.propertyPath,this.errors=[],this.throwError=y&&y.throwError,this.throwFirst=y&&y.throwFirst,this.throwAll=y&&y.throwAll,this.disableFormat=y&&y.disableFormat===!0};e.prototype.addError=function(g){var b;if(typeof g=="string")b=new r(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");b=new r(g.message,this.instance,this.schema,this.path,g.name,g.argument)}if(this.errors.push(b),this.throwFirst)throw new n(this);if(this.throwError)throw b;return b},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 t(m,g){return g+": "+m.toString()+`
|
|
107
|
+
`}e.prototype.toString=function(g){return this.errors.map(t).join("")},Object.defineProperty(e.prototype,"valid",{get:function(){return!this.errors.length}}),de.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=de.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=de.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=de.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"],de.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=de.makeSuffix=function(g){return g=g.toString(),!g.match(/[.\s\[\]]/)&&!g.match(/^[\d]/)?"."+g:g.match(/^\d+$/)?"["+g+"]":"["+JSON.stringify(g)+"]"};de.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}de.deepMerge=f,de.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")}de.encodePath=function(g){return g.map(d).join("")},de.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},de.isSchema=function(g){return typeof g=="object"&&g||typeof g=="boolean"};var p=de.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 de}var Io,Bd;function Cv(){if(Bd)return Io;Bd=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 x=this.validateSchema(f[y],S,p,m.makeChild(S,y));x.instance!==g.instance[y]&&(g.instance[y]=x.instance),g.importErrors(x)}}}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),x=Math.pow(10,_);return Math.round(f*x)%Math.round(y*x)!==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},Io=n,Io}var Oi={},Ld;function Xo(){if(Ld)return Oi;Ld=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 Oo,Nd;function _v(){if(Nd)return Oo;Nd=1;var r=Cv(),e=lr(),t=Xo().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 x in p)if(!r.ignoreProperties[x]&&_.indexOf(x)<0){var E=null,z=this.attributes[x];if(z)E=z.call(this,d,p,m,g);else if(m.allowUnknownAttributes===!1)throw new o("Unsupported attribute: "+x,p);E&&b.importErrors(E)}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)},Oo=c,Oo}var $d;function Ev(){if($d)return Ze;$d=1;var r=Ze.Validator=_v();return Ze.ValidatorResult=lr().ValidatorResult,Ze.ValidatorResultError=lr().ValidatorResultError,Ze.ValidationError=lr().ValidationError,Ze.SchemaError=lr().SchemaError,Ze.SchemaScanResult=Xo().SchemaScanResult,Ze.scan=Xo().scan,Ze.validate=function(e,t,n){var i=new r;return i.validate(e,t,n)},Ze}var xv=Ev(),hs=s.object({name:s.string(),description:s.string()}),ea=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)}},kv=hs.extend({type:s.literal("function"),parametersSchema:yr,checkParameters:s.function(),implementation:s.function()}),Fv=hs.extend({type:s.literal("rawFunction"),parametersSchema:yr,checkParameters:s.function(),implementation:s.function()}),Pv=hs.extend({type:s.literal("unimplementedRawFunction"),parametersJsonSchema:yr,checkParameters:s.function(),implementation:s.function()}),Tv=hs.extend({type:s.literal("remoteTool"),pluginIdentifier:s.string(),parametersJsonSchema:yr,checkParameters:s.function(),implementation:s.function()});s.discriminatedUnion("type",[kv,Fv,Pv,Tv]);function Av(r,e){return e.map(t=>`${[r,...t.path].join(".")} ${t.message}`).join(`
|
|
108
|
+
`)}var ta=class extends Error{constructor(e){super(`Tool "${e}" is not implemented.`)}};function Rv({name:r,description:e,pluginIdentifier:t,parametersJsonSchema:n,implementation:i}){return{name:r,description:e,type:"remoteTool",pluginIdentifier:t,parametersJsonSchema:n,checkParameters:o=>{let l=new xv.Validator().validate(o,n);if(l.errors.length>0)throw new Error(j`
|
|
109
109
|
Failed to parse arguments for tool "${r}":
|
|
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`
|
|
110
|
+
${Av("params",l.errors)}
|
|
111
|
+
`)},implementation:i}}function Iv(r){return{type:"function",function:{name:r.name,description:r.description,parameters:xi(r.parametersSchema)}}}function Ov(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parametersJsonSchema}}}function Mv(r){return{type:"function",function:{name:r.name,description:r.description,parameters:r.parametersJsonSchema}}}function ll(r){let e=r.type;switch(e){case"function":return Iv(r);case"rawFunction":case"unimplementedRawFunction":return Ov(r);case"remoteTool":return Mv(r);default:{let t=e;throw new Error(`Unhandled type: ${t}`)}}}var cr=class extends Error{constructor(e,t){super(e),this.rawContent=t}},At=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()]}},kt;(function(r){r.Connected="CONNECTED",r.Errored="ERRORED",r.Closed="CLOSED"})(kt||(kt={}));var Mi=new H("Channel"),ra=class r{constructor(e){this.innerSend=e,this.nextAckId=0,this.waitingForAck=new Map,this.receivedACK=t=>{if(this.connectionStatus.get()!==kt.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()!==kt.Connected){Mi.warn("Received message while in status",this.connectionStatus.get());return}this.emitOnMessage(t)},this.errored=t=>{if(this.connectionStatus.get()!==kt.Connected){Mi.warn("Received error while in status",this.connectionStatus.get());return}this.rejectAllWaitingForAck(t),this.setConnectionStatus(kt.Errored),this.emitOnError(t)},this.closed=()=>{this.rejectAllWaitingForAck(new Error("Channel closed")),this.setConnectionStatus(kt.Closed),this.emitOnClose()},[this.onMessage,this.emitOnMessage]=pt.create(),[this.onError,this.emitOnError]=pt.create(),[this.onClose,this.emitOnClose]=pt.create(),[this.connectionStatus,this.setConnectionStatus]=Fn.create(kt.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}},jv=(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})(),rh=(function(){function r(e){this.generateIdentifier=e,this.kv=new jv}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})(),Bv=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)}})(),Lv=(function(r){Bv(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})(rh),Nv=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 $v(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 Uv(r,e){var t=$v(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=Nv(t,2),i=n[0],o=n[1];return e(o,i)})}function $i(r,e){return r.indexOf(e)!==-1}function Ud(r,e){for(var t=0;t<r.length;t++){var n=r[t];if(e(n))return n}}var zv=(function(){function r(){this.transfomers={}}return r.prototype.register=function(e){this.transfomers[e.name]=e},r.prototype.findApplicable=function(e){return Uv(this.transfomers,function(t){return t.isApplicable(e)})},r.prototype.findByName=function(e){return this.transfomers[e]},r})(),qv=function(r){return Object.prototype.toString.call(r).slice(8,-1)},nh=function(r){return typeof r>"u"},Vv=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},na=function(r){return On(r)&&Object.keys(r).length===0},Rt=function(r){return Array.isArray(r)},Wv=function(r){return typeof r=="string"},Zv=function(r){return typeof r=="number"&&!isNaN(r)},Gv=function(r){return typeof r=="boolean"},Kv=function(r){return r instanceof RegExp},Mn=function(r){return r instanceof Map},jn=function(r){return r instanceof Set},ih=function(r){return qv(r)==="Symbol"},Hv=function(r){return r instanceof Date&&!isNaN(r.valueOf())},Jv=function(r){return r instanceof Error},zd=function(r){return typeof r=="number"&&isNaN(r)},Yv=function(r){return Gv(r)||Vv(r)||nh(r)||Zv(r)||Wv(r)||ih(r)},Qv=function(r){return typeof r=="bigint"},Xv=function(r){return r===1/0||r===-1/0},eD=function(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)},tD=function(r){return r instanceof URL},sh=function(r){return r.replace(/\./g,"\\.")},Mo=function(r){return r.map(String).map(sh).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},ia=globalThis&&globalThis.__assign||function(){return ia=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},ia.apply(this,arguments)},sa=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},oa=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 Ge(r,e,t,n){return{isApplicable:r,annotation:e,transform:t,untransform:n}}var oh=[Ge(nh,"undefined",function(){return null},function(){}),Ge(Qv,"bigint",function(r){return r.toString()},function(r){return typeof BigInt<"u"?BigInt(r):(console.error("Please add a BigInt polyfill."),r)}),Ge(Hv,"Date",function(r){return r.toISOString()},function(r){return new Date(r)}),Ge(Jv,"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}),Ge(Kv,"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)}),Ge(jn,"set",function(r){return oa([],sa(r.values()))},function(r){return new Set(r)}),Ge(Mn,"map",function(r){return oa([],sa(r.entries()))},function(r){return new Map(r)}),Ge(function(r){return zd(r)||Xv(r)},"number",function(r){return zd(r)?"NaN":r>0?"Infinity":"-Infinity"},Number),Ge(function(r){return r===0&&1/r===-1/0},"number",function(){return"-0"},Number),Ge(tD,"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 ah=ps(function(r,e){if(ih(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}),rD=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce(function(r,e){return r[e.name]=e,r},{}),lh=ps(eD,function(r){return["typed-array",r.constructor.name]},function(r){return oa([],sa(r))},function(r,e){var t=rD[e[1]];if(!t)throw new Error("Trying to deserialize unknown typed array");return new t(r)});function ch(r,e){if(r?.constructor){var t=!!e.classRegistry.getIdentifier(r.constructor);return t}return!1}var uh=ps(ch,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 ia({},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)}),dh=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)}),nD=[uh,ah,dh,lh],qd=function(r,e){var t=Ud(nD,function(i){return i.isApplicable(r,e)});if(t)return{value:t.transform(r,e),type:t.annotation(r,e)};var n=Ud(oh,function(i){return i.isApplicable(r,e)});if(n)return{value:n.transform(r,e),type:n.annotation}},fh={};oh.forEach(function(r){fh[r.annotation]=r});var iD=function(r,e,t){if(Rt(e))switch(e[0]){case"symbol":return ah.untransform(r,e,t);case"class":return uh.untransform(r,e,t);case"custom":return dh.untransform(r,e,t);case"typed-array":return lh.untransform(r,e,t);default:throw new Error("Unknown transformation: "+e)}else{var n=fh[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 hh(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 sD=function(r,e){hh(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},aa=function(r,e,t){if(hh(e),e.length===0)return t(r);for(var n=r,i=0;i<e.length-1;i++){var o=e[i];if(Rt(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(Rt(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},ht=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},Ft=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 la(r,e,t){if(t===void 0&&(t=[]),!!r){if(!Rt(r)){Kr(r,function(a,l){return la(a,e,Ft(Ft([],ht(t)),ht(Dn(l))))});return}var n=ht(r,2),i=n[0],o=n[1];o&&Kr(o,function(a,l){la(a,e,Ft(Ft([],ht(t)),ht(Dn(l))))}),e(i,t)}}function oD(r,e,t){return la(e,function(n,i){r=aa(r,i,function(o){return iD(o,n,t)})}),r}function aD(r,e){function t(a,l){var c=sD(r,Dn(l));a.map(Dn).forEach(function(u){r=aa(r,u,function(){return c})})}if(Rt(e)){var n=ht(e,2),i=n[0],o=n[1];i.forEach(function(a){r=aa(r,Dn(a),function(){return r})}),o&&Kr(o,t)}else Kr(e,t);return r}var lD=function(r,e){return On(r)||Rt(r)||Mn(r)||jn(r)||ch(r,e)};function cD(r,e,t){var n=t.get(r);n?n.push(e):t.set(r,[e])}function uD(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=ht(i),a=o[0],l=o.slice(1);a.length===0?n=l.map(Mo):t[Mo(a)]=l.map(Mo)}}),n?na(t)?[n]:[n,t]:na(t)?void 0:t}var ph=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=Yv(r);if(!c){cD(r,i,e);var u=a.get(r);if(u)return n?{transformedValue:null}:u}if(!lD(r,t)){var h=qd(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=qd(r,t),p=(l=d?.value)!==null&&l!==void 0?l:r,m=Rt(p)?[]:{},g={};Kr(p,function(y,D){var v=ph(y,e,t,n,Ft(Ft([],ht(i)),[D]),Ft(Ft([],ht(o)),[r]),a);m[D]=v.transformedValue,Rt(v.annotations)?g[D]=v.annotations:On(v.annotations)&&Kr(v.annotations,function(S,_){g[sh(D)+"."+_]=S})});var b=na(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 mh(r){return Object.prototype.toString.call(r).slice(8,-1)}function Vd(r){return mh(r)==="Array"}function dD(r){if(mh(r)!=="Object")return!1;let e=Object.getPrototypeOf(r);return!!e&&e.constructor===Object&&e===Object.prototype}function fD(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 ca(r,e={}){if(Vd(r))return r.map(i=>ca(i,e));if(!dD(r))return r;let t=Object.getOwnPropertyNames(r),n=Object.getOwnPropertySymbols(r);return[...t,...n].reduce((i,o)=>{if(Vd(e.props)&&!e.props.includes(o))return i;let a=r[o],l=ca(a,e);return fD(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)},hD=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},pD=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},gh=(function(){function r(e){var t=e===void 0?{}:e,n=t.dedupe,i=n===void 0?!1:n;this.classRegistry=new Lv,this.symbolRegistry=new rh(function(o){var a;return(a=o.description)!==null&&a!==void 0?a:""}),this.customTransformerRegistry=new zv,this.allowedErrorProps=[],this.dedupe=i}return r.prototype.serialize=function(e){var t=new Map,n=ph(e,t,this,this.dedupe),i={json:n.transformedValue};n.annotations&&(i.meta=or(or({},i.meta),{values:n.annotations}));var o=uD(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=ca(t);return n?.values&&(i=oD(i,n.values,this)),n?.referentialEqualities&&(i=aD(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,pD([],hD(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})(),mD=gh.serialize,gD=gh.deserialize;function zr(r,e){switch(r){case"raw":return e;case"superjson":return mD(e)}}function ji(r,e){switch(r){case"raw":return e;case"superjson":return gD(e)}}var He=s.any(),yD=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:He}),s.object({type:s.literal("channelSend"),channelId:s.number().int(),message:He,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:He}),s.object({type:s.literal("signalSubscribe"),creationParameter:He,endpoint:s.string(),subscribeId:s.number().int()}),s.object({type:s.literal("signalUnsubscribe"),subscribeId:s.number().int()}),s.object({type:s.literal("writableSignalSubscribe"),creationParameter:He,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(He),tags:s.array(s.string())})]),bD=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:He,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:He}),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(He),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(He),tags:s.array(s.string())}),s.object({type:s.literal("writableSignalError"),subscribeId:s.number().int(),error:xe})]),ua=class{constructor(){this.disposed=!1}async[Symbol.asyncDispose](){if(this.disposed)throw new Error("Cannot dispose twice");this.disposed=!0}},Qi=class extends ua{parseIncomingMessage(e){return bD.parse(e)}send(e){let t=yD.parse(e);this.sendViaTransport(t)}onHavingOneOrMoreOpenCommunication(){}onHavingNoOpenCommunication(){}},vD=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 da=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`
|
|
112
112
|
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=Se.Connecting,Promise.resolve(this.url).then(e=>{this.resolvedUrl=e,this.ws=new
|
|
113
|
+
`);if(this.abortSignal!==void 0&&this.abortSignal.aborted)throw new Error(this.abortSignal.reason);this.status=Se.Connecting,Promise.resolve(this.url).then(e=>{this.resolvedUrl=e,this.ws=new Qe.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 t=this.abortSignal;if(t!==void 0)if(t.aborted)this.onWsError(t.reason);else{let n=()=>{this.onWsError(t.reason)};t.addEventListener("abort",n,{once:!0}),this.ws.addEventListener("close",()=>{t.removeEventListener("abort",n)})}})}onWsOpen(){this.ws.addEventListener("message",this.onWsMessage.bind(this)),this.status=Se.Connected,this.queuedMessages.forEach(e=>this.sendViaTransport(e)),this.queuedMessages=[],this.updateShouldRef(this.shouldRef)}onWsMessage(e){if(this.status!==Se.Connected){this.logger.warn("Received message while not connected. Message ignored:",e.data);return}let t;try{t=JSON.parse(String(e.data))}catch{this.logger.warn("Received invalid JSON message from server:",e.data);return}let n;try{n=this.parseIncomingMessage(t)}catch{this.logger.warn("Received invalid message from server:",t);return}this.receivedMessage(n)}onWsError(e){if(this.status!==Se.Disconnected){this.logger.warn("WebSocket error:",e),e.code==="ECONNREFUSED"&&this.logger.warnText`
|
|
114
114
|
WebSocket connection refused. This can happen if the server is not running or the client
|
|
115
115
|
is trying to connect to the wrong path. The server path that this client is
|
|
116
116
|
attempting to connect to is:
|
|
@@ -123,7 +123,7 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
123
123
|
2. The API server in LM Studio has started
|
|
124
124
|
|
|
125
125
|
3. The client is attempting to connect to the correct path
|
|
126
|
-
`;try{this.ws?.close()}catch{}this.status=Se.Disconnected,this.errored(e)}}onWsTimeout(){if(this.status!==Se.Disconnected){this.logger.warn("Websocket timed out");try{this.ws?.close()}catch{}this.status=Se.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===Se.Connected?this.ws.send(JSON.stringify(e)):(this.queuedMessages.push(e),this.status===Se.Disconnected&&this.connect())}async[Symbol.asyncDispose](){if(await super[Symbol.asyncDispose](),this.shouldRef){let{promise:e,resolve:t}=ee();this.resolveDisposed=t,await e}if(this.ws!==null){try{this.ws.close()}catch{}this.ws=null}this.errored(new Error("WebSocket client transport disposed")),this.status=Se.Disconnected}},
|
|
126
|
+
`;try{this.ws?.close()}catch{}this.status=Se.Disconnected,this.errored(e)}}onWsTimeout(){if(this.status!==Se.Disconnected){this.logger.warn("Websocket timed out");try{this.ws?.close()}catch{}this.status=Se.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===Se.Connected?this.ws.send(JSON.stringify(e)):(this.queuedMessages.push(e),this.status===Se.Disconnected&&this.connect())}async[Symbol.asyncDispose](){if(await super[Symbol.asyncDispose](),this.shouldRef){let{promise:e,resolve:t}=ee();this.resolveDisposed=t,await e}if(this.ws!==null){try{this.ws.close()}catch{}this.ws=null}this.errored(new Error("WebSocket client transport disposed")),this.status=Se.Disconnected}},fa=class r extends da{constructor(e,t,n,i,o,{parentLogger:a,abortSignal:l}={}){super(e,i,o,{parentLogger:a,abortSignal:l}),this.clientIdentifier=t,this.clientPasskey=n,this.logger=this.logger.subclass("AuthenticatedWsClientTransport")}static createAuthenticatedWsClientTransportFactory({url:e,clientIdentifier:t,clientPasskey:n,abortSignal:i}){return(o,a,l)=>new r(e,t,n,o,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 t=JSON.parse(e.data.toString("utf-8")),n=vD.parse(t);n.success?super.onWsOpen():this.onWsError(new Error("Failed to authenticate: "+n.error))}catch(t){this.onWsError(new Error("Failed to parse authentication result: "+t?.message))}},{once:!0})}};function DD(r,e,t){return Gi(r,e,t)}var Xi=class{constructor(e,t,{parentLogger:n,errorDeserializer:i,verboseErrorMessage:o}={}){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 H("ClientPort",n),this.errorDeserializer=i??DD,this.verboseErrorMessage=o??!0,this.transport=t(this.receivedMessage,this.errored,this.logger)}communicationWarning(e){this.producedCommunicationWarningsCount>=5||(this.logger.warnText`
|
|
127
127
|
Produced communication warning: ${e}
|
|
128
128
|
|
|
129
129
|
This is usually caused by communication protocol incompatibility. Please make sure you are
|
|
@@ -134,13 +134,13 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
134
134
|
Received invalid message for channel: endpointName = ${t.endpoint.name}, message =
|
|
135
135
|
${n}. Zod error:
|
|
136
136
|
|
|
137
|
-
${
|
|
137
|
+
${Ye.prettyPrintZod("message",i.error)}
|
|
138
138
|
`);return}t.receivedMessage(i.data)}receivedChannelAck(e){let t=this.openChannels.get(e.channelId);if(t===void 0){this.communicationWarning(`Received channelAck for unknown channel, channelId = ${e.channelId}`);return}t.receivedAck(e.ackId)}receivedChannelClose(e){let t=this.openChannels.get(e.channelId);if(t===void 0){this.communicationWarning(`Received channelClose for unknown channel, channelId = ${e.channelId}`);return}this.openChannels.delete(e.channelId),t.closed(),this.updateOpenCommunicationsCount()}receivedChannelError(e){let t=this.openChannels.get(e.channelId);if(t===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?t.stack:void 0);t.errored(n),this.updateOpenCommunicationsCount()}receivedRpcResult(e){let t=this.ongoingRpcs.get(e.callId);if(t===void 0){this.communicationWarning(`Received rpcResult for unknown rpc, callId = ${e.callId}`);return}let n=ji(t.endpoint.serialization,e.result),i=t.endpoint.returns.safeParse(n);if(!i.success){this.communicationWarning(j`
|
|
139
139
|
Received invalid result for rpc, endpointName = ${t.endpoint.name}, result =
|
|
140
140
|
${n}. Zod error:
|
|
141
141
|
|
|
142
|
-
${
|
|
143
|
-
`);return}t.resolve(i.data),this.ongoingRpcs.delete(e.callId),this.updateOpenCommunicationsCount()}receivedRpcError(e){let t=this.ongoingRpcs.get(e.callId);if(t===void 0){this.communicationWarning(`Received rpcError for unknown rpc, callId = ${e.callId}`);return}let n=this.errorDeserializer(e.error,"RPC Error",this.verboseErrorMessage?t.stack:void 0);t.reject(n),this.ongoingRpcs.delete(e.callId),this.updateOpenCommunicationsCount()}receivedSignalUpdate(e){let t=this.openSignalSubscriptions.get(e.subscribeId);if(t===void 0)return;let n=e.patches.map(l=>ji(t.endpoint.serialization,l)),i=t.getValue(),o;try{o
|
|
142
|
+
${Ye.prettyPrintZod("result",i.error)}
|
|
143
|
+
`);return}t.resolve(i.data),this.ongoingRpcs.delete(e.callId),this.updateOpenCommunicationsCount()}receivedRpcError(e){let t=this.ongoingRpcs.get(e.callId);if(t===void 0){this.communicationWarning(`Received rpcError for unknown rpc, callId = ${e.callId}`);return}let n=this.errorDeserializer(e.error,"RPC Error",this.verboseErrorMessage?t.stack:void 0);t.reject(n),this.ongoingRpcs.delete(e.callId),this.updateOpenCommunicationsCount()}receivedSignalUpdate(e){let t=this.openSignalSubscriptions.get(e.subscribeId);if(t===void 0)return;let n=e.patches.map(l=>ji(t.endpoint.serialization,l)),i=t.getValue(),o;try{o=$o(i,n)}catch(l){this.communicationWarning(j`
|
|
144
144
|
Failed to apply patches to signal on signalUpdate. subscribeId = ${e.subscribeId}.
|
|
145
145
|
|
|
146
146
|
beforeValue = ${JSON.stringify(i,null,2)},
|
|
@@ -159,8 +159,8 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
159
159
|
|
|
160
160
|
Zod error:
|
|
161
161
|
|
|
162
|
-
${
|
|
163
|
-
`);return}t.receivedPatches(o,n,e.tags)}receivedSignalError(e){let t=this.openSignalSubscriptions.get(e.subscribeId);if(t===void 0){this.communicationWarning(`Received signalError for unknown signal, subscribeId = ${e.subscribeId}`);return}let n=this.errorDeserializer(e.error,"Signal Error",this.verboseErrorMessage?t.stack:void 0);t.errored(n),this.openSignalSubscriptions.delete(e.subscribeId),this.updateOpenCommunicationsCount()}receivedWritableSignalUpdate(e){let t=this.openWritableSignalSubscriptions.get(e.subscribeId);if(t===void 0)return;let n=e.patches.map(l=>ji(t.endpoint.serialization,l)),i=t.getValue(),o;try{o
|
|
162
|
+
${Ye.prettyPrintZod("value",a.error)}
|
|
163
|
+
`);return}t.receivedPatches(o,n,e.tags)}receivedSignalError(e){let t=this.openSignalSubscriptions.get(e.subscribeId);if(t===void 0){this.communicationWarning(`Received signalError for unknown signal, subscribeId = ${e.subscribeId}`);return}let n=this.errorDeserializer(e.error,"Signal Error",this.verboseErrorMessage?t.stack:void 0);t.errored(n),this.openSignalSubscriptions.delete(e.subscribeId),this.updateOpenCommunicationsCount()}receivedWritableSignalUpdate(e){let t=this.openWritableSignalSubscriptions.get(e.subscribeId);if(t===void 0)return;let n=e.patches.map(l=>ji(t.endpoint.serialization,l)),i=t.getValue(),o;try{o=$o(t.getValue(),n)}catch(l){this.communicationWarning(j`
|
|
164
164
|
Failed to apply patches to writable signal on writableSignalUpdate. subscribeId =
|
|
165
165
|
${e.subscribeId}.
|
|
166
166
|
|
|
@@ -180,7 +180,7 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
180
180
|
|
|
181
181
|
Zod error:
|
|
182
182
|
|
|
183
|
-
${
|
|
183
|
+
${Ye.prettyPrintZod("value",a.error)}
|
|
184
184
|
`);return}t.firstUpdateReceived=!0,t.receivedPatches(o,n,e.tags)}receivedWritableSignalError(e){let t=this.openWritableSignalSubscriptions.get(e.subscribeId);if(t===void 0){this.communicationWarning(`Received writableSignalError for unknown signal, subscribeId = ${e.subscribeId}`);return}let n=this.errorDeserializer(e.error,"Writable Signal Error",this.verboseErrorMessage?t.stack:void 0);t.errored(n),this.openWritableSignalSubscriptions.delete(e.subscribeId),this.updateOpenCommunicationsCount()}receivedCommunicationWarning(e){this.logger.warnText`
|
|
185
185
|
Received communication warning from the server: ${e.warning}
|
|
186
186
|
|
|
@@ -188,10 +188,10 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
188
188
|
using the up-to-date versions of the SDK and LM Studio.
|
|
189
189
|
|
|
190
190
|
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`
|
|
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,...ra.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=$e.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]=zo.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]()}},ha=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 yh(){let r;try{r=window}catch{r=void 0}return r!==void 0&&r.lmsHostedEnv!==void 0?r.lmsHostedEnv:null}function bh(r,e){let t=r,n=e;return new At().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:Je,throwIfNotFound:s.boolean()}),returns:t.optional()}).addRpcEndpoint("getLoadConfig",{parameter:s.object({specifier:Je}),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:L0}),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 wD(){return new At().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:Zb})])})}function SD(){return bh(hf,ff).addRpcEndpoint("embedString",{parameter:s.object({modelSpecifier:Je,inputString:s.string()}),returns:s.object({embedding:s.array(s.number())})}).addRpcEndpoint("tokenize",{parameter:s.object({specifier:Je,inputString:s.string()}),returns:s.object({tokens:s.array(s.number())})}).addRpcEndpoint("countTokens",{parameter:s.object({specifier:Je,inputString:s.string()}),returns:s.object({tokenCount:s.number().int()})})}function CD(){return new At().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:sf,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:Ao}),s.object({type:s.literal("onFileProcessingStepProgress"),index:s.number().int(),step:Ao,progress:s.number()}),s.object({type:s.literal("onFileProcessingStepEnd"),index:s.number().int(),step:Ao}),s.object({type:s.literal("onSearchingStart")}),s.object({type:s.literal("onSearchingEnd")}),s.object({type:s.literal("result"),result:Z0})])}).addChannelEndpoint("parseDocument",{creationParameter:s.object({fileIdentifier:s.string(),parseOpts:mf}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("parserLoaded"),parser:Vo}),s.object({type:s.literal("progress"),progress:s.number()}),s.object({type:s.literal("result"),content:s.string(),parser:Vo})]),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 _D(){return bh(Wo,Sf).addChannelEndpoint("predict",{creationParameter:s.object({modelSpecifier:Je,history:dr,predictionConfigStack:Ki,fuzzyPresetIdentifier:s.string().optional(),ignoreServerSessionConfig:s.boolean().optional()}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("fragment"),fragment:Ff,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:Tf,modelInfo:Wo,loadModelConfig:X,predictionConfig:X})]),toServerPacket:s.discriminatedUnion("type",[s.object({type:s.literal("cancel")})])}).addRpcEndpoint("applyPromptTemplate",{parameter:s.object({specifier:Je,history:dr,predictionConfigStack:Ki,opts:Df}),returns:s.object({formatted:s.string()})}).addRpcEndpoint("tokenize",{parameter:s.object({specifier:Je,inputString:s.string()}),returns:s.object({tokens:s.array(s.number())})}).addRpcEndpoint("countTokens",{parameter:s.object({specifier:Je,inputString:s.string()}),returns:s.object({tokenCount:s.number().int()})}).addRpcEndpoint("preloadDraftModel",{parameter:s.object({specifier:Je,draftModelKey:s.string()}),returns:s.void()})}function ED(){return new At().addChannelEndpoint("startToolUseSession",{creationParameter:s.object({pluginIdentifier:s.string(),pluginConfigSpecifier:kd}),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:kd,tools:s.array(ar),history:dr}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("fragment"),fragment:Ff}),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:Ka}),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(Fd),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(Fd),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:Pf}),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:P0}),returns:s.void()}).addRpcEndpoint("processingHandleRequest",{parameter:s.object({pci:s.string(),token:s.string(),request:R0}),returns:s.object({response:M0})}).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:j0})}).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:Rd}),returns:s.void()}).addRpcEndpoint("setGlobalConfigSchematics",{parameter:s.object({schematics:Rd}),returns:s.void()}).addRpcEndpoint("pluginInitCompleted",{parameter:s.void(),returns:s.void()})}function xD(){return new At().addRpcEndpoint("searchModels",{parameter:s.object({opts:Zf}),returns:s.object({results:s.array(V0)})}).addRpcEndpoint("getModelDownloadOptions",{parameter:s.object({modelSearchResultIdentifier:Wf}),returns:s.object({results:s.array(q0)})}).addChannelEndpoint("downloadModel",{creationParameter:s.object({downloadIdentifier:s.string()}),toClientPacket:s.discriminatedUnion("type",[s.object({type:s.literal("downloadProgress"),update:To}),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:To}),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:U0})}).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:Ad}),s.object({type:s.literal("planReady"),plan:Ad}),s.object({type:s.literal("downloadProgress"),update:To}),s.object({type:s.literal("startFinalizing")}),s.object({type:s.literal("success")})])})}function kD(){return new At().addRpcEndpoint("listDownloadedModels",{parameter:s.void(),returns:s.array(B0)}).addChannelEndpoint("alive",{creationParameter:s.void(),toServerPacket:s.void(),toClientPacket:s.void()}).addRpcEndpoint("notify",{parameter:nf,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 FD(r,e,t,n){let[i,o]=pt.create(),[a,l]=pt.create(),c=e.getApiIpcTunnel(r,{authVersion:1,clientIdentifier:t,clientPasskey:n},o,l);return ha.createFactory(i,a,c)}function PD(r,e,t,n){return fa.createAuthenticatedWsClientTransportFactory({url:Promise.resolve(e).then(i=>`${i}/${r}`),clientIdentifier:t,clientPasskey:n})}function TD(r,e,t,n,i,o,{errorDeserializer:a,verboseErrorMessage:l}={}){let c=yh();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,FD(t,c,n,i),{parentLogger:o,errorDeserializer:a,verboseErrorMessage:l})):new Xi(r,PD(t,e,n,i),{parentLogger:o,errorDeserializer:a,verboseErrorMessage:l})}var pa=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 AD(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(),av]).optional(),onProgress:s.function().optional()})}var es=class{getLoadModelOptsSchema(){return this.loadModelOptsSchema===null&&(this.loadModelOptsSchema=AD(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`
|
|
192
192
|
Verbose logging is enabled. To hide progress logs, set the "verbose" option to false in
|
|
193
193
|
client.llm.load.
|
|
194
|
-
`);let g=e,b=this.port.createChannel("loadModel",{modelKey:e,identifier:i,ttlMs:t.ttl===void 0?void 0:t.ttl*1e3,loadConfigStack:
|
|
194
|
+
`);let g=e,b=this.port.createChannel("loadModel",{modelKey:e,identifier:i,ttlMs:t.ttl===void 0?void 0:t.ttl*1e3,loadConfigStack:Md("apiOverride",this.loadConfigToKVConfig(l??this.defaultLoadConfig))},y=>{switch(y.type){case"resolved":{g=y.info.modelKey,y.ambiguous!==void 0&&this.logger.warn(j`
|
|
195
195
|
Multiple models found for key ${e}:
|
|
196
196
|
|
|
197
197
|
${y.ambiguous.map(D=>` - ${D}`).join(`
|
|
@@ -202,10 +202,10 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
202
202
|
Start loading model ${g}...
|
|
203
203
|
`);break}case"success":{a&&this.logger.logAtLevel(p,j`
|
|
204
204
|
Successfully loaded model ${g} in ${Date.now()-m}ms
|
|
205
|
-
`),f(this.createDomainSpecificModel(this.port,y.info,this.validator,this.logger));break}case"progress":{let{progress:D}=y;if(c!==void 0)B(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 b.onError.subscribeOnce(d),o!==void 0&&(o.aborted?(b.send({type:"cancel"}),d(o.reason)):o.addEventListener("abort",()=>{b.send({type:"cancel"}),d(o.reason)},{once:!0})),await h}unload(e){let t=A(1);return this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"unload","identifier",Vr,e,t),this.port.callRpc("unloadModel",{identifier:e},{stack:t})}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 t=await this.port.callRpc("getModelInfo",{specifier:{type:"query",query:{}},throwIfNotFound:!0},{stack:e});if(t===void 0)throw new Error("Backend should have thrown.");return this.createDomainSpecificModel(this.port,t,this.validator,new H("LLM",this.logger))}createDynamicHandle(e){let t=A(1);this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"createDynamicHandle","param",s.union([Vr,
|
|
205
|
+
`),f(this.createDomainSpecificModel(this.port,y.info,this.validator,this.logger));break}case"progress":{let{progress:D}=y;if(c!==void 0)B(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 b.onError.subscribeOnce(d),o!==void 0&&(o.aborted?(b.send({type:"cancel"}),d(o.reason)):o.addEventListener("abort",()=>{b.send({type:"cancel"}),d(o.reason)},{once:!0})),await h}unload(e){let t=A(1);return this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"unload","identifier",Vr,e,t),this.port.callRpc("unloadModel",{identifier:e},{stack:t})}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 t=await this.port.callRpc("getModelInfo",{specifier:{type:"query",query:{}},throwIfNotFound:!0},{stack:e});if(t===void 0)throw new Error("Backend should have thrown.");return this.createDomainSpecificModel(this.port,t,this.validator,new H("LLM",this.logger))}createDynamicHandle(e){let t=A(1);this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"createDynamicHandle","param",s.union([Vr,Ja]),e,t);let n;if(typeof e=="string"?n={identifier:e}:n=e,n.path?.includes("\\"))throw me(j`
|
|
206
206
|
Model path should not contain backslashes, even if you are on Windows. Use forward
|
|
207
207
|
slashes instead.
|
|
208
|
-
`,t);return this.createDomainDynamicHandle(this.port,{type:"query",query:n},this.validator,new H("DynamicHandle",this.logger))}createDynamicHandleFromInstanceReference(e){let t=A(1);return this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"createDynamicHandleFromInstanceReference","instanceReference",s.string(),e,t),this.createDomainDynamicHandle(this.port,{type:"instanceReference",instanceReference:e},this.validator,new H("DynamicHandle",this.logger))}async model(e,t={}){let n=A(1);if(e===void 0)return await this.getAny(n);[e,t]=this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`,"model",["modelKey","opts"],[Vr,this.getLoadModelOptsSchema()],[e,t],n);let{identifier:i,signal:o,verbose:a="info",config:l,onProgress:c}=t;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}=ee(),p=typeof a=="boolean"?"info":a,m=Date.now(),g=this.port.createChannel("getOrLoad",{identifier:e,loadTtlMs:t.ttl===void 0?void 0:t.ttl*1e3,loadConfigStack:
|
|
208
|
+
`,t);return this.createDomainDynamicHandle(this.port,{type:"query",query:n},this.validator,new H("DynamicHandle",this.logger))}createDynamicHandleFromInstanceReference(e){let t=A(1);return this.validator.validateMethodParamOrThrow(`client.${this.namespace}`,"createDynamicHandleFromInstanceReference","instanceReference",s.string(),e,t),this.createDomainDynamicHandle(this.port,{type:"instanceReference",instanceReference:e},this.validator,new H("DynamicHandle",this.logger))}async model(e,t={}){let n=A(1);if(e===void 0)return await this.getAny(n);[e,t]=this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`,"model",["modelKey","opts"],[Vr,this.getLoadModelOptsSchema()],[e,t],n);let{identifier:i,signal:o,verbose:a="info",config:l,onProgress:c}=t;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}=ee(),p=typeof a=="boolean"?"info":a,m=Date.now(),g=this.port.createChannel("getOrLoad",{identifier:e,loadTtlMs:t.ttl===void 0?void 0:t.ttl*1e3,loadConfigStack:Md("apiOverride",this.loadConfigToKVConfig(l??this.defaultLoadConfig))},b=>{switch(b.type){case"alreadyLoaded":return f(this.createDomainSpecificModel(this.port,b.info,this.validator,this.logger));case"unloadingOtherJITModel":{a&&this.logger.logAtLevel(p,j`
|
|
209
209
|
Unloading other JIT model ${b.info.modelKey}. (You can disable this behavior
|
|
210
210
|
by going to LM Studio -> Settings -> Developer -> Turn OFF JIT models auto-evict)
|
|
211
211
|
`);break}case"startLoading":{a&&(this.logger.logAtLevel(p,j`
|
|
@@ -215,13 +215,13 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
215
215
|
Model ${e} is not loaded. Start loading...
|
|
216
216
|
`));break}case"loadProgress":{let{progress:y}=b;if(c!==void 0)B(this.logger,"onProgress",c,[y]);else if(a){let D=Date.now();if(D-u>500||y===1){let v=(y*100).toFixed(1);this.logger.logAtLevel(p,`Loading the model, progress: ${v}%`),u=D}}break}case"loadSuccess":a&&this.logger.logAtLevel(p,j`
|
|
217
217
|
Successfully loaded model ${b.info.modelKey} in ${Date.now()-m}ms
|
|
218
|
-
`),f(this.createDomainSpecificModel(this.port,b.info,this.validator,this.logger))}},{stack:n});return g.onError.subscribeOnce(d),o?.addEventListener("abort",()=>{g.send({type:"cancel"}),d(o.reason)}),await h}};function wn(r,e,t){if(r!==void 0)return r===e?{checked:!1,value:t}:{checked:!0,value:r}}var ts=class{constructor(e,t){this.port=e,this.specifier=t}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})}},Bn=class extends ts{constructor(e,t,n,i=new H("EmbeddingModel")){super(e,t),this.validator=n,this.logger=i}async embed(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("client.embedding","embed","inputString",s.string().or(s.array(s.string())),e,t),Array.isArray(e)?await Promise.all(e.map(n=>this.port.callRpc("embedString",{inputString:n,modelSpecifier:this.specifier},{stack:t}))):await this.port.callRpc("embedString",{inputString:e,modelSpecifier:this.specifier},{stack:t})}async getContextLength(){let e=A(1),t=await this.getLoadConfig(e);return
|
|
218
|
+
`),f(this.createDomainSpecificModel(this.port,b.info,this.validator,this.logger))}},{stack:n});return g.onError.subscribeOnce(d),o?.addEventListener("abort",()=>{g.send({type:"cancel"}),d(o.reason)}),await h}};function wn(r,e,t){if(r!==void 0)return r===e?{checked:!1,value:t}:{checked:!0,value:r}}var ts=class{constructor(e,t){this.port=e,this.specifier=t}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})}},Bn=class extends ts{constructor(e,t,n,i=new H("EmbeddingModel")){super(e,t),this.validator=n,this.logger=i}async embed(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("client.embedding","embed","inputString",s.string().or(s.array(s.string())),e,t),Array.isArray(e)?await Promise.all(e.map(n=>this.port.callRpc("embedString",{inputString:n,modelSpecifier:this.specifier},{stack:t}))):await this.port.callRpc("embedString",{inputString:e,modelSpecifier:this.specifier},{stack:t})}async getContextLength(){let e=A(1),t=await this.getLoadConfig(e);return th.access(t,"contextLength")}async getEvalBatchSize(){let e=A(1),t=await this.getLoadConfig(e);return Tt.access(t,"embedding.load.llama.evalBatchSize")}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}},ma=class extends Bn{constructor(e,t,n,i=new H("EmbeddingModel")){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}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 me("This model has already been unloaded",t)}return e}},ga=class extends es{constructor(){super(...arguments),this.namespace="embedding",this.defaultLoadConfig={},this.loadModelConfigSchema=Xb}loadConfigToKVConfig(e){return wv.buildPartialConfig({"llama.acceleration.offloadRatio":e.gpu?.ratio,"load.gpuSplitConfig":gf(e.gpu),contextLength:e.contextLength,"llama.ropeFrequencyBase":wn(e.ropeFrequencyBase,0,0),"llama.ropeFrequencyScale":wn(e.ropeFrequencyScale,0,0),"llama.keepModelInMemory":e.keepModelInMemory,"llama.tryMmap":e.tryMmap})}createDomainSpecificModel(e,t,n,i){return new ma(e,t,n,i)}createDomainDynamicHandle(e,t,n,i){return new Bn(e,t,n,i)}},RD=mf.extend({onProgress:s.function().optional(),signal:s.instanceof(AbortSignal).optional()}),ID=s.object({onFileProcessList:s.function().optional(),onFileProcessingStart:s.function().optional(),onFileProcessingEnd:s.function().optional(),onFileProcessingStepStart:s.function().optional(),onFileProcessingStepProgress:s.function().optional(),onFileProcessingStepEnd:s.function().optional(),onSearchingStart:s.function().optional(),onSearchingEnd:s.function().optional(),verbose:s.union([s.boolean(),s.string()]).optional()}),OD=s.object({chunkingMethod:Gf.optional(),limit:s.number().int().optional(),embeddingModel:s.instanceof(Bn).optional(),databasePath:s.string().optional(),signal:s.instanceof(AbortSignal).optional(),...ID.shape});function MD(r){switch(r){case"loading":return"Loading";case"chunking":return"Chunking";case"embedding":return"Embedding";default:{let e=r;throw new Error(`Unexpected processing step: ${e}`)}}}var ya=class{constructor(e,t,n){this.filesPort=e,this.validator=t,this.logger=new H("File",n)}async getLocalFileAbsolutePath(e,t){return await this.filesPort.callRpc("getLocalFileAbsolutePath",{fileName:e},{stack:t})}createFileHandleFromChatMessagePartFileData(e){return new pe(this,e.identifier,e.fileType,e.sizeBytes,e.name)}async prepareImage(e){let t=await(0,Qe.readFileAsBase64)(e);if(t.success===!1)throw new Error(j`
|
|
219
219
|
Your current JavaScript environment does not support reading files. If you can read the file
|
|
220
220
|
using other methods, please use "prepareImageBase64".
|
|
221
|
-
`);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:o,sizeBytes:a}=await this.filesPort.callRpc("uploadFileBase64",{name:n,contentBase64:t.base64});return new
|
|
221
|
+
`);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:o,sizeBytes:a}=await this.filesPort.callRpc("uploadFileBase64",{name:n,contentBase64:t.base64});return new pe(this,i,o,a,n)}async prepareImageBase64(e,t){let{identifier:n,fileType:i,sizeBytes:o}=await this.filesPort.callRpc("uploadFileBase64",{name:e,contentBase64:t});return new pe(this,n,i,o,e)}async prepareFile(e){let t=await(0,Qe.readFileAsBase64)(e);if(t.success===!1)throw new Error(j`
|
|
222
222
|
Your current JavaScript environment does not support reading files. If you can read the file
|
|
223
223
|
using other methods, please use "prepareFileBase64".
|
|
224
|
-
`);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:o,sizeBytes:a}=await this.filesPort.callRpc("uploadFileBase64",{name:n,contentBase64:t.base64});return new
|
|
224
|
+
`);let n=e.split(/[\\/]/).at(-1),{identifier:i,fileType:o,sizeBytes:a}=await this.filesPort.callRpc("uploadFileBase64",{name:n,contentBase64:t.base64});return new pe(this,i,o,a,n)}async prepareFileBase64(e,t){let{identifier:n,fileType:i,sizeBytes:o}=await this.filesPort.callRpc("uploadFileBase64",{name:e,contentBase64:t});return new pe(this,n,i,o,e)}async retrieve(e,t,n={}){let i=this.logger,o=A(1);this.validator.validateMethodParamsOrThrow("client.retrieval","retrieve",["query","filePaths","opts"],[s.string(),s.array(s.instanceof(pe)),OD],[e,t,n],o);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=y=>{let D=t[y];if(D===void 0)throw new Error(`File not found: ${y}`);return D},h=y=>y.map(u),f=Dv.buildPartialConfig({chunkingMethod:n.chunkingMethod,databaseFile:n.databasePath,embeddingModel:(await n.embeddingModel.getModelInfo())?.identifier,limit:n.limit}),d,p=[],m=0,g=0,b="";return await new Promise((y,D)=>{let v=this.filesPort.createChannel("retrieve",{query:e,fileIdentifiers:t.map(S=>S.identifier),config:f},S=>{switch(S.type){case"onFileProcessList":d=h(S.indices),B(i,"onFileProcessList",n.onFileProcessList,[d]),c&&i.logAtLevel(l,j`
|
|
225
225
|
Found ${d.length} files need processing:
|
|
226
226
|
${d.map(_=>_.name).join(", ")}
|
|
227
227
|
`);break;case"onFileProcessingStart":{if(d===null)throw new Error("onFileProcessList must be called before onFileProcessingStart");let _=u(S.index);B(i,"onFileProcessingStart",n.onFileProcessingStart,[_,d.indexOf(_),d]),c&&(p[S.index]=Date.now(),i.logAtLevel(l,j`
|
|
@@ -230,12 +230,12 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
230
230
|
`));break}case"onFileProcessingEnd":{if(d===null)throw new Error("onFileProcessList must be called before onFileProcessingEnd");let _=u(S.index);B(i,"onFileProcessingEnd",n.onFileProcessingEnd,[_,d.indexOf(_),d]),c&&i.logAtLevel(l,j`
|
|
231
231
|
File processed: ${_.name}.
|
|
232
232
|
Time took: ${Date.now()-p[S.index]}ms
|
|
233
|
-
`);break}case"onFileProcessingStepStart":B(i,"onFileProcessingStepStart",n.onFileProcessingStepStart,[u(S.index),S.step]);break;case"onFileProcessingStepProgress":{B(i,"onFileProcessingStepProgress",n.onFileProcessingStepProgress,[u(S.index),S.step,S.progress]);let _=Date.now();if(c&&(_-g>500||S.progress===1)){g=_;let
|
|
234
|
-
> ${
|
|
235
|
-
`;b!==
|
|
233
|
+
`);break}case"onFileProcessingStepStart":B(i,"onFileProcessingStepStart",n.onFileProcessingStepStart,[u(S.index),S.step]);break;case"onFileProcessingStepProgress":{B(i,"onFileProcessingStepProgress",n.onFileProcessingStepProgress,[u(S.index),S.step,S.progress]);let _=Date.now();if(c&&(_-g>500||S.progress===1)){g=_;let x=j`
|
|
234
|
+
> ${MD(S.step)}: ${Math.round(S.progress*100)}%
|
|
235
|
+
`;b!==x&&(b=x,i.logAtLevel(l,x))}break}case"onFileProcessingStepEnd":B(i,"onFileProcessingStepEnd",n.onFileProcessingStepEnd,[u(S.index),S.step]);break;case"onSearchingStart":B(i,"onSearchingStart",n.onSearchingStart,[]),c&&(m=Date.now(),i.logAtLevel(l,"Start searching in the vector database..."));break;case"onSearchingEnd":B(i,"onSearchingEnd",n.onSearchingEnd,[]),c&&i.logAtLevel(l,j`
|
|
236
236
|
Finished searching in the vector database.
|
|
237
237
|
Time took: ${Date.now()-m}ms
|
|
238
|
-
`);break;case"result":{y({entries:S.result.entries.map(_=>({content:_.content,score:_.score,source:t[_.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,t={}){let n=A(1);this.validator.validateMethodParamsOrThrow("client.files","parseDocument",["fileHandle","opts"],[s.instanceof(
|
|
238
|
+
`);break;case"result":{y({entries:S.result.entries.map(_=>({content:_.content,score:_.score,source:t[_.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,t={}){let n=A(1);this.validator.validateMethodParamsOrThrow("client.files","parseDocument",["fileHandle","opts"],[s.instanceof(pe),RD],[e,t],n);let{onParserLoaded:i,onProgress:o,signal:a,...l}=t,{promise:c,resolve:u,reject:h}=ee();t.signal?.throwIfAborted();let f=!1,d=this.filesPort.createChannel("parseDocument",{fileIdentifier:e.identifier,parseOpts:l},p=>{switch(p.type){case"progress":{B(this.logger,"onProgress",o,[p.progress]);break}case"parserLoaded":{B(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 t=A(1);return await this.filesPort.callRpc("getDocumentParsingLibrary",{fileIdentifier:e.identifier},{stack:t})}};function Wd(r,e){let t=I.default.redBright(` ${r.title} `);return r.suggestion!==void 0&&(t+=`
|
|
239
239
|
|
|
240
240
|
|
|
241
241
|
`+I.default.bgWhite.black(" (!) SUGGESTION ")+`
|
|
@@ -245,82 +245,82 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
245
245
|
|
|
246
246
|
`+I.default.bgWhite.black(" (X) CAUSE ")+`
|
|
247
247
|
|
|
248
|
-
`+I.default.gray(r.cause)),
|
|
248
|
+
`+I.default.gray(r.cause)),me(t,e)}var vh=new Map;function Yr(r,e){vh.set(r,e)}function jD(r,e){if(r.length===0)return I.default.gray(" You don't have any LLMs downloaded.");let t=r.map(n=>I.default.cyanBright(" \u2022 "+n)).join(`
|
|
249
249
|
`);return r.length<e&&(t+=I.default.gray(`
|
|
250
250
|
... (and ${e-r.length} more)`)),t}Yr("generic.pathNotFound",({availablePathsSample:r,path:e,totalModels:t},n)=>gr(`Cannot find a model with path "${I.default.yellowBright(e)}"`,j`
|
|
251
251
|
Here are your available models:
|
|
252
252
|
|
|
253
|
-
${
|
|
253
|
+
${jD(r,t)}
|
|
254
254
|
|
|
255
255
|
Run
|
|
256
256
|
|
|
257
257
|
${I.default.yellowBright("lms ls")}
|
|
258
258
|
|
|
259
259
|
to see a full list of loadable models
|
|
260
|
-
`,n));function
|
|
260
|
+
`,n));function Dh(r,e){if(r.length===0)return I.default.gray(" You don't have any models loaded.");let t=r.map(n=>I.default.cyanBright(" \u2022 "+n)).join(`
|
|
261
261
|
`);return r.length<e&&(t+=I.default.gray(`
|
|
262
262
|
... (and ${e-r.length} more)`)),t}Yr("generic.identifierNotFound",({loadedModelsSample:r,identifier:e,totalLoadedModels:t},n)=>gr(`Cannot find a model with identifier "${I.default.yellowBright(e)}"`,j`
|
|
263
263
|
Here are your loaded models:
|
|
264
264
|
|
|
265
|
-
${
|
|
265
|
+
${Dh(r,t)}
|
|
266
266
|
|
|
267
267
|
Run
|
|
268
268
|
|
|
269
269
|
${I.default.yellowBright("lms ps")}
|
|
270
270
|
|
|
271
271
|
to see a full list of loaded models
|
|
272
|
-
`,n));Yr("generic.specificModelUnloaded",(r,e)=>
|
|
272
|
+
`,n));Yr("generic.specificModelUnloaded",(r,e)=>me(I.default.bgRed.white(j`
|
|
273
273
|
This model has already been unloaded.
|
|
274
|
-
`),e));function
|
|
275
|
-
The model must be ${I.default.yellowBright(
|
|
274
|
+
`),e));function ba(r){switch(r){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: ${r}`),"Unknown Model Domain"}}function BD(r){let e=[];return r.domain!==void 0&&e.push(j`
|
|
275
|
+
The model must be ${I.default.yellowBright(ba(r.domain))}
|
|
276
276
|
`),r.identifier!==void 0&&e.push(`The identifier must be exactly "${I.default.yellowBright(r.identifier)}"`),r.path!==void 0&&e.push(`The path must match "${I.default.yellowBright(r.path)}"`),e.length===0?I.default.gray(" \u2022 Any Model"):e.map(t=>I.default.white(" \u2022 "+t)).join(`
|
|
277
|
-
`)}Yr("generic.noModelMatchingQuery",({loadedModelsSample:r,totalLoadedModels:e,query:t},n)=>
|
|
277
|
+
`)}Yr("generic.noModelMatchingQuery",({loadedModelsSample:r,totalLoadedModels:e,query:t},n)=>me(j`
|
|
278
278
|
${I.default.bgRed.white(" No loaded model satisfies all requirements specified in the query. ")}
|
|
279
279
|
|
|
280
280
|
Loaded Models:
|
|
281
281
|
|
|
282
|
-
${
|
|
282
|
+
${Dh(r,e)}
|
|
283
283
|
|
|
284
284
|
Your query:
|
|
285
285
|
|
|
286
|
-
${
|
|
286
|
+
${BD(t)}
|
|
287
287
|
|
|
288
288
|
Run
|
|
289
289
|
|
|
290
290
|
${I.default.yellowBright("lms ps")}
|
|
291
291
|
|
|
292
292
|
to see a full list of loaded models with details
|
|
293
|
-
`,n));Yr("generic.domainMismatch",({actualDomain:r,expectedDomain:e,path:t},n)=>
|
|
293
|
+
`,n));Yr("generic.domainMismatch",({actualDomain:r,expectedDomain:e,path:t},n)=>me(j`
|
|
294
294
|
${I.default.bgRed.white(" Model has wrong domain. ")}
|
|
295
295
|
|
|
296
|
-
Expecting ${I.default.greenBright(t)} to be ${I.default.yellowBright(
|
|
297
|
-
`,n));function
|
|
296
|
+
Expecting ${I.default.greenBright(t)} to be ${I.default.yellowBright(ba(e))}, but it is actually ${I.default.yellowBright(ba(r))}.
|
|
297
|
+
`,n));function LD(r,e){if(r.length===0)return I.default.gray(" You don't have any presets available.");let t=r.map(({identifier:n,name:i})=>I.default.cyanBright(` \u2022 ${i} (${I.default.cyan(n)})`)).join(`
|
|
298
298
|
`);return r.length<e&&(t+=I.default.gray(`
|
|
299
299
|
... (and ${e-r.length} more)`)),t}Yr("generic.presetNotFound",({specifiedFuzzyPresetIdentifier:r,availablePresetsSample:e,totalAvailablePresets:t})=>gr(`Cannot find a preset with identifier "${I.default.yellowBright(r)}"`,j`
|
|
300
300
|
Here are your available presets:
|
|
301
301
|
|
|
302
|
-
${
|
|
302
|
+
${LD(e,t)}
|
|
303
303
|
|
|
304
304
|
Note: To specify a preset in the SDK, you need to use its identifier (in parentheses). You
|
|
305
305
|
can get a preset's identifier by right-clicking on it and then select "Copy Preset
|
|
306
306
|
Identifier".
|
|
307
|
-
`));function
|
|
307
|
+
`));function ND(r,e,t){if(r.displayData===void 0)return Wd(r,t);let n,i=vh.get(r.displayData.code);return i!==void 0?(n=i(r.displayData,t),pf(n,r),n):Wd(r,t)}function Zd({value:r,falseDefault:e}){return r===void 0?void 0:r===!1?{checked:!1,value:e}:{checked:!0,value:r}}var va=class{constructor(e,t){this.rounds=e,this.totalExecutionTimeSeconds=t}},$D=new Wi(Math.floor(Math.random()*(Number.MAX_SAFE_INTEGER/2/1e4))*1e4),Da=class{needsQueueing(){return!1}async runInQueue(e,t){if(t?.aborted)throw new Error("Operation aborted");return e()}},wa=class{constructor(){this.queue=[],this.executing=!1,this.poisoned=!1,this.poisonError=null}needsQueueing(){return this.executing||this.queue.length>0}async runInQueue(e,t){if(t?.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(t?.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(t){if(t.aborted)return i(new Error("Operation aborted"));t.addEventListener("abort",()=>{let o=this.queue.findIndex(a=>a.resolve===n&&a.reject===i);o!==-1&&(this.queue.splice(o,1),i(new Error("Operation aborted")))},{once:!0})}this.queue.push({fn:async()=>{try{if(t?.aborted)throw new Error("Operation aborted");let o=await e();return n(o),o}catch(o){throw i(o),o}},resolve:n,reject:i,signal:t})})}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(t){this.poisoned=!0,this.poisonError=t,this.clearQueue(t)}finally{this.executing=!1,this.poisoned||this.processQueue()}}}clearQueue(e){for(let t of this.queue)t.reject(e);this.queue=[]}},Sa=class{constructor(e,t,n){this.toolCallRequest=e,this.tool=t,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,t){if(this.resultContainer[0]!==null)throw gr(`Cannot call ${e} after a result has been set`,j`
|
|
308
308
|
This tool call guard has already set a result previously (${this.resultContainer[0].type}).
|
|
309
309
|
You cannot set a result more than once.
|
|
310
|
-
`,t)}},
|
|
310
|
+
`,t)}},wh=s.object({onFirstToken:s.function().optional(),onPredictionFragment:s.function().optional(),onMessage:s.function().optional(),onRoundStart:s.function().optional(),onRoundEnd:s.function().optional(),onPredictionCompleted:s.function().optional(),onPromptProcessingProgress:s.function().optional(),onToolCallRequestStart:s.function().optional(),onToolCallRequestNameReceived:s.function().optional(),onToolCallRequestArgumentFragmentGenerated:s.function().optional(),onToolCallRequestEnd:s.function().optional(),onToolCallRequestFinalized:s.function().optional(),onToolCallRequestFailure:s.function().optional(),onToolCallRequestDequeued:s.function().optional(),guardToolCall:s.function().optional(),handleInvalidToolRequest:s.function().optional(),maxPredictionRounds:s.number().int().min(1).optional(),signal:s.instanceof(AbortSignal).optional(),allowParallelToolExecution:s.boolean().optional()}),UD=(r,e)=>{if(e)return r.message;throw r};async function Sh(r,e,t,n,i,o,a,l){let c=new AbortController,u=mt.from(r),h=-1,f=!1;t.signal!==void 0&&(t.signal.aborted?c.abort(t.signal.reason):t.signal.addEventListener("abort",()=>{c.abort(t.signal?.reason)},{once:!0}));let d=!1,p=0,m=new Map;for(let g of e)m.has(g.name)&&i.warnText`
|
|
311
311
|
Duplicate tool (${g.name}) found in the tools array. The last tool with the same name
|
|
312
312
|
will be used.
|
|
313
|
-
`,m.set(g.name,g);do{let g=!0;t.maxPredictionRounds!==void 0&&p+1>=t.maxPredictionRounds&&(g=!1);let b=!1,y=!1,D=[],v=[],S=[],_=[],
|
|
313
|
+
`,m.set(g.name,g);do{let g=!0;t.maxPredictionRounds!==void 0&&p+1>=t.maxPredictionRounds&&(g=!1);let b=!1,y=!1,D=[],v=[],S=[],_=[],x=0,E=[],z=[],{promise:w,resolve:C,reject:P}=ee(),{promise:U,resolve:Z,reject:q}=ee(),_e=async(N,ne,fe)=>{let gt;try{gt=await(t.handleInvalidToolRequest??UD)(N,ne)}catch(yt){throw c.signal.aborted?c.signal.reason:(c.abort(),yt)}if(gt===void 0)return;let Ot;try{Ot=JSON.stringify(gt)}catch{throw c.abort(),me("handleInvalidToolRequest returned a value that cannot be converted to JSON.",n)}ne===void 0?i.warnText`
|
|
314
314
|
The "handleInvalidToolRequest" callback has returned a result, but the tool request has
|
|
315
315
|
completely failed to parse, thus LM Studio cannot provide the result to the tool call.
|
|
316
316
|
Please avoid returning a result when the second parameter of the callback is undefined.
|
|
317
317
|
See the documentation for "handleInvalidToolRequest" for more information.
|
|
318
|
-
`:(
|
|
318
|
+
`:(E.push({index:fe,data:{type:"toolCallResult",toolCallId:ne.id,content:Ot}}),x++)};c.signal.throwIfAborted(),B(i,"onRoundStart",t.onRoundStart,[p]);let ye=!1,be=new AbortController,Q=t.allowParallelToolExecution?new Da:new wa,Fe=!1,Qr=!1;a({allowTools:g,history:u._internalGetData(),signal:be.signal,handleFragment:N=>{y||(y=!0,B(i,"onFirstToken",t.onFirstToken,[p])),B(i,"onFragment",t.onPredictionFragment,[{roundIndex:p,...N}]),D.push(N.content),N.isStructural||(N.reasoningType==="reasoning"?v.push(N.content):S.push(N.content))},handlePromptProcessingProgress:N=>{B(i,"onPromptProcessingProgress",t.onPromptProcessingProgress,[p,N])},handleToolCallGenerationStart:N=>{h=$D.next(),Fe=!1,Qr=!1,ye=!0,B(i,"onToolCallRequestStart",t.onToolCallRequestStart,[p,h,{toolCallId:N}])},handleToolCallGenerationNameReceived:N=>{Fe=!0,B(i,"onToolCallRequestNameReceived",t.onToolCallRequestNameReceived,[p,h,N])},handleToolCallGenerationArgumentFragmentGenerated:N=>{Qr=!0,B(i,"onToolCallRequestArgumentFragmentGenerated",t.onToolCallRequestArgumentFragmentGenerated,[p,h,N])},handleToolCallGenerationEnd:(N,ne)=>{let fe=h;ye=!1;let gt=x;x++,Fe||B(i,"onToolCallRequestNameReceived",t.onToolCallRequestNameReceived,[p,fe,N.name]),Qr||B(i,"onToolCallRequestArgumentFragmentGenerated",t.onToolCallRequestArgumentFragmentGenerated,[p,fe,JSON.stringify(N.arguments??{},null,2)]);let Ot={...N};_.push(Ot);let yt=m.get(N.name);if(yt===void 0){let bt=new cr(`Cannot find tool with name ${N.name}.`,ne);z.push(_e(bt,N,gt).catch(q)),B(i,"onToolCallRequestFailure",t.onToolCallRequestFailure,[p,fe,bt]);return}try{yt.checkParameters(Ot.arguments)}catch(bt){let br=new cr(bt.message,ne);z.push(_e(br,N,gt).catch(q)),B(i,"onToolCallRequestFailure",t.onToolCallRequestFailure,[p,fe,br]);return}let Oh=new ea(new H(`Tool(${N.name})`,i),c.signal,fe),dl=Q.needsQueueing();B(i,"onToolCallRequestEnd",t.onToolCallRequestEnd,[p,fe,{isQueued:dl,toolCallRequest:N,rawContent:ne}]),z.push(Q.runInQueue(async()=>{if(dl&&B(i,"onToolCallRequestDequeued",t.onToolCallRequestDequeued,[p,fe]),t.guardToolCall!==void 0){let Mt=[null];if(await t.guardToolCall(p,fe,new Sa(N,yt,Mt)),Mt[0]===null)throw gr("Tool call guard did not allow or deny the tool call.",j`
|
|
319
319
|
The \`guardToolCall\` handler must call one of the methods on the controller
|
|
320
320
|
to allow or deny the tool call.
|
|
321
|
-
`,n);let
|
|
321
|
+
`,n);let ms=Mt[0];switch(ms.type){case"allow":break;case"allowAndOverrideParameters":{Ot.arguments=ms.parameters;break}case"deny":{E.push({index:gt,data:{type:"toolCallResult",toolCallId:N.id,content:JSON.stringify({error:ms.reason})}});return}}}B(i,"onToolCallRequestFinalized",t.onToolCallRequestFinalized,[p,fe,{toolCallRequest:N,rawContent:ne}]);let bt;try{bt=await yt.implementation(Ot.arguments??{},Oh)}catch(Mt){if(!(Mt instanceof ta))throw Mt;f=!0}let br;if(bt===void 0)br="undefined";else try{br=JSON.stringify(bt)}catch{throw me(`Return value of tool ${yt.name} cannot be converted to JSON.`,n)}E.push({index:gt,data:{type:"toolCallResult",toolCallId:N.id,content:br}})},c.signal).catch(q))},handleToolCallGenerationFailed:(N,ne)=>{ye=!1;let fe=new cr(N.message,ne);z.push(_e(fe,void 0,0).catch(q)),B(i,"onToolCallRequestFailure",t.onToolCallRequestFailure,[p,h,fe])},handlePredictionEnd:N=>{let ne=l({endPacket:N,content:D.join(""),reasoningContent:v.join(""),nonReasoningContent:S.join(""),predictionsPerformed:p});B(i,"onPredictionCompleted",t.onPredictionCompleted,[ne]),C()},handleError:N=>{if(ye){let ne=new cr(`Generation failed: ${N.message}`,void 0);ye=!1,B(i,"onToolCallRequestFailure",t.onToolCallRequestFailure,[p,h,ne])}b=!0,P(N)}});let ve=()=>{b||(b=!0,be.abort(c.signal.reason))};if(c.signal.addEventListener("abort",ve),w.then(()=>{let N=ce.from({role:"assistant",content:[{type:"text",text:D.join("")},..._.map(ne=>({type:"toolCallRequest",toolCallRequest:ne}))]});u.append(N.asMutableCopy()),B(i,"onMessage",t.onMessage,[N])}).then(()=>Promise.all(z)).then(()=>Z(),q),await U,d=!1,E.length>0){E.sort((ne,fe)=>ne.index-fe.index);let N=ce.from({role:"tool",content:E.map(ne=>ne.data)});u.append(N.asMutableCopy()),B(i,"onMessage",t.onMessage,[N]),d=!0}B(i,"onRoundEnd",t.onRoundEnd,[p]),p++,t.maxPredictionRounds!==void 0&&p>=t.maxPredictionRounds&&(d=!1),d&&=!f}while(d);return new va(p,(performance.now()-o)/1e3)}var Ln=class{constructor(e,t,n,i,o,a,l,c){this.content=e,this.reasoningContent=t,this.nonReasoningContent=n,this.stats=i,this.modelInfo=o,this.roundIndex=a,this.loadConfig=l,this.predictionConfig=c}},Ca=class extends Ln{constructor(e,t,n,i,o,a,l,c,u){super(e,t,n,i,o,a,l,c),this.parsed=u}},rs=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("");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 Ln(t,n,i,this.stats,this.modelInfo,0,this.loadModelConfig,this.predictionConfig):new Ca(t,n,i,this.stats,this.modelInfo,0,this.loadModelConfig,this.predictionConfig,this.parser(t))}constructor(e,t){super(),this.onCancel=e,this.parser=t,this.stats=null,this.modelInfo=null,this.loadModelConfig=null,this.predictionConfig=null}static create(e,t){let n=new r(e,t);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()}},Ch=Qa.extend({onPromptProcessingProgress:s.function().optional(),onFirstToken:s.function().optional(),onPredictionFragment:s.function().optional(),onToolCallRequestStart:s.function().optional(),onToolCallRequestNameReceived:s.function().optional(),onToolCallRequestArgumentFragmentGenerated:s.function().optional(),onToolCallRequestEnd:s.function().optional(),onToolCallRequestFailure:s.function().optional(),signal:s.instanceof(AbortSignal).optional(),preset:s.string().optional()});function _h(r){let{onPromptProcessingProgress:e,onFirstToken:t,onPredictionFragment:n,onToolCallRequestStart:i,onToolCallRequestNameReceived:o,onToolCallRequestArgumentFragmentGenerated:a,onToolCallRequestEnd:l,onToolCallRequestFailure:c,signal:u,preset:h,...f}=r;return[f,{onPromptProcessingProgress:e,onFirstToken:t,onPredictionFragment:n,onToolCallRequestStart:i,onToolCallRequestNameReceived:o,onToolCallRequestArgumentFragmentGenerated:a,onToolCallRequestEnd:l,onToolCallRequestFailure:c,signal:u,preset:h}]}var zD=Ch.extend({onMessage:s.function().optional(),onToolCallRequestStart:s.function().optional(),onToolCallRequestNameReceived:s.function().optional(),onToolCallRequestArgumentFragmentGenerated:s.function().optional(),onToolCallRequestEnd:s.function().optional(),onToolCallRequestFailure:s.function().optional()});function qD(r){let{onMessage:e,...t}=r,[n,i]=_h(t);return[n,i,{onMessage:e}]}var VD=Qa.extend(wh.shape).extend({preset:s.string().optional()});function WD(r){let{onFirstToken:e,onPredictionFragment:t,onMessage:n,onRoundStart:i,onRoundEnd:o,onPredictionCompleted:a,onPromptProcessingProgress:l,onToolCallRequestStart:c,onToolCallRequestNameReceived:u,onToolCallRequestArgumentFragmentGenerated:h,onToolCallRequestEnd:f,onToolCallRequestFinalized:d,onToolCallRequestFailure:p,onToolCallRequestDequeued:m,guardToolCall:g,handleInvalidToolRequest:b,maxPredictionRounds:y,signal:D,preset:v,allowParallelToolExecution:S,..._}=r;return[_,{onFirstToken:e,onPredictionFragment:t,onMessage:n,onRoundStart:i,onRoundEnd:o,onPredictionCompleted:a,onPromptProcessingProgress:l,onToolCallRequestStart:c,onToolCallRequestNameReceived:u,onToolCallRequestArgumentFragmentGenerated:h,onToolCallRequestEnd:f,onToolCallRequestFinalized:d,onToolCallRequestFailure:p,onToolCallRequestDequeued:m,guardToolCall:g,handleInvalidToolRequest:b,maxPredictionRounds:y,signal:D,preset:v,allowParallelToolExecution:S}]}var ZD=j`
|
|
322
322
|
{% 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`
|
|
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 Sv(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(),Ch],[e,t],n);let[i,o]=_h(t),[a,l]=pt.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:ZD},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,zD],[e,t],n);let[i,o]=pt.create(),[a,l,c]=qD(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(mt.from(e)._internalGetData(),Ro(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,[ce.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,VD],[e,n],o);let[a,{preset:l,...c}]=WD(n);if(a.structured!==void 0&&a.structured.type!=="none"&&t.length>0)throw me("Structured output is currently not supported in .act() when there are tools.",o);if(a.structured!==void 0&&a.structured.parse!==void 0)throw me("zod schema is not supported in .act().",o);if(a.rawTools!==void 0)throw me("`rawTools` is not supported in act. Use `tools` instead",o);let u;t.length===0?u={type:"none"}:u={type:"toolArray",tools:t.map(ll)};let h=Ro(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig({...a,rawTools:u})),f=Ro(this.internalKVConfigStack,"apiOverride",this.predictionConfigInputToKVConfig({...a,rawTools:{type:"none"}}));return await Sh(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:x,handleError:E})=>{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":{x({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(E)},({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,Df],[e,t],n),(await this.port.callRpc("applyPromptTemplate",{specifier:this.specifier,history:mt.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})}},_a=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 me("This model has already been unloaded",t)}return e}},Ea=class extends es{constructor(){super(...arguments),this.namespace="llm",this.defaultLoadConfig={},this.loadModelConfigSchema=Qb}loadConfigToKVConfig(e){return vv.buildPartialConfig({contextLength:e.contextLength,"llama.evalBatchSize":e.evalBatchSize,"llama.acceleration.offloadRatio":e.gpu?.ratio,numCpuExpertLayersRatio:e.gpu?.numCpuExpertLayersRatio,"load.gpuSplitConfig":gf(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":Zd({value:e.llamaKCacheQuantizationType,falseDefault:"f16"}),"llama.vCacheQuantizationType":Zd({value:e.llamaVCacheQuantizationType,falseDefault:"f16"})})}createDomainSpecificModel(e,t,n,i){return new _a(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}},xa=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()}},GD=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()}),KD=wh.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??Jf,workingDirectoryPath:t??void 0};if(e!==void 0)throw gr("Cannot use plugin config with prediction process",j`
|
|
324
324
|
You cannot provide a plugin config to the generator handle when it is associated with a
|
|
325
325
|
prediction process. The plugin config that was configured for the prediction process will
|
|
326
326
|
be used instead.
|
|
@@ -334,7 +334,7 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
334
334
|
|
|
335
335
|
If you want to use a different working directory, you will need to create a separate
|
|
336
336
|
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`
|
|
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,GD],[e,t],n);let{onFirstToken:i,onPredictionFragment:o,onMessage:a,signal:l,pluginConfig:c,workingDirectory:u}=t,h=!1,f=!1,d=new Uo;l!==void 0&&(l.aborted?d.cancel():l.addEventListener("abort",()=>d.cancel(),{once:!0}));let{ongoingPrediction:p,finished:m,failed:g,push:b}=xa.create(this.pluginIdentifier,()=>{d.cancel()}),y=this.port.createChannel("generateWithGenerator",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.getPluginConfigSpecifier(c,u,n),tools:[],history:mt.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,[ce.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,KD],[e,n],o);let{pluginConfig:a,workingDirectory:l,...c}=n,u=t.map(ll);return await Sh(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 x=this.port.createChannel("generateWithGenerator",{pluginIdentifier:this.pluginIdentifier,pluginConfigSpecifier:this.getPluginConfigSpecifier(a,l,o),tools:h?u:[],history:f},E=>{switch(E.type){case"fragment":{p(E.fragment);break}case"promptProcessingProgress":{m(E.progress);break}case"toolCallGenerationStart":{g(E.toolCallId);break}case"toolCallGenerationNameReceived":{b(E.name);break}case"toolCallGenerationArgumentFragmentGenerated":{y(E.content);break}case"toolCallGenerationEnd":{D(E.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?x.send({type:"cancel"}):d.addEventListener("abort",()=>{x.send({type:"cancel"})},{once:!0}),x.onError.subscribeOnce(_)},({content:h,nonReasoningContent:f,reasoningContent:d})=>new is(h,d,f,this.pluginIdentifier))}},HD=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})}},ka=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(),Pf],[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)}},JD=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},YD=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 QD(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 XD(...r){return r.map(QD).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 mt.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 Fa(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 Pa(this.processingControllerHandle,n)}createDebugInfoBlock(e){let t=qr();return this.sendUpdate({type:"debugInfoBlock.create",id:t,debugInfo:e}),new Ta(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 Aa(this.processingControllerHandle,a,e??"assistant")}debug(...e){this.createDebugInfoBlock(XD(...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 Sb(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 Ra(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)}},Fa=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}},Pa=class{constructor(e,t){this.handle=e,this.id=t}},Ta=class{constructor(e,t){this.handle=e,this.id=t}},Aa=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=JD(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{YD(t)}}},Ra=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})}},Ia=class extends Nn{constructor(e,t,n,i,o){super(e,t,n,i,o)}},Oa=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)})}},Ma=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=ce.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 ce)]).safeParse(d);if(!p.success)throw new Error("PromptPreprocessor returned an invalid value:"+Ye.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 Ia(this.client,u.signal,a.pluginConfig,a.globalPluginConfig,a.workingDirectoryPath);e(f).then(d=>{let p=d.map(ll);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`
|
|
338
338
|
Tool call returned undefined. This is not expected as the model always expects
|
|
339
339
|
a result. If you don't want to return anything, you can just return a string
|
|
340
340
|
reporting that the tool call was successful. For example: "operation
|
|
@@ -345,16 +345,16 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
345
345
|
Tool call succeeded, but returned a value that is not JSON serializable. In
|
|
346
346
|
order to provide the result to the model, return values of tools must be JSON
|
|
347
347
|
serializable. In this case, we will give the model string "${m}".
|
|
348
|
-
`})}o.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||(o.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 t=A(1);this.validator.validateMethodParamOrThrow("plugins","setGenerator","generator",
|
|
348
|
+
`})}o.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||(o.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 t=A(1);this.validator.validateMethodParamOrThrow("plugins","setGenerator","generator",HD,e,t);let n=new H("Generator",this.rootLogger);n.info("Register with LM Studio");let i=new Map,o=this.port.createChannel("setGenerator",void 0,a=>{let l=a.type;switch(l){case"generate":{let c=new H(`Request (${a.taskId.substring(0,6)})`,n);c.info("New generate request received.");let u=new AbortController,h=new Oa(o,a.taskId),f=new ka(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=mt.createRaw(a.input,!1);e(f,d).then(p=>{p!==void 0&&c.warnText`
|
|
349
349
|
The generator has returned a value. This it not expected. You should report
|
|
350
350
|
generated content using method on the controller. The returned value will be
|
|
351
351
|
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(`
|
|
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})}},ew=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},tw=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 Rv({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=ew(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{tw(i)}}})}},ja=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)}}},rw=s.object({pluginConfig:X.optional(),workingDirectory:s.string().optional()}),nw=s.object({manifest:Ka}),Ba=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",nw,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 Ma(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"],[jb,rw],[e,t],n),await this.internalStartToolUseSession(e,{type:"direct",config:t.pluginConfig??Jf,workingDirectoryPath:t.workingDirectory})}async startToolUseSessionUsingPredictionProcess(e,t,n,i){return await ja.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)}},iw=s.object({onStartFinalizing:s.function().optional(),onProgress:s.function().optional(),signal:s.instanceof(AbortSignal).optional()}),La=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",iw,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})}},sw=s.object({onProgress:s.function().optional(),onStartFinalizing:s.function().optional(),signal:s.instanceof(AbortSignal).optional()}),Na=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",sw,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}},$a=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 Na(this.repositoryPort,this.validator,this.logger,t))}},ow=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()}),aw=s.object({path:s.string(),description:s.string().optional(),makePrivate:s.boolean().optional(),writeRevision:s.boolean().optional(),overrides:Ce.optional(),onMessage:s.function().optional()}),lw=s.object({onAuthenticationUrl:s.function()}),cw=s.object({keyId:s.string(),publicKey:s.string(),privateKey:s.string()});s.object({userName:s.string()});var uw=s.object({owner:s.string(),name:s.string(),onPlanUpdated:s.function().optional()}),Ua=class{constructor(e,t,n){this.repositoryPort=e,this.validator=t,this.downloadPlanFinalizationRegistry=new FinalizationRegistry(({owner:i,name:o})=>{this.logger.warn(`
|
|
353
353
|
A download plan for artifact ${i}/${o} has been garbage collected without being
|
|
354
354
|
disposed. Please make sure you are creating the download plan with the "using" keyword.
|
|
355
355
|
|
|
356
356
|
This is a memory leak and needs to be fixed.
|
|
357
|
-
`)}),this.logger=new H("Repository",n)}async searchModels(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("repository","search","opts",
|
|
357
|
+
`)}),this.logger=new H("Repository",n)}async searchModels(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("repository","search","opts",Zf,e,t);let{results:n}=await this.repositoryPort.callRpc("searchModels",{opts:e},{stack:t});return n.map(i=>new $a(this.repositoryPort,this.validator,this.logger,i))}async installPluginDependencies(e){let t=A(1);this.validator.validateMethodParamOrThrow("repository","installPluginDependencies","pluginFolder",s.string(),e,t),await this.repositoryPort.callRpc("installPluginDependencies",{pluginFolder:e},{stack:t})}async downloadArtifact(e){let t=A(1);this.validator.validateMethodParamOrThrow("client.repository","downloadArtifact","opts",ow,e,t);let{owner:n,name:i,revisionNumber:o,path:a,onProgress:l,onStartFinalizing:c,signal:u}=e,{promise:h,resolve:f,reject:d}=ee(),p=this.repositoryPort.createChannel("downloadArtifact",{artifactOwner:n,artifactName:i,revisionNumber:o,path:a},g=>{switch(g.type){case"downloadProgress":{B(this.logger,"onProgress",l,[g.update]);break}case"startFinalizing":{B(this.logger,"onStartFinalizing",c,[]);break}case"success":{f();break}default:{let b=g;throw new Error(`Unexpected message type: ${b}`)}}},{stack:t});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 t=A(1),{path:n,description:i,makePrivate:o,writeRevision:a,overrides:l,onMessage:c}=this.validator.validateMethodParamOrThrow("repository","pushArtifact","opts",aw,e,t),u=this.repositoryPort.createChannel("pushArtifact",{path:n,description:i,makePrivate:o,writeRevision:a,overrides:l},p=>{let m=p.type;if(m==="message")B(this.logger,"onMessage",c,[p.message]);else{let g=m;throw new Error(`Unexpected message type: ${g}`)}},{stack:t}),{promise:h,resolve:f,reject:d}=ee();u.onError.subscribeOnce(d),u.onClose.subscribeOnce(f),await h}async getLocalArtifactFileList(e){let t=A(1);this.validator.validateMethodParamOrThrow("repository","getLocalArtifactFileList","path",s.string(),e,t);let{fileList:n}=await this.repositoryPort.callRpc("getLocalArtifactFiles",{path:e},{stack:t});return n}async ensureAuthenticated(e){let t=A(1);this.validator.validateMethodParamOrThrow("repository","ensureAuthenticated","opts",lw,e,t);let{promise:n,resolve:i,reject:o}=ee();this.repositoryPort.createChannel("ensureAuthenticated",void 0,l=>{let c=l.type;switch(c){case"authenticationUrl":{B(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(o),await n}async loginWithPreAuthenticatedKeys(e){let t=A(1);this.validator.validateMethodParamOrThrow("repository","loginWithPreAuthenticatedKeys","opts",cw,e,t);let{keyId:n,publicKey:i,privateKey:o}=e,{userName:a}=await this.repositoryPort.callRpc("loginWithPreAuthenticatedKeys",{keyId:n,publicKey:i,privateKey:o},{stack:t});return{userName:a}}createArtifactDownloadPlanner(e){let{owner:t,name:n,onPlanUpdated:i}=this.validator.validateMethodParamOrThrow("repository","createArtifactDownloadPlanner","opts",uw,e),o=A(1),a=this.repositoryPort.createChannel("createArtifactDownloadPlan",{owner:t,name:n},void 0,{stack:o}),l=new La(t,n,i,a,this.validator,()=>{this.downloadPlanFinalizationRegistry.unregister(l)});return this.downloadPlanFinalizationRegistry.register(l,{owner:t,name:n},l),l}},dw=s.object({port:s.number().int().min(1).max(65535).describe("Port to run the API server on. Must be between 1 and 65535."),cors:s.boolean().describe("Enable CORS on the API server. Allows any website to access the server.")}),za=class{constructor(e,t,n){this.systemPort=e,this.validator=t,this.logger=new H("System",n)}async listDownloadedModels(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("client.system","listDownloadedModels","domain",s.union([s.literal("llm"),s.literal("embedding"),s.undefined()]),e,t);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),t=this.systemPort.createChannel("alive",void 0,void 0,{stack:e}),{promise:n,resolve:i}=ee();t.onError.subscribeOnce(i),t.onClose.subscribeOnce(i),await n}async notify(e){let t=A(1);e=this.validator.validateMethodParamOrThrow("client.system","notify","notification",nf,e,t),await this.systemPort.callRpc("notify",e,{stack:t})}async getLMStudioVersion(){let e=A(1);return await this.systemPort.callRpc("version",void 0,{stack:e})}async unstable_setExperimentFlag(e,t){let n=A(1);[e,t]=this.validator.validateMethodParamsOrThrow("client.system","setExperimentFlag",["flag","value"],[s.string(),s.boolean()],[e,t],n),await this.systemPort.callRpc("setExperimentFlag",{code:e,value:t},{stack:n})}async unstable_getExperimentFlags(){let e=A(1);return await this.systemPort.callRpc("getExperimentFlags",void 0,{stack:e})}async startHttpServer(e){let t=A(1);return e=this.validator.validateMethodParamOrThrow("client.system","startHttpServer","args",dw,e),await this.systemPort.callRpc("startHttpServer",{port:e.port,cors:e.cors},{stack:t})}async stopHttpServer(){let e=A(1);return await this.systemPort.callRpc("stopHttpServer",void 0,{stack:e})}},fw=s.object({logger:s.any().optional(),baseUrl:s.string().optional(),verboseErrorMessages:s.boolean().optional(),clientIdentifier:s.string().optional(),clientPasskey:s.string().optional(),disableConnection:s.boolean().optional(),llmPort:s.any().optional(),embeddingPort:s.any().optional(),systemPort:s.any().optional(),diagnosticsPort:s.any().optional(),retrievalPort:s.any().optional(),filesPort:s.any().optional(),repositoryPort:s.any().optional(),pluginsPort:s.any().optional()}).strict(),cs=class{validateBaseUrlOrThrow(e){let t;try{t=new URL(e)}catch{this.logger.throw(j`
|
|
358
358
|
Failed to construct LMStudioClient. The baseUrl passed in is invalid. Received: ${e}
|
|
359
359
|
`)}["ws:","wss:"].includes(t.protocol)||this.logger.throw(j`
|
|
360
360
|
Failed to construct LMStudioClient. The baseUrl passed in must have protocol "ws" or "wss".
|
|
@@ -371,7 +371,7 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
371
371
|
Failed to construct LMStudioClient. The baseUrl passed in must not end with a "/". If you
|
|
372
372
|
are reverse-proxying, you should remove the trailing slash from the baseUrl. Received:
|
|
373
373
|
${e}
|
|
374
|
-
`)}async isLocalhostWithGivenPortLMStudioServer(e){let t=await fetch(`http://127.0.0.1:${e}/lmstudio-greeting`);if(t.status!==200)throw new Error("Status is not 200.");if((await t.json())?.lmstudio!==!0)throw new Error("Not an LM Studio server.");return e}async guessBaseUrl(e){if(
|
|
374
|
+
`)}async isLocalhostWithGivenPortLMStudioServer(e){let t=await fetch(`http://127.0.0.1:${e}/lmstudio-greeting`);if(t.status!==200)throw new Error("Status is not 200.");if((await t.json())?.lmstudio!==!0)throw new Error("Not an LM Studio server.");return e}async guessBaseUrl(e){if(yh()!==null)return Promise.resolve("Using hosted env");if(Sn.default.browser)try{return this.isLocalhostWithGivenPortLMStudioServer(1234),"ws://127.0.0.1:1234"}catch{j`
|
|
375
375
|
${I.default.redBright("Failed to connect to LM Studio.")}
|
|
376
376
|
|
|
377
377
|
Is LM Studio running? If not, please start it by running:
|
|
@@ -388,7 +388,7 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
388
388
|
${I.default.white("(i) For more information, refer to the LM Studio documentation:")}
|
|
389
389
|
|
|
390
390
|
${I.default.gray("https://lmstudio.ai/docs/local-server")}
|
|
391
|
-
`}return Promise.any(
|
|
391
|
+
`}return Promise.any(Oy.map(this.isLocalhostWithGivenPortLMStudioServer)).then(t=>`ws://127.0.0.1:${t}`,()=>{throw me(j`
|
|
392
392
|
${I.default.redBright("Failed to connect to LM Studio.")}
|
|
393
393
|
|
|
394
394
|
Please make sure LM Studio is running on your machine.
|
|
@@ -403,7 +403,7 @@ ${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label"
|
|
|
403
403
|
${I.default.white("(i) For more information, refer to the LM Studio documentation:")}
|
|
404
404
|
|
|
405
405
|
${I.default.gray("https://lmstudio.ai/docs/local-server")}
|
|
406
|
-
`,e)})}createPort(e,t,n){return
|
|
406
|
+
`,e)})}createPort(e,t,n){return TD(n,this.resolvingBaseUrl,e,this.clientIdentifier,this.clientPasskey,new H(t,this.logger),{errorDeserializer:ND,verboseErrorMessage:this.verboseErrorMessages})}constructor(e={}){let{logger:t,baseUrl:n,verboseErrorMessages:i,clientIdentifier:o,clientPasskey:a,disableConnection:l,llmPort:c,embeddingPort:u,systemPort:h,diagnosticsPort:f,retrievalPort:d,filesPort:p,repositoryPort:m,pluginsPort:g}=new Ye().validateConstructorParamOrThrow("LMStudioClient","opts",fw,e);if(globalThis.__LMS_PLUGIN_CONTEXT&&e.baseUrl===void 0)throw new Error(j`
|
|
407
407
|
You cannot create a local LMStudioClient in a plugin context. To use LM Studio APIs, use
|
|
408
408
|
the "client" property attached to the Controllers.
|
|
409
409
|
|
|
@@ -424,7 +424,7 @@ export async function generate(ctl: GeneratorController) {
|
|
|
424
424
|
the LMStudioClient constructor:
|
|
425
425
|
|
|
426
426
|
${"const client = new LMStudioClient({ baseUrl: 'ws://<host_name>:<port>' });"}
|
|
427
|
-
`);this.logger=new H("LMStudioClient",t),this.clientIdentifier=o??(0,
|
|
427
|
+
`);this.logger=new H("LMStudioClient",t),this.clientIdentifier=o??(0,Qe.generateRandomBase64)(18),this.clientPasskey=a??(0,Qe.generateRandomBase64)(18);let b=A(1);l?this.resolvingBaseUrl=new Promise(()=>{}):n===void 0?this.resolvingBaseUrl=this.guessBaseUrl(i?b:void 0):(this.validateBaseUrlOrThrow(n),this.resolvingBaseUrl=n),this.verboseErrorMessages=i??!0,this.llmPort=c??this.createPort("llm","LLM",_D()),this.embeddingPort=u??this.createPort("embedding","Embedding",SD()),this.systemPort=h??this.createPort("system","System",kD()),this.diagnosticsPort=f??this.createPort("diagnostics","Diagnostics",wD()),this.filesPort=p??this.createPort("files","Files",CD()),this.repositoryPort=m??this.createPort("repository","Repository",xD()),this.pluginsPort=g??this.createPort("plugins","Plugins",ED());let y=new Ye;this.llm=new Ea(this,this.llmPort,new H("LLM",this.logger),y),this.embedding=new ga(this,this.embeddingPort,new H("Embedding",this.logger),y),this.system=new za(this.systemPort,y,this.logger),this.diagnostics=new pa(this.diagnosticsPort,y,this.logger),this.files=new ya(this.filesPort,y,this.logger),this.repository=new Ua(this.repositoryPort,y,this.logger),this.plugins=new Ba(this.pluginsPort,this,y,this.logger,t)}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 Eh(r,e,t,n,i){return(await new tn({host:e}).generate({model:t,system:n,prompt:r,stream:!1,images:i})).response||"No response"}async function xh(r,e,t,n,i){try{let o=new cs({baseUrl:e}),a=await o.llm.model(t),l={role:"user",content:r};if(i){let h=await o.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(o){let a=o instanceof Error?o.message:"Unknown error";throw new Error(`LM Studio error: ${a}`)}}var kh=`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
428
|
|
|
429
429
|
Respond with ONLY a valid JSON object (no markdown, no extra text) in one of these formats:
|
|
430
430
|
{"action": "mouse_move", "x": number, "y": number, "reasoning": "explanation"}
|
|
@@ -433,7 +433,7 @@ Respond with ONLY a valid JSON object (no markdown, no extra text) in one of the
|
|
|
433
433
|
{"action": "keyboard_input", "text": "text to type", "reasoning": "explanation"}
|
|
434
434
|
{"action": "DONE", "reasoning": "explanation of what was accomplished"}
|
|
435
435
|
|
|
436
|
-
x and y are screen coordinates in pixels from the top-left corner. Return DONE only when the instruction is fully completed.`;function
|
|
436
|
+
x and y are screen coordinates in pixels from the top-left corner. Return DONE only when the instruction is fully completed.`;function Fh(r){try{let e=r.trim().replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/i,""),t=JSON.parse(e);if(t&&typeof t.action=="string")return t}catch{let e=r.match(/\{[\s\S]*?\}/);if(e)try{let t=JSON.parse(e[0]);if(t&&typeof t.action=="string")return t}catch{}}return null}async function Ph(){return(await require("screenshot-desktop")({format:"png"})).toString("base64")}function Th(r){switch(r.action){case"mouse_move":return`Move mouse to (${r.x}, ${r.y})`;case"mouse_left_click":return`Left click at (${r.x}, ${r.y})`;case"mouse_right_click":return`Right click at (${r.x}, ${r.y})`;case"keyboard_input":return`Type: "${r.text}"`;case"DONE":return"DONE"}}async function Ah(r){if(r.action==="DONE")return;let{mouse:e,keyboard:t,Button:n,Point:i}=require("@nut-tree-fork/nut-js");r.action==="mouse_move"?await e.setPosition(new i(r.x,r.y)):r.action==="mouse_left_click"?(await e.setPosition(new i(r.x,r.y)),await e.click(n.LEFT)):r.action==="mouse_right_click"?(await e.setPosition(new i(r.x,r.y)),await e.click(n.RIGHT)):r.action==="keyboard_input"&&await t.type(r.text),await new Promise(o=>setTimeout(o,500))}var ul=Me(require("readline")),se=Me(require("fs")),It=Me(require("path"));function et(r,...e){for(let t of e){let n=r.indexOf(t);if(n!==-1&&r[n+1]&&!r[n+1].startsWith("-"))return r[n+1]}}function Ih(r,...e){return e.some(t=>r.includes(t))}function hw(r){let e=et(r,"-p","--platform")||process.env.ASKII_PLATFORM||"ollama",t=et(r,"--ollama-url")||process.env.ASKII_OLLAMA_URL||"http://localhost:11434",n=et(r,"--lmstudio-url")||process.env.ASKII_LMSTUDIO_URL||"ws://localhost:1234",i=et(r,"--ollama-model")||process.env.ASKII_OLLAMA_MODEL||"gemma3:270m",o=et(r,"--lmstudio-model")||process.env.ASKII_LMSTUDIO_MODEL||"qwen/qwen3-coder-30b";return{platform:e,url:e==="lmstudio"?n:t,model:e==="lmstudio"?o:i,mode:et(r,"--mode")||process.env.ASKII_MODE||"funny",maxRounds:parseInt(et(r,"--max-rounds")||process.env.ASKII_MAX_ROUNDS||"5"),yes:Ih(r,"-y","--yes")}}async function Vn(r,e,t,n){return r.platform==="lmstudio"?xh(e,r.url,r.model,t,n):Eh(e,r.url,r.model,t,n?[n]:void 0)}async function cl(){return process.stdin.isTTY?null:new Promise(r=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>e+=t),process.stdin.on("end",()=>r(e.trim()||null))})}async function Wn(r,e,t){return t?(console.error(`${e} (auto-confirmed)`),!0):new Promise(n=>{r.question(`${e} (y/N) `,i=>n(i.toLowerCase()==="y"))})}function Rh(){console.log(`ASKII CLI ( \u2022_\u2022)>\u2310\u25A0-\u25A0 (\u2310\u25A0_\u25A0)
|
|
437
437
|
AI code assistant for your terminal
|
|
438
438
|
|
|
439
439
|
Usage: askii <command> [options]
|
|
@@ -473,21 +473,25 @@ Examples:
|
|
|
473
473
|
askii -p lmstudio --lmstudio-model "my-model" do "refactor index.ts"
|
|
474
474
|
askii control --ollama-model llava "open Notepad and type hello world"
|
|
475
475
|
askii control --yes --ollama-model llava "click the search bar and search for cats"
|
|
476
|
-
`)}async function
|
|
476
|
+
`)}async function pw(){let r=process.argv.slice(2),e=r[0]||"help",t=r,n=r.filter(o=>!o.startsWith("-"));(Ih(t,"-h","--help")||e==="help")&&(Rh(),process.exit(0));let i=hw(t);if(e==="ask"){let o=await cl(),a=et(t,"-c","--code")||o,l=n.slice(1).join(" ");l||(console.error("Error: provide a question as an argument"),process.exit(1));let c=a?`Code:
|
|
477
477
|
\`\`\`
|
|
478
478
|
${a}
|
|
479
479
|
\`\`\`
|
|
480
480
|
|
|
481
481
|
Question: ${l}`:`Question: ${l}`;console.error(`ASKII is thinking... ${Xr()}`);try{let u=await Vn(i,c);console.log(`
|
|
482
482
|
ASKII Says: ${Kn()}
|
|
483
|
-
`),console.log(u)}catch(u){console.error(`Error: ${u instanceof Error?u.message:"Unknown error"}`),process.exit(1)}}else if(e==="edit"){let o=await
|
|
483
|
+
`),console.log(u)}catch(u){console.error(`Error: ${u instanceof Error?u.message:"Unknown error"}`),process.exit(1)}}else if(e==="edit"){let o=await cl(),a=et(t,"-c","--code")||o,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
484
|
\`\`\`
|
|
485
485
|
${a}
|
|
486
486
|
\`\`\`
|
|
487
487
|
|
|
488
488
|
Request: ${l}
|
|
489
489
|
|
|
490
|
-
Return only the updated code without explanation.`;console.error("ASKII is editing... (\u2022_\u2022)>\u2310\u25A0-\u25A0");try{let u=await Vn(i,c);console.log(
|
|
490
|
+
Return only the updated code without explanation.`;console.error("ASKII is editing... (\u2022_\u2022)>\u2310\u25A0-\u25A0");try{let u=await Vn(i,c);console.log(ml(u))}catch(u){console.error(`Error: ${u instanceof Error?u.message:"Unknown error"}`),process.exit(1)}}else if(e==="explain"){let o=await cl(),a=n.slice(1).join(" ")||o;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... ${Xr()}`);try{let h=await Vn(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 o=n.slice(1).join(" ");o||(console.error("Error: provide a task as an argument"),process.exit(1));let a=et(t,"--dir")||process.cwd();console.error(`ASKII is working... ${Xr()}`);let l=ul.createInterface({input:process.stdin,output:process.stderr});try{let c=hl(a);console.error(`
|
|
491
|
+
Workspace: ${a}
|
|
492
|
+
\`\`\`
|
|
493
|
+
${c}\`\`\`
|
|
494
|
+
`);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
495
|
|
|
492
496
|
Current workspace structure:
|
|
493
497
|
\`\`\`
|
|
@@ -495,25 +499,28 @@ ${c}
|
|
|
495
499
|
\`\`\`
|
|
496
500
|
|
|
497
501
|
You have access to the following action types:
|
|
498
|
-
- {"type": "view", "path": "path/to/file"} - View file contents
|
|
502
|
+
- {"type": "view", "path": "path/to/file"} - View file contents, results sent back to you
|
|
503
|
+
- {"type": "list", "path": "path/to/folder"} - List files in a folder, results sent back to you
|
|
499
504
|
- {"type": "create", "path": "path/to/file", "content": "file content"}
|
|
500
505
|
- {"type": "modify", "path": "path/to/file", "oldContent": "text to replace", "newContent": "replacement text"}
|
|
506
|
+
- {"type": "rename", "path": "old/path", "newPath": "new/path"} - Rename or move a file
|
|
501
507
|
- {"type": "delete", "path": "path/to/file"}
|
|
502
508
|
|
|
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=o;for(;h<i.maxRounds;){let p=h===0?`${f}
|
|
509
|
+
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=o;for(;h<i.maxRounds;){let p=h===0?`${f}
|
|
504
510
|
|
|
505
511
|
User request: ${d}`:`${f}
|
|
506
512
|
|
|
507
|
-
${d}`,m=await Vn(i,p),g=
|
|
513
|
+
${d}`,m=await Vn(i,p),g=pl(m);if(g.length===0)break;let b=g.filter(v=>v.type==="view"||v.type==="list"),y=g.filter(v=>v.type!=="view"&&v.type!=="list"),D={};for(let v of b){let S=It.join(a,v.path);try{if(v.type==="list"){console.error(` \u2192 Listing: ${v.path}`);let _=se.readdirSync(S).map(x=>{let E=se.statSync(It.join(S,x));return`${x} [${E.isDirectory()?"folder":"file"}]`});D[v.path]=_.join(`
|
|
514
|
+
`)}else console.error(` \u2192 Viewing: ${v.path}`),D[v.path]=se.readFileSync(S,"utf-8")}catch{D[v.path]="Error: Cannot read path"}}for(let v of y){let S=It.join(a,v.path);if(v.type==="create"){if(await Wn(l,`Create file: ${v.path}?`,i.yes)){let x=It.dirname(S);se.existsSync(x)||se.mkdirSync(x,{recursive:!0});let E=v.content?Gn(v.content):"";se.writeFileSync(S,E),u++,console.error(` \u2713 Created: ${v.path}`)}}else if(v.type==="modify"){if(await Wn(l,`Modify file: ${v.path}?`,i.yes))try{let x=se.readFileSync(S,"utf-8"),E=v.oldContent?Gn(v.oldContent):"",z=v.newContent?Gn(v.newContent):"";se.writeFileSync(S,x.replace(E,z)),u++,console.error(` \u2713 Modified: ${v.path}`)}catch{console.error(` \u2717 Cannot modify: ${v.path}`)}}else if(v.type==="delete"){if(await Wn(l,`Delete file: ${v.path}? This cannot be undone.`,i.yes))try{se.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 _=It.join(a,v.newPath);if(await Wn(l,`Rename: ${v.path} \u2192 ${v.newPath}?`,i.yes))try{let E=It.dirname(_);se.existsSync(E)||se.mkdirSync(E,{recursive:!0}),se.renameSync(S,_),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
515
|
${JSON.stringify(D,null,2)}
|
|
509
516
|
|
|
510
|
-
|
|
511
|
-
Completed ${u} actions! ${Kn()}`)}catch(c){l.close(),console.error(`Error: ${c instanceof Error?c.message:"Unknown error"}`),process.exit(1)}}else if(e==="control"){let o=n.slice(1).join(" ");o||(console.error("Error: provide an instruction as an argument"),process.exit(1));let a=
|
|
512
|
-
`);let l=0;for(;l<i.maxRounds;){console.error(`Round ${l+1}/${i.maxRounds} \u2014 taking screenshot...`);let c=await
|
|
517
|
+
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(`
|
|
518
|
+
Completed ${u} actions! ${Kn()}`)}catch(c){l.close(),console.error(`Error: ${c instanceof Error?c.message:"Unknown error"}`),process.exit(1)}}else if(e==="control"){let o=n.slice(1).join(" ");o||(console.error("Error: provide an instruction as an argument"),process.exit(1));let a=ul.createInterface({input:process.stdin,output:process.stderr});try{console.error(`ASKII Control starting... ${Xr()}`),console.error(`Instruction: ${o}`),console.error(`(Make sure your model supports vision/images)
|
|
519
|
+
`);let l=0;for(;l<i.maxRounds;){console.error(`Round ${l+1}/${i.maxRounds} \u2014 taking screenshot...`);let c=await Ph(),u=l===0?`Instruction to complete: ${o}
|
|
513
520
|
|
|
514
521
|
Analyze the screenshot and determine the next action.`:`Continuing instruction: ${o}
|
|
515
522
|
|
|
516
|
-
Analyze the updated screenshot and determine the next action, or return DONE if the instruction is complete.`;console.error("Asking AI...");let h=await Vn(i,u,
|
|
517
|
-
Done! ${Kn()}`),console.error(`Reasoning: ${f.reasoning}`);break}let d=
|
|
518
|
-
Action: ${d}`),console.error(`Reasoning: ${f.reasoning}`),!await
|
|
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}`),
|
|
523
|
+
Analyze the updated screenshot and determine the next action, or return DONE if the instruction is complete.`;console.error("Asking AI...");let h=await Vn(i,u,kh,c),f=Fh(h);if(!f){console.error("Error: could not parse action from AI response."),console.error(`Raw response: ${h}`);break}if(f.action==="DONE"){console.error(`
|
|
524
|
+
Done! ${Kn()}`),console.error(`Reasoning: ${f.reasoning}`);break}let d=Th(f);if(console.error(`
|
|
525
|
+
Action: ${d}`),console.error(`Reasoning: ${f.reasoning}`),!await Wn(a,"Execute this action?",i.yes)){console.error("Stopped.");break}await Ah(f),console.error(`Executed.
|
|
526
|
+
`),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}`),Rh(),process.exit(1)}pw();
|