blink 1.0.7 → 1.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/control/index.d.cts +16 -16
- package/dist/browser/control/index.d.ts +16 -16
- package/dist/cli/{dev-H15BYYde.js → dev-BokVEOmg.js} +34 -71
- package/dist/cli/index.js +2 -2
- package/dist/cli/{init-DQcckHBD.js → init-CYhWatkh.js} +47 -0
- package/dist/cli/{init-clXsaOLV.js → init-skH9BkRb.js} +1 -1
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/build/index.cjs +1 -1
- package/dist/node/build/index.js +1 -1
- package/dist/node/{build-lx6plR19.cjs → build-BzoNpizh.cjs} +4 -4
- package/dist/node/{build-M5Q2ZTGh.js → build-D_L0gFGa.js} +5 -5
- package/dist/node/{getMachineId-bsd-CUUgtcEk.cjs → getMachineId-bsd-B84ixt26.cjs} +1 -1
- package/dist/node/{getMachineId-bsd-YA-Qh955.cjs → getMachineId-bsd-BudRe7J9.cjs} +1 -1
- package/dist/node/{getMachineId-bsd-CpiyZ31n.js → getMachineId-bsd-BxqlJcyA.js} +1 -1
- package/dist/node/{getMachineId-bsd-DKc3Wh2z.js → getMachineId-bsd-C10eVJgT.js} +1 -1
- package/dist/node/{getMachineId-darwin-BBDIi9K5.js → getMachineId-darwin-Bf4P0U5b.js} +1 -1
- package/dist/node/{getMachineId-darwin-CcM48gLI.cjs → getMachineId-darwin-Cyng5kFG.cjs} +1 -1
- package/dist/node/{getMachineId-darwin-CQ9-5u-a.js → getMachineId-darwin-JB29MQsG.js} +1 -1
- package/dist/node/{getMachineId-darwin-IcDjLpqm.cjs → getMachineId-darwin-ZVi3EKE3.cjs} +1 -1
- package/dist/node/{getMachineId-linux-BzwdWZoB.cjs → getMachineId-linux-B-CtXK0L.cjs} +1 -1
- package/dist/node/{getMachineId-linux-Cc8c4coA.js → getMachineId-linux-BPnkHJah.js} +1 -1
- package/dist/node/{getMachineId-linux-DMvLmvRp.cjs → getMachineId-linux-CJXPQ8U5.cjs} +1 -1
- package/dist/node/{getMachineId-linux-TNXyQsBB.js → getMachineId-linux-CmMSYp7C.js} +1 -1
- package/dist/node/{getMachineId-unsupported-ApoW5rxx.cjs → getMachineId-unsupported--0R36RP6.cjs} +1 -1
- package/dist/node/{getMachineId-unsupported-CRrpolgF.js → getMachineId-unsupported-C_4fnT4Z.js} +1 -1
- package/dist/node/{getMachineId-unsupported-DYGwqELh.cjs → getMachineId-unsupported-DM7fz1pP.cjs} +1 -1
- package/dist/node/{getMachineId-unsupported-DGhOj3l0.js → getMachineId-unsupported-Dtt3HTNZ.js} +1 -1
- package/dist/node/{getMachineId-win-Dfq5UG8G.js → getMachineId-win-C4G-fkEF.js} +1 -1
- package/dist/node/{getMachineId-win-B-bRjIv0.cjs → getMachineId-win-CjJkZMZe.cjs} +1 -1
- package/dist/node/{getMachineId-win-CSKzOPIT.js → getMachineId-win-D1szVnqR.js} +1 -1
- package/dist/node/{getMachineId-win-CoAu5xDr.cjs → getMachineId-win-DDz2FyEp.cjs} +1 -1
- package/dist/node/{index.node-wsvVRWwb.js → index.node-BdbWMIX0.js} +4 -4
- package/dist/node/{index.node-DN4zHlM1.cjs → index.node-C6sId3jT.cjs} +4 -4
- package/dist/node/react/index.node.cjs +188 -131
- package/dist/node/react/index.node.js +144 -134
- package/dist/node/{token-C10csUbV.cjs → token-BBGr-czK.cjs} +1 -1
- package/dist/node/{token-B0ivJQut.js → token-DOfE6QlD.js} +1 -1
- package/dist/node/{token-util-BwRq8n40.cjs → token-util-BOoyY0PX.cjs} +1 -1
- package/dist/node/token-util-C_uzN2q9.js +1 -0
- package/dist/node/token-util-D9kCwzE6.cjs +1 -0
- package/dist/node/{token-util-1r_uDcp7.js → token-util-_pz5CtFI.js} +1 -1
- package/package.json +1 -1
- package/dist/node/token-util-CSWJ2yfA.js +0 -1
- package/dist/node/token-util-beB2LRJ9.cjs +0 -1
- /package/dist/node/{esm-C-vSI1Ww.cjs → esm-0UNjvroT.cjs} +0 -0
- /package/dist/node/{esm-D1GEQyaY.js → esm-CbZfjZBn.js} +0 -0
- /package/dist/node/{token-error-wsvzy87W.js → token-error-488npYdU.js} +0 -0
- /package/dist/node/{token-error-l6zIbPbZ.cjs → token-error-BoNG8ooW.cjs} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../
|
|
1
|
+
const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-C6sId3jT.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-BzoNpizh.cjs`);let r=require(`zod/v4`);r=e.__toESM(r),require(`zod/v3`);let i=require(`node:buffer`);i=e.__toESM(i);let a=require(`node:fs`);a=e.__toESM(a);let o=require(`node:url`);o=e.__toESM(o);let s=require(`node:stream`);s=e.__toESM(s);let c=require(`node:util`);c=e.__toESM(c);let l=require(`node:crypto`);l=e.__toESM(l);let u=require(`http`);u=e.__toESM(u);let d=require(`path`);d=e.__toESM(d);let f=require(`module`);f=e.__toESM(f);let p=require(`fs`);p=e.__toESM(p);let m=require(`node:process`);m=e.__toESM(m);let h=require(`ai`);h=e.__toESM(h);let g=require(`fs/promises`);g=e.__toESM(g);let _=require(`child_process`);_=e.__toESM(_);let v=require(`react`);v=e.__toESM(v);let y=require(`node:module`);y=e.__toESM(y);let b=require(`zod`);b=e.__toESM(b);let x=require(`node:readline`);x=e.__toESM(x);let S=require(`node:path`);S=e.__toESM(S);let C=require(`node:child_process`);C=e.__toESM(C);let w=require(`node:fs/promises`);w=e.__toESM(w);let T=require(`node:os`);T=e.__toESM(T);function E(e){let[n,r]=(0,v.useState)(void 0),[i,a]=(0,v.useState)([]),[o,s]=(0,v.useState)(void 0),[c,l]=(0,v.useState)(e.buildResult),[u,d]=(0,v.useState)(e.env),[f,p]=(0,v.useState)(e.apiServerUrl),[m,h]=(0,v.useState)(void 0);return(0,v.useEffect)(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),(0,v.useEffect)(()=>{if(!c||`error`in c){r(void 0),a([]),s(void 0),h(void 0);return}let e=new AbortController,n=!1;return s(void 0),r(void 0),h(void 0),(async()=>{let n=await D(),i=(0,_.spawn)(`node`,[`--no-deprecation`,c.entry],{stdio:`pipe`,env:{...process.env,...u,[t.APIServerURLEnvironmentVariable]:f,PORT:n.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{i.kill()}catch{}});let o=!1;i.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!o&&t.startsWith(`Agent server listening on`)||(o||console.log(`stdout: ${t}`),t.length&&a(e=>[...e,{level:`log`,message:t}]))}),i.stderr.on(`data`,e=>{o||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&a(e=>[...e,{level:`error`,message:t}])}),i.on(`error`,t=>{e.abort(t)}),i.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let s=new t.Client({baseUrl:`http://127.0.0.1:${n}`});for(;!e.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;o=!0;let l=await s.capabilities();h(l),r(s)})().catch(e=>{n||s(e instanceof Error?e:Error(String(e)))}),()=>{n=!0,e.abort()}},[c,u,f]),(0,v.useMemo)(()=>({agent:n,logs:i,error:o,capabilities:m}),[n,i,o,m])}async function D(){let e=(0,u.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var O=Object.getOwnPropertyNames,k=(e,t)=>function(){return t||(0,e[O(e)[0]])((t={exports:{}}).exports,t),t.exports},A=(0,y.createRequire)(require(`url`).pathToFileURL(__filename).href);b.z.object({email:b.z.string().email(),password:b.z.string().min(8)}),b.z.object({email:b.z.string().email(),code:b.z.string()}),b.z.object({email:b.z.string().email(),password:b.z.string().min(8)});var j=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},M=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function N(e){}function P(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=N,onError:n=N,onRetry:r=N,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=F(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
2
2
|
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new M(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new M(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
3
3
|
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function F(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
4
4
|
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
@@ -22,7 +22,7 @@ Error message: ${V(t)}`,cause:t}),this[le]=!0,this.value=e}static isInstance(e){
|
|
|
22
22
|
`));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
|
|
23
23
|
`);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})}),Ht=a.__commonJS({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=Bt(),a=Ft(),o=It(),s=Vt(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})}),Ut=a.__commonJS({"../../node_modules/tar-stream/constants.js":((e,t)=>{let n={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=A(`fs`).constants||n}catch{t.exports=n}})}),Wt=a.__commonJS({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=Bt(),a=It(),o=Ut(),s=Vt(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})}),Gt=a.__commonJS({"../../node_modules/tar-stream/index.js":(e=>{e.extract=Ht(),e.pack=Wt()})}),Kt=a.__toESM(Gt(),1);let qt=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await o.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=Kt.pack(),i=async(e,t=``)=>{let n=await o.readdir(e,{withFileTypes:!0});for(let a of n){let n=`${e}/${a.name}`,s=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){r.entry({name:`${s}/`,type:`directory`}),await i(n,s);continue}if(a.isSymbolicLink?.()){let e=await o.readlink(n);r.entry({name:s,type:`symlink`,linkname:e});continue}if(a.isFile()){let e=await o.stat(n);await new Promise((t,i)=>{let a=(0,u.createReadStream)(n),o=r.entry({name:s,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&i(e)});a.on(`error`,i),a.on(`data`,e=>o.write(e)),a.on(`end`,()=>{o.end(),t()})});continue}}};(async()=>{try{await i(e),r.finalize()}catch(e){r.destroy(e)}})();let a=r,s=0,c=!1;return new ReadableStream({start(e){a.on(`data`,t=>{if(!c){if(s+=t.length,s>n){c=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${s} bytes.`));try{a.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),a.once(`error`,t=>{c||(c=!0,e.error(t instanceof Error?t:Error(String(t))))}),a.once(`end`,()=>{c||(c=!0,e.close())})},cancel(){try{a.destroy()}catch{}}})},Jt=(e,t)=>e.length<=t?e:e.slice(e.length-t),Yt=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var Xt=class{constructor(e){this.decoder=new TextDecoder,this.encoder=new TextEncoder,this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new v({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new vt({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=h.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case a.ClientMessageType.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case a.ClientMessageType.PROXY_INIT:{let t=a.ClientMessageSchema[a.ClientMessageType.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new Nt.default(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped(a.ServerMessageType.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(a.ServerMessageType.PROXY_WEBSOCKET_MESSAGE,a.createWebSocketMessagePayload(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(a.ServerMessageType.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case a.ClientMessageType.PROXY_WEBSOCKET_MESSAGE:{let e=a.parseWebSocketMessagePayload(n,this.decoder);r.send(e);break}case a.ClientMessageType.PROXY_WEBSOCKET_CLOSE:{let e=a.ClientMessageSchema[a.ClientMessageType.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case a.ClientMessageType.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r},o;o=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let s={};o.headers.forEach((e,t)=>{s[t]=e});let c={headers:s,status_code:o.status,status_message:o.statusText};e.writeTyped(a.ServerMessageType.PROXY_INIT,this.encoder.encode(JSON.stringify(c)));let l=o.headers.get(`content-length`),u=l?parseInt(l):0,d=h.getMaxPayloadSize()-1;if(u>=d){if(!o.body){e.close();return}let t=o.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(d,r.length-t),i=r.subarray(t,t+n);e.writeTyped(a.ServerMessageType.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else o.body&&await o.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(a.ServerMessageType.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=a.RequestSchema[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{let n=this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=Yt(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await qt(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await c.readFile(t.payload.path),r=await ut(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
|
|
24
24
|
`),a=(t.payload.line_start??1)-1,o=t.payload.line_end??i.length,s=i.slice(a,o);this.sendResponse(e,{id:t.id,payload:{content:s.join(`
|
|
25
|
-
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await c.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await c.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await c.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await c.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(a.ServerMessageType.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([a.ServerMessageType.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=Jt(this.processManager.readANSIOutput(i.pid),64e3),f=Yt(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};Object.defineProperty(e,`Multiplexer`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`Server`,{enumerable:!0,get:function(){return Xt}})})}),cn=k({"node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{on(),e.Server=sn().Server})}),ln=class{constructor(e){this.client=e}listen(e){let t,n,r=!1,i=1e4,a=250,o=()=>{n&&=(clearTimeout(n),void 0)},s=()=>{if(r)return;o();let e=a*.2*Math.random(),t=Math.min(i,Math.floor(a+e));n=setTimeout(()=>{f()},t),a=Math.min(i,Math.floor(a*1.5))},c=()=>{a=250},{Server:l}=cn(),u=new l({send:e=>{let n=t;!n||n.readyState!==WebSocket.OPEN||n.send(e)},fetchProxyRequest(t,n){return e.onRequest(new Request(t,{...n,duplex:n.body?`half`:void 0}))}}),d=t=>{t.binaryType=`arraybuffer`,t.addEventListener(`open`,()=>{r||(c(),e.onConnect?.())}),t.addEventListener(`close`,()=>{r||(e.onDisconnect?.(),s())}),t.addEventListener(`error`,n=>{try{e.onError?.(n)}catch{}try{t.close()}catch{}}),t.addEventListener(`message`,e=>{if(typeof e.data==`string`){console.warn(`Message skipped because it is not a buffer.`);return}try{u.handleMessage(new Uint8Array(e.data))}catch(e){console.error(`message handler error`,e);try{t.close(1011)}catch{}}})},f=()=>{if(!r)try{let n=this.client.websocket(`/api/devhook/${e.id}`);t=n,d(n)}catch(t){try{e.onError?.(t)}catch{}s()}};return f(),{dispose:()=>{if(r)return;r=!0,o();let e=t;t=void 0;try{e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3)}catch{}}}}};let un=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),dn=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({});un.REQUEST,b.z.string(),un.PROXY_INIT,b.z.object({method:b.z.string(),headers:b.z.record(b.z.string(),b.z.string()),url:b.z.string()}),un.PROXY_BODY,b.z.instanceof(Uint8Array),un.PROXY_WEBSOCKET_MESSAGE,b.z.object({type:b.z.enum([`text`,`binary`]),data:b.z.instanceof(Uint8Array)}),un.PROXY_WEBSOCKET_CLOSE,b.z.object({code:b.z.number().optional(),reason:b.z.string().optional()}),dn.RESPONSE,b.z.string(),dn.NOTIFICATION,b.z.string(),dn.PROXY_INIT,b.z.object({status_code:b.z.number(),status_message:b.z.string(),headers:b.z.record(b.z.string(),b.z.string())}),dn.PROXY_DATA,b.z.instanceof(Uint8Array),dn.PROXY_WEBSOCKET_MESSAGE,b.z.instanceof(Uint8Array),dn.PROXY_WEBSOCKET_CLOSE,b.z.object({code:b.z.number(),reason:b.z.string()}),un.PROXY_INIT,b.z.string(),b.z.record(b.z.string(),b.z.string()),b.z.string(),b.z.object({command:b.z.string(),args:b.z.array(b.z.string()),env:b.z.record(b.z.string(),b.z.string()).optional(),cwd:b.z.string().optional()}),b.z.object({pid:b.z.number(),data:b.z.string()}),b.z.object({pid:b.z.number(),output_idle_timeout_ms:b.z.number().optional(),timeout_ms:b.z.number().optional()}),b.z.object({include_dead:b.z.boolean().optional()}),b.z.object({pid:b.z.number(),start_line:b.z.number().optional(),end_line:b.z.number().optional()}),b.z.object({pid:b.z.number(),signal:b.z.string().optional()}),b.z.object({env:b.z.record(b.z.string(),b.z.string())}),b.z.object({path:b.z.string(),line_start:b.z.number().optional(),line_end:b.z.number().optional()}),b.z.object({path:b.z.string(),content:b.z.string(),base64:b.z.boolean().optional(),mode:b.z.number().optional()}),b.z.object({path:b.z.string()}),b.z.object({path:b.z.string()}),b.z.object({path:b.z.string()});const fn=b.z.object({pid:b.z.number(),command:b.z.string(),args:b.z.array(b.z.string()),title:b.z.string().optional(),cwd:b.z.string(),env:b.z.record(b.z.string(),b.z.string()),exit_code:b.z.number().optional(),exit_signal:b.z.number().optional(),duration_ms:b.z.number().optional(),output_total_lines:b.z.number()});fn.extend({ansi_output:b.z.string(),plain_output:b.z.object({lines:b.z.array(b.z.string()),total_lines:b.z.number()})}),b.z.object({pid:b.z.number()}),b.z.object({}),b.z.object({processes:b.z.array(fn)}),b.z.object({lines:b.z.array(b.z.string()),total_lines:b.z.number(),duration_ms:b.z.number(),exit_code:b.z.number().optional(),exit_signal:b.z.number().optional()}),b.z.object({}),b.z.object({}),b.z.object({total_lines:b.z.number(),lines_read:b.z.number(),start_line:b.z.number(),content:b.z.string(),mime_type:b.z.string()}),b.z.object({}),b.z.object({entries:b.z.array(b.z.object({name:b.z.string(),type:b.z.enum([`file`,`directory`,`symlink`])}))}),b.z.object({}),b.z.object({deployment_id:b.z.string()});const pn=b.z.object({type:b.z.enum([`create`,`update`,`delete`]),path:b.z.string()}),mn=b.z.object({type:b.z.enum([`context`,`added`,`deleted`]),content:b.z.string(),oldLineNumber:b.z.number().optional(),newLineNumber:b.z.number().optional()}),hn=b.z.object({oldStart:b.z.number(),oldLines:b.z.number(),newStart:b.z.number(),newLines:b.z.number(),lines:b.z.array(mn)}),gn=b.z.object({path:b.z.string(),status:b.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:b.z.string().optional(),insertions:b.z.number(),deletions:b.z.number(),chunks:b.z.array(hn)}),_n=b.z.object({totalFiles:b.z.number(),totalInsertions:b.z.number(),totalDeletions:b.z.number(),netChange:b.z.number(),startHash:b.z.string().optional(),currentHash:b.z.string().optional(),timespan:b.z.number(),files:b.z.array(gn)}),vn=b.z.object({path:b.z.string(),status:b.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:b.z.boolean()}),yn=b.z.object({hash:b.z.string(),shortHash:b.z.string(),message:b.z.string(),author:b.z.string(),email:b.z.string(),date:b.z.date(),timestamp:b.z.date(),filesChanged:b.z.number(),insertions:b.z.number(),deletions:b.z.number(),commitDiff:b.z.array(gn).optional()});b.z.object({files:b.z.array(vn),branch:b.z.string(),ahead:b.z.number(),behind:b.z.number(),timestamp:b.z.date(),sessionDiff:_n.optional(),workingDirectoryDiff:_n.optional(),newCommits:b.z.array(yn),currentCommit:b.z.object({hash:b.z.string(),shortHash:b.z.string(),message:b.z.string(),author:b.z.string(),date:b.z.date()}).optional(),diffSkipped:b.z.boolean().optional(),payloadTruncated:b.z.boolean().optional(),estimatedSizeKB:b.z.number().optional()}),b.z.object({debounceDelay:b.z.number().optional(),gitStatusInterval:b.z.number().optional(),ignoreDotfiles:b.z.boolean().optional(),ignored:b.z.array(b.z.string()).optional(),watchGit:b.z.boolean().optional(),includeDiffs:b.z.boolean().optional(),maxDiffFiles:b.z.number().optional(),maxPayloadSizeKB:b.z.number().optional(),truncateLargeDiffs:b.z.boolean().optional()}),b.z.object({status:fn}),b.z.object({pid:b.z.number(),output:b.z.string()}),b.z.object({changes:b.z.array(pn)});var bn=class{constructor({send:e,jwt:t,requestTimeoutMS:n}){this.notificationCallbacks=new Map,this.disposables=[],this.requestHandlers=new Map,this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}};b.z.object({}),b.z.object({id:b.z.string(),token:b.z.string()});var xn=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await J(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new bn({send:e=>t.send(e)})}},Sn=class{constructor(e){this.client=e,this.compute=new xn(this.client)}},Cn=class extends an{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new ln(this),this.tools=new Sn(this)}},wn=e.__commonJSMin((e=>{e.__esModule=!0;function t(e){return i(e)===`boolean`}function n(e){return i(e)===`object`}function r(e){return i(e)===`string`}function i(e){return typeof e}function a(e){var i=e.meta,a=e.path,o=e.xdg;return{XDGAppPaths:new(function(){function e(s){s===void 0&&(s={});function c(t){return t===void 0&&(t={}),new e(t)}var l=n(s)?s:{name:s},u=l.suffix??``,d=l.isolated??!0,f=[l.name,i.pkgMainFilename(),i.mainFilename()],p=a.parse((f.find(function(e){return r(e)})??`$eval`)+u).name;c.$name=function(){return p},c.$isolated=function(){return d};function m(e){return e??={isolated:d},t(e)?e:e.isolated??d}function h(e){return m(e)?p:``}return c.cache=function(e){return a.join(o.cache(),h(e))},c.config=function(e){return a.join(o.config(),h(e))},c.data=function(e){return a.join(o.data(),h(e))},c.runtime=function(e){return o.runtime()?a.join(o.runtime(),h(e)):void 0},c.state=function(e){return a.join(o.state(),h(e))},c.configDirs=function(e){return o.configDirs().map(function(t){return a.join(t,h(e))})},c.dataDirs=function(e){return o.dataDirs().map(function(t){return a.join(t,h(e))})},c}return e}())}}e.Adapt=a})),Tn=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){var n=e.env,r=e.osPaths,i=e.path,a=/^darwin$/i.test(e.process.platform),o=/^win/i.test(e.process.platform);function s(){return r.home()||r.temp()}function c(e,t){return e||i.join.apply(i,t)}var l=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`.local`,`share`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`.local`,`state`])}}},u=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`Library`,`Caches`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`Library`,`Preferences`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`Library`,`Application Support`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`Library`,`State`])}}},d=function(){function e(){return c(n.get(`APPDATA`),[s(),`AppData`,`Roaming`])}function t(){return c(n.get(`LOCALAPPDATA`),[s(),`AppData`,`Local`])}return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[t(),`xdg.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[e(),`xdg.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[e(),`xdg.data`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[t(),`xdg.state`])}}};return{XDG:new(function(){function e(){function r(){return new e}var s=a?u():o?d():l();return r.cache=s.cache,r.config=s.config,r.data=s.data,r.runtime=s.runtime,r.state=s.state,r.configDirs=function(){var e=n.get(`XDG_CONFIG_DIRS`);return t([s.config()],e?e.split(i.delimiter):[])},r.dataDirs=function(){var e=n.get(`XDG_DATA_DIRS`);return t([s.data()],e?e.split(i.delimiter):[])},r}return e}())}}e.Adapt=n})),En=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){return!e}function r(e){var r=e.env,i=e.os,a=e.path,o=/^win/i.test(e.process.platform);function s(t){return t?e.path.normalize(e.path.join(t,`.`)):void 0}function c(){return o?function(){var e=[typeof i.homedir==`function`?i.homedir():void 0,r.get(`USERPROFILE`),r.get(`HOME`),r.get(`HOMEDRIVE`)||r.get(`HOMEPATH`)?a.join(r.get(`HOMEDRIVE`)||``,r.get(`HOMEPATH`)||``):void 0];return s(e.find(function(e){return!n(e)}))}():function(){return s((typeof i.homedir==`function`?i.homedir():void 0)||r.get(`HOME`))}()}function l(){function e(e,n){return e?a.join.apply(a,t([e],n)):void 0}function l(){var e=`/tmp`,t=[typeof i.tmpdir==`function`?i.tmpdir():void 0,r.get(`TMPDIR`),r.get(`TEMP`),r.get(`TMP`)];return s(t.find(function(e){return!n(e)}))||e}function u(){var t=`C:\\Temp`,a=[typeof i.tmpdir==`function`?i.tmpdir:function(){},function(){return r.get(`TEMP`)},function(){return r.get(`TMP`)},function(){return e(r.get(`LOCALAPPDATA`),[`Temp`])},function(){return e(c(),[`AppData`,`Local`,`Temp`])},function(){return e(r.get(`ALLUSERSPROFILE`),[`Temp`])},function(){return e(r.get(`SystemRoot`),[`Temp`])},function(){return e(r.get(`windir`),[`Temp`])},function(){return e(r.get(`SystemDrive`),[`\\`,`Temp`])}].find(function(e){return e&&!n(e())});return a&&s(a())||t}return o?u():l()}return{OSPaths:new(function(){function e(){function t(){return new e}return t.home=c,t.temp=l,t}return e}())}}e.Adapt=r})),Dn=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};e.__esModule=!0;var i=r(require(`os`)),a=r(require(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:i,path:a,process}})),On=e.__commonJSMin(((e,t)=>{var n=En(),r=Dn();t.exports=n.Adapt(r.adapter).OSPaths})),kn=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},i=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var a=r(require(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:i(On()).default,path:a,process}})),An=e.__commonJSMin(((e,t)=>{var n=Tn(),r=kn();t.exports=n.Adapt(r.adapter).XDG})),jn=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},i=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var a=r(require(`path`)),o=i(An());e.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=(typeof require<`u`&&require!==null&&require.main?require.main:{filename:void 0}).filename;return(e===process.execArgv[0]?void 0:e)||(process._eval===void 0?process.argv[1]:void 0)},pkgMainFilename:function(){return process.pkg?process.execPath:void 0}},path:a,process,xdg:o.default}})),Mn=e.__commonJSMin(((e,t)=>{var n=wn(),r=jn();t.exports=n.Adapt(r.adapter).XDGAppPaths})),Nn=e.__toESM(Mn(),1),Pn=Nn.default,Fn=e.__commonJSMin(((e,t)=>{t.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]}})),In=e.__commonJSMin(((e,t)=>{let n=Fn(),r={};for(let e of Object.keys(n))r[n[e]]=e;let i={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`]}};t.exports=i;for(let e of Object.keys(i)){if(!(`channels`in i[e]))throw Error(`missing channels property: `+e);if(!(`labels`in i[e]))throw Error(`missing channel labels property: `+e);if(i[e].labels.length!==i[e].channels)throw Error(`channel and label counts mismatch: `+e);let{channels:t,labels:n}=i[e];delete i[e].channels,delete i[e].labels,Object.defineProperty(i[e],`channels`,{value:t}),Object.defineProperty(i[e],`labels`,{value:n})}i.rgb.hsl=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s,c;a===i?s=0:t===a?s=(n-r)/o:n===a?s=2+(r-t)/o:r===a&&(s=4+(t-n)/o),s=Math.min(s*60,360),s<0&&(s+=360);let l=(i+a)/2;return c=a===i?0:l<=.5?o/(a+i):o/(2-a-i),[s,c*100,l*100]},i.rgb.hsv=function(e){let t,n,r,i,a,o=e[0]/255,s=e[1]/255,c=e[2]/255,l=Math.max(o,s,c),u=l-Math.min(o,s,c),d=function(e){return(l-e)/6/u+1/2};return u===0?(i=0,a=0):(a=u/l,t=d(o),n=d(s),r=d(c),o===l?i=r-n:s===l?i=1/3+t-r:c===l&&(i=2/3+n-t),i<0?i+=1:i>1&&--i),[i*360,a*100,l*100]},i.rgb.hwb=function(e){let t=e[0],n=e[1],r=e[2],a=i.rgb.hsl(e)[0],o=1/255*Math.min(t,Math.min(n,r));return r=1-1/255*Math.max(t,Math.max(n,r)),[a,o*100,r*100]},i.rgb.cmyk=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(1-t,1-n,1-r),a=(1-t-i)/(1-i)||0,o=(1-n-i)/(1-i)||0,s=(1-r-i)/(1-i)||0;return[a*100,o*100,s*100,i*100]};function a(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}i.rgb.keyword=function(e){let t=r[e];if(t)return t;let i=1/0,o;for(let t of Object.keys(n)){let r=n[t],s=a(e,r);s<i&&(i=s,o=t)}return o},i.keyword.rgb=function(e){return n[e]},i.rgb.xyz=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92;let i=t*.4124+n*.3576+r*.1805,a=t*.2126+n*.7152+r*.0722,o=t*.0193+n*.1192+r*.9505;return[i*100,a*100,o*100]},i.rgb.lab=function(e){let t=i.rgb.xyz(e),n=t[0],r=t[1],a=t[2];n/=95.047,r/=100,a/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,a=a>.008856?a**(1/3):7.787*a+16/116;let o=116*r-16,s=500*(n-r),c=200*(r-a);return[o,s,c]},i.hsl.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i,a,o;if(n===0)return o=r*255,[o,o,o];i=r<.5?r*(1+n):r+n-r*n;let s=2*r-i,c=[0,0,0];for(let e=0;e<3;e++)a=t+1/3*-(e-1),a<0&&a++,a>1&&a--,o=6*a<1?s+(i-s)*6*a:2*a<1?i:3*a<2?s+(i-s)*(2/3-a)*6:s,c[e]=o*255;return c},i.hsl.hsv=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=n,a=Math.max(r,.01);r*=2,n*=r<=1?r:2-r,i*=a<=1?a:2-a;let o=(r+n)/2,s=r===0?2*i/(a+i):2*n/(r+n);return[t,s*100,o*100]},i.hsv.rgb=function(e){let t=e[0]/60,n=e[1]/100,r=e[2]/100,i=Math.floor(t)%6,a=t-Math.floor(t),o=255*r*(1-n),s=255*r*(1-n*a),c=255*r*(1-n*(1-a));switch(r*=255,i){case 0:return[r,c,o];case 1:return[s,r,o];case 2:return[o,r,c];case 3:return[o,s,r];case 4:return[c,o,r];case 5:return[r,o,s]}},i.hsv.hsl=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=Math.max(r,.01),a,o;o=(2-n)*r;let s=(2-n)*i;return a=n*i,a/=s<=1?s:2-s,a||=0,o/=2,[t,a*100,o*100]},i.hwb.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i=n+r,a;i>1&&(n/=i,r/=i);let o=Math.floor(6*t),s=1-r;a=6*t-o,o&1&&(a=1-a);let c=n+a*(s-n),l,u,d;switch(o){default:case 6:case 0:l=s,u=c,d=n;break;case 1:l=c,u=s,d=n;break;case 2:l=n,u=s,d=c;break;case 3:l=n,u=c,d=s;break;case 4:l=c,u=n,d=s;break;case 5:l=s,u=n,d=c;break}return[l*255,u*255,d*255]},i.cmyk.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i=e[3]/100,a=1-Math.min(1,t*(1-i)+i),o=1-Math.min(1,n*(1-i)+i),s=1-Math.min(1,r*(1-i)+i);return[a*255,o*255,s*255]},i.xyz.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i,a,o;return i=t*3.2406+n*-1.5372+r*-.4986,a=t*-.9689+n*1.8758+r*.0415,o=t*.0557+n*-.204+r*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,i=Math.min(Math.max(0,i),1),a=Math.min(Math.max(0,a),1),o=Math.min(Math.max(0,o),1),[i*255,a*255,o*255]},i.xyz.lab=function(e){let t=e[0],n=e[1],r=e[2];t/=95.047,n/=100,r/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let i=116*n-16,a=500*(t-n),o=200*(n-r);return[i,a,o]},i.lab.xyz=function(e){let t=e[0],n=e[1],r=e[2],i,a,o;a=(t+16)/116,i=n/500+a,o=a-r/200;let s=a**3,c=i**3,l=o**3;return a=s>.008856?s:(a-16/116)/7.787,i=c>.008856?c:(i-16/116)/7.787,o=l>.008856?l:(o-16/116)/7.787,i*=95.047,a*=100,o*=108.883,[i,a,o]},i.lab.lch=function(e){let t=e[0],n=e[1],r=e[2],i;i=Math.atan2(r,n)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(n*n+r*r);return[t,a,i]},i.lch.lab=function(e){let t=e[0],n=e[1],r=e[2]/360*2*Math.PI,i=n*Math.cos(r),a=n*Math.sin(r);return[t,i,a]},i.rgb.ansi16=function(e,t=null){let[n,r,a]=e,o=t===null?i.rgb.hsv(e)[2]:t;if(o=Math.round(o/50),o===0)return 30;let s=30+(Math.round(a/255)<<2|Math.round(r/255)<<1|Math.round(n/255));return o===2&&(s+=60),s},i.hsv.ansi16=function(e){return i.rgb.ansi16(i.hsv.rgb(e),e[2])},i.rgb.ansi256=function(e){let t=e[0],n=e[1],r=e[2];return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},i.ansi16.rgb=function(e){let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let n=(~~(e>50)+1)*.5,r=(t&1)*n*255,i=(t>>1&1)*n*255,a=(t>>2&1)*n*255;return[r,i,a]},i.ansi256.rgb=function(e){if(e>=232){let t=(e-232)*10+8;return[t,t,t]}e-=16;let t,n=Math.floor(e/36)/5*255,r=Math.floor((t=e%36)/6)/5*255,i=t%6/5*255;return[n,r,i]},i.rgb.hex=function(e){let t=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return`000000`.substring(t.length)+t},i.hex.rgb=function(e){let t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let n=t[0];t[0].length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=parseInt(n,16),i=r>>16&255,a=r>>8&255,o=r&255;return[i,a,o]},i.rgb.hcg=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.max(Math.max(t,n),r),a=Math.min(Math.min(t,n),r),o=i-a,s,c;return s=o<1?a/(1-o):0,c=o<=0?0:i===t?(n-r)/o%6:i===n?2+(r-t)/o:4+(t-n)/o,c/=6,c%=1,[c*360,o*100,s*100]},i.hsl.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=n<.5?2*t*n:2*t*(1-n),i=0;return r<1&&(i=(n-.5*r)/(1-r)),[e[0],r*100,i*100]},i.hsv.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=t*n,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.hcg.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100;if(n===0)return[r*255,r*255,r*255];let i=[0,0,0],a=t%1*6,o=a%1,s=1-o,c=0;switch(Math.floor(a)){case 0:i[0]=1,i[1]=o,i[2]=0;break;case 1:i[0]=s,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=o;break;case 3:i[0]=0,i[1]=s,i[2]=1;break;case 4:i[0]=o,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=s}return c=(1-n)*r,[(n*i[0]+c)*255,(n*i[1]+c)*255,(n*i[2]+c)*255]},i.hcg.hsv=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t),i=0;return r>0&&(i=t/r),[e[0],i*100,r*100]},i.hcg.hsl=function(e){let t=e[1]/100,n=e[2]/100*(1-t)+.5*t,r=0;return n>0&&n<.5?r=t/(2*n):n>=.5&&n<1&&(r=t/(2*(1-n))),[e[0],r*100,n*100]},i.hcg.hwb=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t);return[e[0],(r-t)*100,(1-r)*100]},i.hwb.hcg=function(e){let t=e[1]/100,n=1-e[2]/100,r=n-t,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},i.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},i.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},i.gray.hsl=function(e){return[0,0,e[0]]},i.gray.hsv=i.gray.hsl,i.gray.hwb=function(e){return[0,100,e[0]]},i.gray.cmyk=function(e){return[0,0,0,e[0]]},i.gray.lab=function(e){return[e[0],0,0]},i.gray.hex=function(e){let t=Math.round(e[0]/100*255)&255,n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return`000000`.substring(n.length)+n},i.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}})),Ln=e.__commonJSMin(((e,t)=>{let n=In();function r(){let e={},t=Object.keys(n);for(let n=t.length,r=0;r<n;r++)e[t[r]]={distance:-1,parent:null};return e}function i(e){let t=r(),i=[e];for(t[e].distance=0;i.length;){let e=i.pop(),r=Object.keys(n[e]);for(let n=r.length,a=0;a<n;a++){let n=r[a],o=t[n];o.distance===-1&&(o.distance=t[e].distance+1,o.parent=e,i.unshift(n))}}return t}function a(e,t){return function(n){return t(e(n))}}function o(e,t){let r=[t[e].parent,e],i=n[t[e].parent][e],o=t[e].parent;for(;t[o].parent;)r.unshift(t[o].parent),i=a(n[t[o].parent][o],i),o=t[o].parent;return i.conversion=r,i}t.exports=function(e){let t=i(e),n={},r=Object.keys(t);for(let e=r.length,i=0;i<e;i++){let e=r[i];t[e].parent!==null&&(n[e]=o(e,t))}return n}})),Rn=e.__commonJSMin(((e,t)=>{let n=In(),r=Ln(),i={},a=Object.keys(n);function o(e){let t=function(...t){let n=t[0];return n==null?n:(n.length>1&&(t=n),e(t))};return`conversion`in e&&(t.conversion=e.conversion),t}function s(e){let t=function(...t){let n=t[0];if(n==null)return n;n.length>1&&(t=n);let r=e(t);if(typeof r==`object`)for(let e=r.length,t=0;t<e;t++)r[t]=Math.round(r[t]);return r};return`conversion`in e&&(t.conversion=e.conversion),t}a.forEach(e=>{i[e]={},Object.defineProperty(i[e],`channels`,{value:n[e].channels}),Object.defineProperty(i[e],`labels`,{value:n[e].labels});let t=r(e);Object.keys(t).forEach(n=>{let r=t[n];i[e][n]=s(r),i[e][n].raw=o(r)})}),t.exports=i})),zn=e.__commonJSMin(((e,t)=>{let n=(e,t)=>(...n)=>`\u001B[${e(...n)+t}m`,r=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};5;${r}m`},i=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};2;${r[0]};${r[1]};${r[2]}m`},a=e=>e,o=(e,t,n)=>[e,t,n],s=(e,t,n)=>{Object.defineProperty(e,t,{get:()=>{let r=n();return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0}),r},enumerable:!0,configurable:!0})},c,l=(e,t,n,r)=>{c===void 0&&(c=Rn());let i=r?10:0,a={};for(let[r,o]of Object.entries(c)){let s=r===`ansi16`?`ansi`:r;r===t?a[s]=e(n,i):typeof o==`object`&&(a[s]=e(o[t],i))}return a};function u(){let e=new Map,t={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]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[n,r]of Object.entries(t)){for(let[n,i]of Object.entries(r))t[n]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[n]=t[n],e.set(i[0],i[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,`codes`,{value:e,enumerable:!1}),t.color.close=`\x1B[39m`,t.bgColor.close=`\x1B[49m`,s(t.color,`ansi`,()=>l(n,`ansi16`,a,!1)),s(t.color,`ansi256`,()=>l(r,`ansi256`,a,!1)),s(t.color,`ansi16m`,()=>l(i,`rgb`,o,!1)),s(t.bgColor,`ansi`,()=>l(n,`ansi16`,a,!0)),s(t.bgColor,`ansi256`,()=>l(r,`ansi256`,a,!0)),s(t.bgColor,`ansi16m`,()=>l(i,`rgb`,o,!0)),t}Object.defineProperty(t,`exports`,{enumerable:!0,get:u})})),Bn=e.__commonJSMin(((e,t)=>{let r=require(`os`),i=require(`tty`),a=n.require_has_flag(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:n;if(`TEAMCITY_VERSION`in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:n}function u(e){let t=l(e,e&&e.isTTY);return c(t)}t.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),Vn=e.__commonJSMin(((e,t)=>{t.exports={stringReplaceAll:(e,t,n)=>{let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.substr(a,r-a)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.substr(a),o},stringEncaseCRLFWithFirstIndex:(e,t,n,r)=>{let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.substr(i,(o?r-1:r)-i)+t+(o?`\r
|
|
25
|
+
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await c.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await c.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await c.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await c.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(a.ServerMessageType.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([a.ServerMessageType.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=Jt(this.processManager.readANSIOutput(i.pid),64e3),f=Yt(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};Object.defineProperty(e,`Multiplexer`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`Server`,{enumerable:!0,get:function(){return Xt}})})}),cn=k({"node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{on(),e.Server=sn().Server})}),ln=class{constructor(e){this.client=e}listen(e){let t,n,r=!1,i=1e4,a=250,o=()=>{n&&=(clearTimeout(n),void 0)},s=()=>{if(r)return;o();let e=a*.2*Math.random(),t=Math.min(i,Math.floor(a+e));n=setTimeout(()=>{f()},t),a=Math.min(i,Math.floor(a*1.5))},c=()=>{a=250},{Server:l}=cn(),u=new l({send:e=>{let n=t;!n||n.readyState!==WebSocket.OPEN||n.send(e)},fetchProxyRequest(t,n){return e.onRequest(new Request(t,{...n,duplex:n.body?`half`:void 0}))}}),d=t=>{t.binaryType=`arraybuffer`,t.addEventListener(`open`,()=>{r||(c(),e.onConnect?.())}),t.addEventListener(`close`,()=>{r||(e.onDisconnect?.(),s())}),t.addEventListener(`error`,n=>{try{e.onError?.(n)}catch{}try{t.close()}catch{}}),t.addEventListener(`message`,e=>{if(typeof e.data==`string`){console.warn(`Message skipped because it is not a buffer.`);return}try{u.handleMessage(new Uint8Array(e.data))}catch(e){console.error(`message handler error`,e);try{t.close(1011)}catch{}}})},f=()=>{if(!r)try{let n=this.client.websocket(`/api/devhook/${e.id}`);t=n,d(n)}catch(t){try{e.onError?.(t)}catch{}s()}};return f(),{dispose:()=>{if(r)return;r=!0,o();let e=t;t=void 0;try{e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3)}catch{}}}}};let un=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),dn=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({});un.REQUEST,b.z.string(),un.PROXY_INIT,b.z.object({method:b.z.string(),headers:b.z.record(b.z.string(),b.z.string()),url:b.z.string()}),un.PROXY_BODY,b.z.instanceof(Uint8Array),un.PROXY_WEBSOCKET_MESSAGE,b.z.object({type:b.z.enum([`text`,`binary`]),data:b.z.instanceof(Uint8Array)}),un.PROXY_WEBSOCKET_CLOSE,b.z.object({code:b.z.number().optional(),reason:b.z.string().optional()}),dn.RESPONSE,b.z.string(),dn.NOTIFICATION,b.z.string(),dn.PROXY_INIT,b.z.object({status_code:b.z.number(),status_message:b.z.string(),headers:b.z.record(b.z.string(),b.z.string())}),dn.PROXY_DATA,b.z.instanceof(Uint8Array),dn.PROXY_WEBSOCKET_MESSAGE,b.z.instanceof(Uint8Array),dn.PROXY_WEBSOCKET_CLOSE,b.z.object({code:b.z.number(),reason:b.z.string()}),un.PROXY_INIT,b.z.string(),b.z.record(b.z.string(),b.z.string()),b.z.string(),b.z.object({command:b.z.string(),args:b.z.array(b.z.string()),env:b.z.record(b.z.string(),b.z.string()).optional(),cwd:b.z.string().optional()}),b.z.object({pid:b.z.number(),data:b.z.string()}),b.z.object({pid:b.z.number(),output_idle_timeout_ms:b.z.number().optional(),timeout_ms:b.z.number().optional()}),b.z.object({include_dead:b.z.boolean().optional()}),b.z.object({pid:b.z.number(),start_line:b.z.number().optional(),end_line:b.z.number().optional()}),b.z.object({pid:b.z.number(),signal:b.z.string().optional()}),b.z.object({env:b.z.record(b.z.string(),b.z.string())}),b.z.object({path:b.z.string(),line_start:b.z.number().optional(),line_end:b.z.number().optional()}),b.z.object({path:b.z.string(),content:b.z.string(),base64:b.z.boolean().optional(),mode:b.z.number().optional()}),b.z.object({path:b.z.string()}),b.z.object({path:b.z.string()}),b.z.object({path:b.z.string()});const fn=b.z.object({pid:b.z.number(),command:b.z.string(),args:b.z.array(b.z.string()),title:b.z.string().optional(),cwd:b.z.string(),env:b.z.record(b.z.string(),b.z.string()),exit_code:b.z.number().optional(),exit_signal:b.z.number().optional(),duration_ms:b.z.number().optional(),output_total_lines:b.z.number()});fn.extend({ansi_output:b.z.string(),plain_output:b.z.object({lines:b.z.array(b.z.string()),total_lines:b.z.number()})}),b.z.object({pid:b.z.number()}),b.z.object({}),b.z.object({processes:b.z.array(fn)}),b.z.object({lines:b.z.array(b.z.string()),total_lines:b.z.number(),duration_ms:b.z.number(),exit_code:b.z.number().optional(),exit_signal:b.z.number().optional()}),b.z.object({}),b.z.object({}),b.z.object({total_lines:b.z.number(),lines_read:b.z.number(),start_line:b.z.number(),content:b.z.string(),mime_type:b.z.string()}),b.z.object({}),b.z.object({entries:b.z.array(b.z.object({name:b.z.string(),type:b.z.enum([`file`,`directory`,`symlink`])}))}),b.z.object({}),b.z.object({deployment_id:b.z.string()});const pn=b.z.object({type:b.z.enum([`create`,`update`,`delete`]),path:b.z.string()}),mn=b.z.object({type:b.z.enum([`context`,`added`,`deleted`]),content:b.z.string(),oldLineNumber:b.z.number().optional(),newLineNumber:b.z.number().optional()}),hn=b.z.object({oldStart:b.z.number(),oldLines:b.z.number(),newStart:b.z.number(),newLines:b.z.number(),lines:b.z.array(mn)}),gn=b.z.object({path:b.z.string(),status:b.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:b.z.string().optional(),insertions:b.z.number(),deletions:b.z.number(),chunks:b.z.array(hn)}),_n=b.z.object({totalFiles:b.z.number(),totalInsertions:b.z.number(),totalDeletions:b.z.number(),netChange:b.z.number(),startHash:b.z.string().optional(),currentHash:b.z.string().optional(),timespan:b.z.number(),files:b.z.array(gn)}),vn=b.z.object({path:b.z.string(),status:b.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:b.z.boolean()}),yn=b.z.object({hash:b.z.string(),shortHash:b.z.string(),message:b.z.string(),author:b.z.string(),email:b.z.string(),date:b.z.date(),timestamp:b.z.date(),filesChanged:b.z.number(),insertions:b.z.number(),deletions:b.z.number(),commitDiff:b.z.array(gn).optional()});b.z.object({files:b.z.array(vn),branch:b.z.string(),ahead:b.z.number(),behind:b.z.number(),timestamp:b.z.date(),sessionDiff:_n.optional(),workingDirectoryDiff:_n.optional(),newCommits:b.z.array(yn),currentCommit:b.z.object({hash:b.z.string(),shortHash:b.z.string(),message:b.z.string(),author:b.z.string(),date:b.z.date()}).optional(),diffSkipped:b.z.boolean().optional(),payloadTruncated:b.z.boolean().optional(),estimatedSizeKB:b.z.number().optional()}),b.z.object({debounceDelay:b.z.number().optional(),gitStatusInterval:b.z.number().optional(),ignoreDotfiles:b.z.boolean().optional(),ignored:b.z.array(b.z.string()).optional(),watchGit:b.z.boolean().optional(),includeDiffs:b.z.boolean().optional(),maxDiffFiles:b.z.number().optional(),maxPayloadSizeKB:b.z.number().optional(),truncateLargeDiffs:b.z.boolean().optional()}),b.z.object({status:fn}),b.z.object({pid:b.z.number(),output:b.z.string()}),b.z.object({changes:b.z.array(pn)});var bn=class{constructor({send:e,jwt:t,requestTimeoutMS:n}){this.notificationCallbacks=new Map,this.disposables=[],this.requestHandlers=new Map,this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}};b.z.object({}),b.z.object({id:b.z.string(),token:b.z.string()});var xn=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await J(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new bn({send:e=>t.send(e)})}},Sn=class{constructor(e){this.client=e,this.compute=new xn(this.client)}},Cn=class extends an{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new ln(this),this.tools=new Sn(this)}},wn=e.__commonJSMin((e=>{e.__esModule=!0;function t(e){return i(e)===`boolean`}function n(e){return i(e)===`object`}function r(e){return i(e)===`string`}function i(e){return typeof e}function a(e){var i=e.meta,a=e.path,o=e.xdg;return{XDGAppPaths:new(function(){function e(s){s===void 0&&(s={});function c(t){return t===void 0&&(t={}),new e(t)}var l=n(s)?s:{name:s},u=l.suffix??``,d=l.isolated??!0,f=[l.name,i.pkgMainFilename(),i.mainFilename()],p=a.parse((f.find(function(e){return r(e)})??`$eval`)+u).name;c.$name=function(){return p},c.$isolated=function(){return d};function m(e){return e??={isolated:d},t(e)?e:e.isolated??d}function h(e){return m(e)?p:``}return c.cache=function(e){return a.join(o.cache(),h(e))},c.config=function(e){return a.join(o.config(),h(e))},c.data=function(e){return a.join(o.data(),h(e))},c.runtime=function(e){return o.runtime()?a.join(o.runtime(),h(e)):void 0},c.state=function(e){return a.join(o.state(),h(e))},c.configDirs=function(e){return o.configDirs().map(function(t){return a.join(t,h(e))})},c.dataDirs=function(e){return o.dataDirs().map(function(t){return a.join(t,h(e))})},c}return e}())}}e.Adapt=a})),Tn=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){var n=e.env,r=e.osPaths,i=e.path,a=/^darwin$/i.test(e.process.platform),o=/^win/i.test(e.process.platform);function s(){return r.home()||r.temp()}function c(e,t){return e||i.join.apply(i,t)}var l=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`.local`,`share`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`.local`,`state`])}}},u=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`Library`,`Caches`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`Library`,`Preferences`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`Library`,`Application Support`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`Library`,`State`])}}},d=function(){function e(){return c(n.get(`APPDATA`),[s(),`AppData`,`Roaming`])}function t(){return c(n.get(`LOCALAPPDATA`),[s(),`AppData`,`Local`])}return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[t(),`xdg.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[e(),`xdg.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[e(),`xdg.data`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[t(),`xdg.state`])}}};return{XDG:new(function(){function e(){function r(){return new e}var s=a?u():o?d():l();return r.cache=s.cache,r.config=s.config,r.data=s.data,r.runtime=s.runtime,r.state=s.state,r.configDirs=function(){var e=n.get(`XDG_CONFIG_DIRS`);return t([s.config()],e?e.split(i.delimiter):[])},r.dataDirs=function(){var e=n.get(`XDG_DATA_DIRS`);return t([s.data()],e?e.split(i.delimiter):[])},r}return e}())}}e.Adapt=n})),En=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){return!e}function r(e){var r=e.env,i=e.os,a=e.path,o=/^win/i.test(e.process.platform);function s(t){return t?e.path.normalize(e.path.join(t,`.`)):void 0}function c(){return o?function(){var e=[typeof i.homedir==`function`?i.homedir():void 0,r.get(`USERPROFILE`),r.get(`HOME`),r.get(`HOMEDRIVE`)||r.get(`HOMEPATH`)?a.join(r.get(`HOMEDRIVE`)||``,r.get(`HOMEPATH`)||``):void 0];return s(e.find(function(e){return!n(e)}))}():function(){return s((typeof i.homedir==`function`?i.homedir():void 0)||r.get(`HOME`))}()}function l(){function e(e,n){return e?a.join.apply(a,t([e],n)):void 0}function l(){var e=`/tmp`,t=[typeof i.tmpdir==`function`?i.tmpdir():void 0,r.get(`TMPDIR`),r.get(`TEMP`),r.get(`TMP`)];return s(t.find(function(e){return!n(e)}))||e}function u(){var t=`C:\\Temp`,a=[typeof i.tmpdir==`function`?i.tmpdir:function(){},function(){return r.get(`TEMP`)},function(){return r.get(`TMP`)},function(){return e(r.get(`LOCALAPPDATA`),[`Temp`])},function(){return e(c(),[`AppData`,`Local`,`Temp`])},function(){return e(r.get(`ALLUSERSPROFILE`),[`Temp`])},function(){return e(r.get(`SystemRoot`),[`Temp`])},function(){return e(r.get(`windir`),[`Temp`])},function(){return e(r.get(`SystemDrive`),[`\\`,`Temp`])}].find(function(e){return e&&!n(e())});return a&&s(a())||t}return o?u():l()}return{OSPaths:new(function(){function e(){function t(){return new e}return t.home=c,t.temp=l,t}return e}())}}e.Adapt=r})),Dn=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};e.__esModule=!0;var i=r(require(`os`)),a=r(require(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:i,path:a,process}})),On=e.__commonJSMin(((e,t)=>{var n=En(),r=Dn();t.exports=n.Adapt(r.adapter).OSPaths})),kn=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},i=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var a=r(require(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:i(On()).default,path:a,process}})),An=e.__commonJSMin(((e,t)=>{var n=Tn(),r=kn();t.exports=n.Adapt(r.adapter).XDG})),jn=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},i=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var a=r(require(`path`)),o=i(An());e.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=(typeof require<`u`&&require!==null&&require.main?require.main:{filename:void 0}).filename;return(e===process.execArgv[0]?void 0:e)||(process._eval===void 0?process.argv[1]:void 0)},pkgMainFilename:function(){return process.pkg?process.execPath:void 0}},path:a,process,xdg:o.default}})),Mn=e.__commonJSMin(((e,t)=>{var n=wn(),r=jn();t.exports=n.Adapt(r.adapter).XDGAppPaths})),Nn=e.__toESM(Mn(),1),Pn=Nn.default,Fn=e.__commonJSMin(((e,t)=>{t.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]}})),In=e.__commonJSMin(((e,t)=>{let n=Fn(),r={};for(let e of Object.keys(n))r[n[e]]=e;let i={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`]}};t.exports=i;for(let e of Object.keys(i)){if(!(`channels`in i[e]))throw Error(`missing channels property: `+e);if(!(`labels`in i[e]))throw Error(`missing channel labels property: `+e);if(i[e].labels.length!==i[e].channels)throw Error(`channel and label counts mismatch: `+e);let{channels:t,labels:n}=i[e];delete i[e].channels,delete i[e].labels,Object.defineProperty(i[e],`channels`,{value:t}),Object.defineProperty(i[e],`labels`,{value:n})}i.rgb.hsl=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s,c;a===i?s=0:t===a?s=(n-r)/o:n===a?s=2+(r-t)/o:r===a&&(s=4+(t-n)/o),s=Math.min(s*60,360),s<0&&(s+=360);let l=(i+a)/2;return c=a===i?0:l<=.5?o/(a+i):o/(2-a-i),[s,c*100,l*100]},i.rgb.hsv=function(e){let t,n,r,i,a,o=e[0]/255,s=e[1]/255,c=e[2]/255,l=Math.max(o,s,c),u=l-Math.min(o,s,c),d=function(e){return(l-e)/6/u+1/2};return u===0?(i=0,a=0):(a=u/l,t=d(o),n=d(s),r=d(c),o===l?i=r-n:s===l?i=1/3+t-r:c===l&&(i=2/3+n-t),i<0?i+=1:i>1&&--i),[i*360,a*100,l*100]},i.rgb.hwb=function(e){let t=e[0],n=e[1],r=e[2],a=i.rgb.hsl(e)[0],o=1/255*Math.min(t,Math.min(n,r));return r=1-1/255*Math.max(t,Math.max(n,r)),[a,o*100,r*100]},i.rgb.cmyk=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(1-t,1-n,1-r),a=(1-t-i)/(1-i)||0,o=(1-n-i)/(1-i)||0,s=(1-r-i)/(1-i)||0;return[a*100,o*100,s*100,i*100]};function a(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}i.rgb.keyword=function(e){let t=r[e];if(t)return t;let i=1/0,o;for(let t of Object.keys(n)){let r=n[t],s=a(e,r);s<i&&(i=s,o=t)}return o},i.keyword.rgb=function(e){return n[e]},i.rgb.xyz=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92;let i=t*.4124+n*.3576+r*.1805,a=t*.2126+n*.7152+r*.0722,o=t*.0193+n*.1192+r*.9505;return[i*100,a*100,o*100]},i.rgb.lab=function(e){let t=i.rgb.xyz(e),n=t[0],r=t[1],a=t[2];n/=95.047,r/=100,a/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,a=a>.008856?a**(1/3):7.787*a+16/116;let o=116*r-16,s=500*(n-r),c=200*(r-a);return[o,s,c]},i.hsl.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i,a,o;if(n===0)return o=r*255,[o,o,o];i=r<.5?r*(1+n):r+n-r*n;let s=2*r-i,c=[0,0,0];for(let e=0;e<3;e++)a=t+1/3*-(e-1),a<0&&a++,a>1&&a--,o=6*a<1?s+(i-s)*6*a:2*a<1?i:3*a<2?s+(i-s)*(2/3-a)*6:s,c[e]=o*255;return c},i.hsl.hsv=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=n,a=Math.max(r,.01);r*=2,n*=r<=1?r:2-r,i*=a<=1?a:2-a;let o=(r+n)/2,s=r===0?2*i/(a+i):2*n/(r+n);return[t,s*100,o*100]},i.hsv.rgb=function(e){let t=e[0]/60,n=e[1]/100,r=e[2]/100,i=Math.floor(t)%6,a=t-Math.floor(t),o=255*r*(1-n),s=255*r*(1-n*a),c=255*r*(1-n*(1-a));switch(r*=255,i){case 0:return[r,c,o];case 1:return[s,r,o];case 2:return[o,r,c];case 3:return[o,s,r];case 4:return[c,o,r];case 5:return[r,o,s]}},i.hsv.hsl=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=Math.max(r,.01),a,o;o=(2-n)*r;let s=(2-n)*i;return a=n*i,a/=s<=1?s:2-s,a||=0,o/=2,[t,a*100,o*100]},i.hwb.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i=n+r,a;i>1&&(n/=i,r/=i);let o=Math.floor(6*t),s=1-r;a=6*t-o,o&1&&(a=1-a);let c=n+a*(s-n),l,u,d;switch(o){default:case 6:case 0:l=s,u=c,d=n;break;case 1:l=c,u=s,d=n;break;case 2:l=n,u=s,d=c;break;case 3:l=n,u=c,d=s;break;case 4:l=c,u=n,d=s;break;case 5:l=s,u=n,d=c;break}return[l*255,u*255,d*255]},i.cmyk.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i=e[3]/100,a=1-Math.min(1,t*(1-i)+i),o=1-Math.min(1,n*(1-i)+i),s=1-Math.min(1,r*(1-i)+i);return[a*255,o*255,s*255]},i.xyz.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i,a,o;return i=t*3.2406+n*-1.5372+r*-.4986,a=t*-.9689+n*1.8758+r*.0415,o=t*.0557+n*-.204+r*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,i=Math.min(Math.max(0,i),1),a=Math.min(Math.max(0,a),1),o=Math.min(Math.max(0,o),1),[i*255,a*255,o*255]},i.xyz.lab=function(e){let t=e[0],n=e[1],r=e[2];t/=95.047,n/=100,r/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let i=116*n-16,a=500*(t-n),o=200*(n-r);return[i,a,o]},i.lab.xyz=function(e){let t=e[0],n=e[1],r=e[2],i,a,o;a=(t+16)/116,i=n/500+a,o=a-r/200;let s=a**3,c=i**3,l=o**3;return a=s>.008856?s:(a-16/116)/7.787,i=c>.008856?c:(i-16/116)/7.787,o=l>.008856?l:(o-16/116)/7.787,i*=95.047,a*=100,o*=108.883,[i,a,o]},i.lab.lch=function(e){let t=e[0],n=e[1],r=e[2],i;i=Math.atan2(r,n)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(n*n+r*r);return[t,a,i]},i.lch.lab=function(e){let t=e[0],n=e[1],r=e[2]/360*2*Math.PI,i=n*Math.cos(r),a=n*Math.sin(r);return[t,i,a]},i.rgb.ansi16=function(e,t=null){let[n,r,a]=e,o=t===null?i.rgb.hsv(e)[2]:t;if(o=Math.round(o/50),o===0)return 30;let s=30+(Math.round(a/255)<<2|Math.round(r/255)<<1|Math.round(n/255));return o===2&&(s+=60),s},i.hsv.ansi16=function(e){return i.rgb.ansi16(i.hsv.rgb(e),e[2])},i.rgb.ansi256=function(e){let t=e[0],n=e[1],r=e[2];return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},i.ansi16.rgb=function(e){let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let n=(~~(e>50)+1)*.5,r=(t&1)*n*255,i=(t>>1&1)*n*255,a=(t>>2&1)*n*255;return[r,i,a]},i.ansi256.rgb=function(e){if(e>=232){let t=(e-232)*10+8;return[t,t,t]}e-=16;let t,n=Math.floor(e/36)/5*255,r=Math.floor((t=e%36)/6)/5*255,i=t%6/5*255;return[n,r,i]},i.rgb.hex=function(e){let t=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return`000000`.substring(t.length)+t},i.hex.rgb=function(e){let t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let n=t[0];t[0].length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=parseInt(n,16),i=r>>16&255,a=r>>8&255,o=r&255;return[i,a,o]},i.rgb.hcg=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.max(Math.max(t,n),r),a=Math.min(Math.min(t,n),r),o=i-a,s,c;return s=o<1?a/(1-o):0,c=o<=0?0:i===t?(n-r)/o%6:i===n?2+(r-t)/o:4+(t-n)/o,c/=6,c%=1,[c*360,o*100,s*100]},i.hsl.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=n<.5?2*t*n:2*t*(1-n),i=0;return r<1&&(i=(n-.5*r)/(1-r)),[e[0],r*100,i*100]},i.hsv.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=t*n,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.hcg.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100;if(n===0)return[r*255,r*255,r*255];let i=[0,0,0],a=t%1*6,o=a%1,s=1-o,c=0;switch(Math.floor(a)){case 0:i[0]=1,i[1]=o,i[2]=0;break;case 1:i[0]=s,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=o;break;case 3:i[0]=0,i[1]=s,i[2]=1;break;case 4:i[0]=o,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=s}return c=(1-n)*r,[(n*i[0]+c)*255,(n*i[1]+c)*255,(n*i[2]+c)*255]},i.hcg.hsv=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t),i=0;return r>0&&(i=t/r),[e[0],i*100,r*100]},i.hcg.hsl=function(e){let t=e[1]/100,n=e[2]/100*(1-t)+.5*t,r=0;return n>0&&n<.5?r=t/(2*n):n>=.5&&n<1&&(r=t/(2*(1-n))),[e[0],r*100,n*100]},i.hcg.hwb=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t);return[e[0],(r-t)*100,(1-r)*100]},i.hwb.hcg=function(e){let t=e[1]/100,n=1-e[2]/100,r=n-t,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},i.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},i.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},i.gray.hsl=function(e){return[0,0,e[0]]},i.gray.hsv=i.gray.hsl,i.gray.hwb=function(e){return[0,100,e[0]]},i.gray.cmyk=function(e){return[0,0,0,e[0]]},i.gray.lab=function(e){return[e[0],0,0]},i.gray.hex=function(e){let t=Math.round(e[0]/100*255)&255,n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return`000000`.substring(n.length)+n},i.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}})),Ln=e.__commonJSMin(((e,t)=>{let n=In();function r(){let e={},t=Object.keys(n);for(let n=t.length,r=0;r<n;r++)e[t[r]]={distance:-1,parent:null};return e}function i(e){let t=r(),i=[e];for(t[e].distance=0;i.length;){let e=i.pop(),r=Object.keys(n[e]);for(let n=r.length,a=0;a<n;a++){let n=r[a],o=t[n];o.distance===-1&&(o.distance=t[e].distance+1,o.parent=e,i.unshift(n))}}return t}function a(e,t){return function(n){return t(e(n))}}function o(e,t){let r=[t[e].parent,e],i=n[t[e].parent][e],o=t[e].parent;for(;t[o].parent;)r.unshift(t[o].parent),i=a(n[t[o].parent][o],i),o=t[o].parent;return i.conversion=r,i}t.exports=function(e){let t=i(e),n={},r=Object.keys(t);for(let e=r.length,i=0;i<e;i++){let e=r[i];t[e].parent!==null&&(n[e]=o(e,t))}return n}})),Rn=e.__commonJSMin(((e,t)=>{let n=In(),r=Ln(),i={},a=Object.keys(n);function o(e){let t=function(...t){let n=t[0];return n==null?n:(n.length>1&&(t=n),e(t))};return`conversion`in e&&(t.conversion=e.conversion),t}function s(e){let t=function(...t){let n=t[0];if(n==null)return n;n.length>1&&(t=n);let r=e(t);if(typeof r==`object`)for(let e=r.length,t=0;t<e;t++)r[t]=Math.round(r[t]);return r};return`conversion`in e&&(t.conversion=e.conversion),t}a.forEach(e=>{i[e]={},Object.defineProperty(i[e],`channels`,{value:n[e].channels}),Object.defineProperty(i[e],`labels`,{value:n[e].labels});let t=r(e);Object.keys(t).forEach(n=>{let r=t[n];i[e][n]=s(r),i[e][n].raw=o(r)})}),t.exports=i})),zn=e.__commonJSMin(((e,t)=>{let n=(e,t)=>(...n)=>`\u001B[${e(...n)+t}m`,r=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};5;${r}m`},i=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};2;${r[0]};${r[1]};${r[2]}m`},a=e=>e,o=(e,t,n)=>[e,t,n],s=(e,t,n)=>{Object.defineProperty(e,t,{get:()=>{let r=n();return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0}),r},enumerable:!0,configurable:!0})},c,l=(e,t,n,r)=>{c===void 0&&(c=Rn());let i=r?10:0,a={};for(let[r,o]of Object.entries(c)){let s=r===`ansi16`?`ansi`:r;r===t?a[s]=e(n,i):typeof o==`object`&&(a[s]=e(o[t],i))}return a};function u(){let e=new Map,t={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]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[n,r]of Object.entries(t)){for(let[n,i]of Object.entries(r))t[n]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[n]=t[n],e.set(i[0],i[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,`codes`,{value:e,enumerable:!1}),t.color.close=`\x1B[39m`,t.bgColor.close=`\x1B[49m`,s(t.color,`ansi`,()=>l(n,`ansi16`,a,!1)),s(t.color,`ansi256`,()=>l(r,`ansi256`,a,!1)),s(t.color,`ansi16m`,()=>l(i,`rgb`,o,!1)),s(t.bgColor,`ansi`,()=>l(n,`ansi16`,a,!0)),s(t.bgColor,`ansi256`,()=>l(r,`ansi256`,a,!0)),s(t.bgColor,`ansi16m`,()=>l(i,`rgb`,o,!0)),t}Object.defineProperty(t,`exports`,{enumerable:!0,get:u})})),Bn=e.__commonJSMin(((e,n)=>{let r=require(`os`),i=require(`tty`),a=t.require_has_flag(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:n;if(`TEAMCITY_VERSION`in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:n}function u(e){let t=l(e,e&&e.isTTY);return c(t)}n.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),Vn=e.__commonJSMin(((e,t)=>{t.exports={stringReplaceAll:(e,t,n)=>{let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.substr(a,r-a)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.substr(a),o},stringEncaseCRLFWithFirstIndex:(e,t,n,r)=>{let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.substr(i,(o?r-1:r)-i)+t+(o?`\r
|
|
26
26
|
`:`
|
|
27
27
|
`)+n,i=r+1,r=e.indexOf(`
|
|
28
28
|
`,i)}while(r!==-1);return a+=e.substr(i),a}}})),Hn=e.__commonJSMin(((e,t)=>{let n=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,r=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,i=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,a=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,o=new Map([[`n`,`
|
|
@@ -35,12 +35,12 @@ Error message: ${V(t)}`,cause:t}),this[le]=!0,this.value=e}static isInstance(e){
|
|
|
35
35
|
`).map(e=>Er(e,t,n)).join(`
|
|
36
36
|
`)}const Or={actions:new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]])};function kr(e,t){if(typeof e==`string`)return Or.aliases.get(e)===t;for(let n of e)if(n!==void 0&&kr(n,t))return!0;return!1}function Ar(e,t){if(e===t)return;let n=e.split(`
|
|
37
37
|
`),r=t.split(`
|
|
38
|
-
`),i=[];for(let e=0;e<Math.max(n.length,r.length);e++)n[e]!==r[e]&&i.push(e);return i}const jr=globalThis.process.platform.startsWith(`win`),Mr=Symbol(`clack:cancel`);function Nr(e){return e===Mr}function Pr(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Fr({input:e=
|
|
38
|
+
`),i=[];for(let e=0;e<Math.max(n.length,r.length);e++)n[e]!==r[e]&&i.push(e);return i}const jr=globalThis.process.platform.startsWith(`win`),Mr=Symbol(`clack:cancel`);function Nr(e){return e===Mr}function Pr(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Fr({input:e=m.stdin,output:t=m.stdout,overwrite:n=!0,hideCursor:r=!0}={}){let i=x.createInterface({input:e,output:t,prompt:``,tabSize:1});x.emitKeypressEvents(e,i),e.isTTY&&e.setRawMode(!0);let a=(i,{name:o,sequence:s})=>{if(kr([String(i),o,s],`cancel`)){r&&t.write(qn.cursor.show),process.exit(0);return}if(!n)return;let c=o===`return`?0:-1,l=o===`return`?-1:0;x.moveCursor(t,c,l,()=>{x.clearLine(t,1,()=>{e.once(`keypress`,a)})})};return r&&t.write(qn.cursor.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(qn.cursor.show),e.isTTY&&!jr&&e.setRawMode(!1),i.terminal=!1,i.close()}}var Ir=Object.defineProperty,Lr=(e,t,n)=>t in e?Ir(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Rr=(e,t,n)=>(Lr(e,typeof t==`symbol`?t:t+``,n),n),zr=class{constructor(e,t=!0){Rr(this,`input`),Rr(this,`output`),Rr(this,`_abortSignal`),Rr(this,`rl`),Rr(this,`opts`),Rr(this,`_render`),Rr(this,`_track`,!1),Rr(this,`_prevFrame`,``),Rr(this,`_subscribers`,new Map),Rr(this,`_cursor`,0),Rr(this,`state`,`initial`),Rr(this,`error`,``),Rr(this,`value`);let{input:n=m.stdin,output:r=m.stdout,render:i,signal:a,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=a,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise((e,t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(Mr);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}let n=new s.Writable;n._write=(e,t,n)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,``),this._cursor=this.rl?.cursor??0,this.emit(`value`,this.value)),n()},this.input.pipe(n),this.rl=x.default.createInterface({input:this.input,output:n,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),x.default.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on(`keypress`,this.onKeypress),Pr(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(qn.cursor.show),this.output.off(`resize`,this.render),Pr(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(qn.cursor.show),this.output.off(`resize`,this.render),Pr(this.input,!1),e(Mr)})})}onKeypress(e,t){if(this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&Or.aliases.has(t.name)&&this.emit(`cursor`,Or.aliases.get(t.name)),Or.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),e===` `&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit(`value`,this.opts.placeholder))),e&&this.emit(`key`,e.toLowerCase()),t?.name===`return`){if(this.opts.validate){let e=this.opts.validate(this.value);e&&(this.error=e instanceof Error?e.message:e,this.state=`error`,this.rl?.write(this.value))}this.state!==`error`&&(this.state=`submit`)}kr([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
|
|
39
39
|
`),Pr(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Dr(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
|
|
40
40
|
`).length-1;this.output.write(qn.cursor.move(-999,e*-1))}render(){let e=Dr(this._render(this)??``,process.stdout.columns,{hard:!0});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(qn.cursor.hide);else{let t=Ar(this._prevFrame,e);if(this.restoreCursor(),t&&t?.length===1){let n=t[0];this.output.write(qn.cursor.move(0,n)),this.output.write(qn.erase.lines(1));let r=e.split(`
|
|
41
41
|
`);this.output.write(r[n]),this._prevFrame=e,this.output.write(qn.cursor.move(0,r.length-n-1));return}if(t&&t?.length>1){let n=t[0];this.output.write(qn.cursor.move(0,n)),this.output.write(qn.erase.down());let r=e.split(`
|
|
42
42
|
`).slice(n);this.output.write(r.join(`
|
|
43
|
-
`)),this._prevFrame=e;return}this.output.write(qn.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},Br=class extends zr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`value`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(qn.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},Vr=Object.defineProperty,Hr=(e,t,n)=>t in e?Vr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ur=(e,t,n)=>(Hr(e,typeof t==`symbol`?t:t+``,n),n),Wr=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},Gr=(e,t,n)=>(Wr(e,t,`read from private field`),n?n.call(e):t.get(e)),Kr=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},qr=(e,t,n,r)=>(Wr(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n),Jr;let Yr=class extends zr{constructor(e){super(e,!1),Ur(this,`options`),Ur(this,`cursor`,0),Kr(this,Jr,void 0);let{options:t}=e;qr(this,Jr,e.selectableGroups!==!1),this.options=Object.entries(t).flatMap(([e,t])=>[{value:e,group:!0,label:e},...t.map(t=>({...t,group:e}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),Gr(this,Jr)?0:1),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let e=this.options[this.cursor]?.group===!0;!Gr(this,Jr)&&e&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case`down`:case`right`:{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let e=this.options[this.cursor]?.group===!0;!Gr(this,Jr)&&e&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case`space`:this.toggleValue();break}})}getGroupItems(e){return this.options.filter(t=>t.group===e)}isGroupSelected(e){return this.getGroupItems(e).every(e=>this.value.includes(e.value))}toggleValue(){let e=this.options[this.cursor];if(e.group===!0){let t=e.value,n=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter(e=>n.findIndex(t=>t.value===e)===-1):this.value=[...this.value,...n.map(e=>e.value)],this.value=Array.from(new Set(this.value))}else this.value=this.value.includes(e.value)?this.value.filter(t=>t!==e.value):[...this.value,e.value]}};Jr=new WeakMap;var Xr=Object.defineProperty,Zr=(e,t,n)=>t in e?Xr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Qr=(e,t,n)=>(Zr(e,typeof t==`symbol`?t:t+``,n),n);let $r=class extends zr{constructor(e){super(e,!1),Qr(this,`options`),Qr(this,`cursor`,0),this.options=e.options,this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0),this.on(`key`,e=>{e===`a`&&this.toggleAll()}),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case`down`:case`right`:this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case`space`:this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){this.value=this.value.length===this.options.length?[]:this.options.map(e=>e.value)}toggleValue(){this.value=this.value.includes(this._value)?this.value.filter(e=>e!==this._value):[...this.value,this._value]}};var ei=Object.defineProperty,ti=(e,t,n)=>t in e?ei(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ni=(e,t,n)=>(ti(e,typeof t==`symbol`?t:t+``,n),n),ri=class extends zr{constructor({mask:e,...t}){super(t),ni(this,`valueWithCursor`,``),ni(this,`_mask`,`•`),this._mask=e??`•`,this.on(`finalize`,()=>{this.valueWithCursor=this.masked}),this.on(`value`,()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${Jn.default.inverse(Jn.default.hidden(`_`))}`;else{let e=this.masked.slice(0,this.cursor),t=this.masked.slice(this.cursor);this.valueWithCursor=`${e}${Jn.default.inverse(t[0])}${t.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}},ii=Object.defineProperty,ai=(e,t,n)=>t in e?ii(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,oi=(e,t,n)=>(ai(e,typeof t==`symbol`?t:t+``,n),n),si=class extends zr{constructor(e){super(e,!1),oi(this,`options`),oi(this,`cursor`,0),this.options=e.options,this.cursor=this.options.findIndex(({value:t})=>t===e.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case`down`:case`right`:this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}},ci=Object.defineProperty,li=(e,t,n)=>t in e?ci(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ui=(e,t,n)=>(li(e,typeof t==`symbol`?t:t+``,n),n),di=class extends zr{constructor(e){super(e,!1),ui(this,`options`),ui(this,`cursor`,0),this.options=e.options;let t=this.options.map(({value:[e]})=>e?.toLowerCase());this.cursor=Math.max(t.indexOf(e.initialValue),0),this.on(`key`,e=>{if(!t.includes(e))return;let n=this.options.find(({value:[t]})=>t?.toLowerCase()===e);n&&(this.value=n.value,this.state=`submit`,this.emit(`submit`))})}},fi=class extends zr{get valueWithCursor(){if(this.state===`submit`)return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;let e=this.value.slice(0,this.cursor),[t,...n]=this.value.slice(this.cursor);return`${e}${Jn.default.inverse(t)}${n.join(``)}`}get cursor(){return this._cursor}constructor(e){super(e),this.on(`finalize`,()=>{this.value||=e.defaultValue})}},Y=e.__toESM(Gn(),1),pi=e.__toESM(Wn(),1);function mi(){return
|
|
43
|
+
`)),this._prevFrame=e;return}this.output.write(qn.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},Br=class extends zr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`value`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(qn.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},Vr=Object.defineProperty,Hr=(e,t,n)=>t in e?Vr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ur=(e,t,n)=>(Hr(e,typeof t==`symbol`?t:t+``,n),n),Wr=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},Gr=(e,t,n)=>(Wr(e,t,`read from private field`),n?n.call(e):t.get(e)),Kr=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},qr=(e,t,n,r)=>(Wr(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n),Jr;let Yr=class extends zr{constructor(e){super(e,!1),Ur(this,`options`),Ur(this,`cursor`,0),Kr(this,Jr,void 0);let{options:t}=e;qr(this,Jr,e.selectableGroups!==!1),this.options=Object.entries(t).flatMap(([e,t])=>[{value:e,group:!0,label:e},...t.map(t=>({...t,group:e}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),Gr(this,Jr)?0:1),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let e=this.options[this.cursor]?.group===!0;!Gr(this,Jr)&&e&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case`down`:case`right`:{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let e=this.options[this.cursor]?.group===!0;!Gr(this,Jr)&&e&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case`space`:this.toggleValue();break}})}getGroupItems(e){return this.options.filter(t=>t.group===e)}isGroupSelected(e){return this.getGroupItems(e).every(e=>this.value.includes(e.value))}toggleValue(){let e=this.options[this.cursor];if(e.group===!0){let t=e.value,n=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter(e=>n.findIndex(t=>t.value===e)===-1):this.value=[...this.value,...n.map(e=>e.value)],this.value=Array.from(new Set(this.value))}else this.value=this.value.includes(e.value)?this.value.filter(t=>t!==e.value):[...this.value,e.value]}};Jr=new WeakMap;var Xr=Object.defineProperty,Zr=(e,t,n)=>t in e?Xr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Qr=(e,t,n)=>(Zr(e,typeof t==`symbol`?t:t+``,n),n);let $r=class extends zr{constructor(e){super(e,!1),Qr(this,`options`),Qr(this,`cursor`,0),this.options=e.options,this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0),this.on(`key`,e=>{e===`a`&&this.toggleAll()}),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case`down`:case`right`:this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case`space`:this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){this.value=this.value.length===this.options.length?[]:this.options.map(e=>e.value)}toggleValue(){this.value=this.value.includes(this._value)?this.value.filter(e=>e!==this._value):[...this.value,this._value]}};var ei=Object.defineProperty,ti=(e,t,n)=>t in e?ei(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ni=(e,t,n)=>(ti(e,typeof t==`symbol`?t:t+``,n),n),ri=class extends zr{constructor({mask:e,...t}){super(t),ni(this,`valueWithCursor`,``),ni(this,`_mask`,`•`),this._mask=e??`•`,this.on(`finalize`,()=>{this.valueWithCursor=this.masked}),this.on(`value`,()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${Jn.default.inverse(Jn.default.hidden(`_`))}`;else{let e=this.masked.slice(0,this.cursor),t=this.masked.slice(this.cursor);this.valueWithCursor=`${e}${Jn.default.inverse(t[0])}${t.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}},ii=Object.defineProperty,ai=(e,t,n)=>t in e?ii(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,oi=(e,t,n)=>(ai(e,typeof t==`symbol`?t:t+``,n),n),si=class extends zr{constructor(e){super(e,!1),oi(this,`options`),oi(this,`cursor`,0),this.options=e.options,this.cursor=this.options.findIndex(({value:t})=>t===e.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case`down`:case`right`:this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}},ci=Object.defineProperty,li=(e,t,n)=>t in e?ci(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ui=(e,t,n)=>(li(e,typeof t==`symbol`?t:t+``,n),n),di=class extends zr{constructor(e){super(e,!1),ui(this,`options`),ui(this,`cursor`,0),this.options=e.options;let t=this.options.map(({value:[e]})=>e?.toLowerCase());this.cursor=Math.max(t.indexOf(e.initialValue),0),this.on(`key`,e=>{if(!t.includes(e))return;let n=this.options.find(({value:[t]})=>t?.toLowerCase()===e);n&&(this.value=n.value,this.state=`submit`,this.emit(`submit`))})}},fi=class extends zr{get valueWithCursor(){if(this.state===`submit`)return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;let e=this.value.slice(0,this.cursor),[t,...n]=this.value.slice(this.cursor);return`${e}${Jn.default.inverse(t)}${n.join(``)}`}get cursor(){return this._cursor}constructor(e){super(e),this.on(`finalize`,()=>{this.value||=e.defaultValue})}},Y=e.__toESM(Gn(),1),pi=e.__toESM(Wn(),1);function mi(){return m.default.platform===`win32`?!!m.default.env.CI||!!m.default.env.WT_SESSION||!!m.default.env.TERMINUS_SUBLIME||m.default.env.ConEmuTask===`{cmd::Cmder}`||m.default.env.TERM_PROGRAM===`Terminus-Sublime`||m.default.env.TERM_PROGRAM===`vscode`||m.default.env.TERM===`xterm-256color`||m.default.env.TERM===`alacritty`||m.default.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:m.default.env.TERM!==`linux`}const hi=mi(),gi=(e,t)=>hi?e:t,_i=gi(`◆`,`*`),vi=gi(`■`,`x`),yi=gi(`▲`,`x`),bi=gi(`◇`,`o`),xi=gi(`┌`,`T`),X=gi(`│`,`|`),Si=gi(`└`,`—`),Ci=gi(`●`,`>`),wi=gi(`○`,` `),Ti=gi(`◻`,`[•]`),Ei=gi(`◼`,`[+]`),Di=gi(`◻`,`[ ]`),Oi=gi(`▪`,`•`),ki=gi(`─`,`-`),Ai=gi(`╮`,`+`),ji=gi(`├`,`+`),Mi=gi(`╯`,`+`),Ni=gi(`●`,`•`),Pi=gi(`◆`,`*`),Fi=gi(`▲`,`!`),Ii=gi(`■`,`x`),Li=e=>{switch(e){case`initial`:case`active`:return Y.default.cyan(_i);case`cancel`:return Y.default.red(vi);case`error`:return Y.default.yellow(yi);case`submit`:return Y.default.green(bi)}},Ri=e=>{let{cursor:t,options:n,style:r}=e,i=e.maxItems??1/0,a=Math.max(process.stdout.rows-4,0),o=Math.min(a,Math.max(i,5)),s=0;t>=s+o-3?s=Math.max(Math.min(t-o+3,n.length-o),0):t<s+2&&(s=Math.max(t-2,0));let c=o<n.length&&s>0,l=o<n.length&&s+o<n.length;return n.slice(s,s+o).map((e,n,i)=>{let a=n===0&&c,o=n===i.length-1&&l;return a||o?Y.default.dim(`...`):r(e,n+s===t)})},zi=e=>new fi({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){let t=`${Y.default.gray(X)}
|
|
44
44
|
${Li(this.state)} ${e.message}
|
|
45
45
|
`,n=e.placeholder?Y.default.inverse(e.placeholder[0])+Y.default.dim(e.placeholder.slice(1)):Y.default.inverse(Y.default.hidden(`_`)),r=this.value?this.valueWithCursor:n;switch(this.state){case`error`:return`${t.trim()}
|
|
46
46
|
${Y.default.yellow(X)} ${r}
|
|
@@ -100,7 +100,7 @@ ${Y.default.cyan(Si)}
|
|
|
100
100
|
`}}}).prompt()},Ki=(e=``,t=``)=>{let n=`
|
|
101
101
|
${e}
|
|
102
102
|
`.split(`
|
|
103
|
-
`),r=(0,
|
|
103
|
+
`),r=(0,c.stripVTControlCharacters)(t).length,i=Math.max(n.reduce((e,t)=>{let n=(0,c.stripVTControlCharacters)(t);return n.length>e?n.length:e},0),r)+2,a=n.map(e=>`${Y.default.gray(X)} ${Y.default.dim(e)}${` `.repeat(i-(0,c.stripVTControlCharacters)(e).length)}${Y.default.gray(X)}`).join(`
|
|
104
104
|
`);process.stdout.write(`${Y.default.gray(X)}
|
|
105
105
|
${Y.default.green(bi)} ${Y.default.reset(t)} ${Y.default.gray(ki.repeat(Math.max(i-r-1,1))+Ai)}
|
|
106
106
|
${a}
|
|
@@ -117,22 +117,22 @@ ${Y.default.gray(Si)} ${e}
|
|
|
117
117
|
`)},info:e=>{Xi.message(e,{symbol:Y.default.blue(Ni)})},success:e=>{Xi.message(e,{symbol:Y.default.green(Pi)})},step:e=>{Xi.message(e,{symbol:Y.default.green(bi)})},warn:e=>{Xi.message(e,{symbol:Y.default.yellow(Fi)})},warning:e=>{Xi.warn(e)},error:e=>{Xi.message(e,{symbol:Y.default.red(Ii)})}},Zi=`${Y.default.gray(X)} `,Qi={message:async(e,{symbol:t=Y.default.gray(X)}={})=>{process.stdout.write(`${Y.default.gray(X)}
|
|
118
118
|
${t} `);let n=3;for await(let t of e){t=t.replace(/\n/g,`
|
|
119
119
|
${Zi}`),t.includes(`
|
|
120
|
-
`)&&(n=3+(0,
|
|
121
|
-
`))).length);let e=(0,
|
|
122
|
-
${Zi}${t.trimStart()}`),n=3+(0,
|
|
120
|
+
`)&&(n=3+(0,c.stripVTControlCharacters)(t.slice(t.lastIndexOf(`
|
|
121
|
+
`))).length);let e=(0,c.stripVTControlCharacters)(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
122
|
+
${Zi}${t.trimStart()}`),n=3+(0,c.stripVTControlCharacters)(t.trimStart()).length)}process.stdout.write(`
|
|
123
123
|
`)},info:e=>Qi.message(e,{symbol:Y.default.blue(Ni)}),success:e=>Qi.message(e,{symbol:Y.default.green(Pi)}),step:e=>Qi.message(e,{symbol:Y.default.green(bi)}),warn:e=>Qi.message(e,{symbol:Y.default.yellow(Fi)}),warning:e=>Qi.warn(e),error:e=>Qi.message(e,{symbol:Y.default.red(Ii)})},$i=({indicator:e=`dots`}={})=>{let t=hi?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],n=hi?80:120,r=process.env.CI===`true`,i,a,o=!1,s=``,c,l=performance.now(),u=e=>{o&&y(e>1?`Something went wrong`:`Canceled`,e)},d=()=>u(2),f=()=>u(1),p=()=>{process.on(`uncaughtExceptionMonitor`,d),process.on(`unhandledRejection`,d),process.on(`SIGINT`,f),process.on(`SIGTERM`,f),process.on(`exit`,u)},m=()=>{process.removeListener(`uncaughtExceptionMonitor`,d),process.removeListener(`unhandledRejection`,d),process.removeListener(`SIGINT`,f),process.removeListener(`SIGTERM`,f),process.removeListener(`exit`,u)},h=()=>{if(c===void 0)return;r&&process.stdout.write(`
|
|
124
124
|
`);let e=c.split(`
|
|
125
125
|
`);process.stdout.write(pi.cursor.move(-999,e.length-1)),process.stdout.write(pi.erase.down(e.length))},g=e=>e.replace(/\.+$/,``),_=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},v=(u=``)=>{o=!0,i=Fr(),s=g(u),l=performance.now(),process.stdout.write(`${Y.default.gray(X)}
|
|
126
126
|
`);let d=0,f=0;p(),a=setInterval(()=>{if(r&&s===c)return;h(),c=s;let n=Y.default.magenta(t[d]);if(r)process.stdout.write(`${n} ${s}...`);else if(e===`timer`)process.stdout.write(`${n} ${s} ${_(l)}`);else{let e=`.`.repeat(Math.floor(f)).slice(0,3);process.stdout.write(`${n} ${s}${e}`)}d=d+1<t.length?d+1:0,f=f<t.length?f+.125:0},n)},y=(t=``,n=0)=>{o=!1,clearInterval(a),h();let r=n===0?Y.default.green(bi):n===1?Y.default.red(vi):Y.default.red(yi);s=g(t??s),e===`timer`?process.stdout.write(`${r} ${s} ${_(l)}
|
|
127
127
|
`):process.stdout.write(`${r} ${s}
|
|
128
|
-
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},ea=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&Nr(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},ta=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=$i();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let na;function ra(){try{return l.default.statSync(`/.dockerenv`),!0}catch{return!1}}function ia(){try{return l.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function aa(){return na===void 0&&(na=ra()||ia()),na}let oa;const sa=()=>{try{return l.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function ca(){return oa===void 0&&(oa=sa()||aa()),oa}const la=()=>{if(h.default.platform!==`linux`)return!1;if(T.default.release().toLowerCase().includes(`microsoft`))return!ca();try{return l.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!ca():!1}catch{return!1}};var ua=h.default.env.__IS_WSL_TEST__?la:la();const da=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await w.default.access(n,w.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await w.default.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),fa=async()=>`${await da()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,pa=async()=>ua?fa():`${h.default.env.SYSTEMROOT||h.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function ma(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const ha=(0,f.promisify)(C.execFile);async function ga(){if(h.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await ha(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const _a=(0,f.promisify)(C.execFile);async function va(e,{humanReadableOutput:t=!0,signal:n}={}){if(h.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await _a(`osascript`,[`-e`,e,r],i);return a.trim()}async function ya(e){return va(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const ba=(0,f.promisify)(C.execFile),xa={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var Sa=class extends Error{};async function Ca(e=ba){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new Sa(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=xa[r];if(!i)throw new Sa(`Unknown browser ID: ${r}`);return i}const wa=(0,f.promisify)(C.execFile),Ta=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Ea(){if(h.default.platform===`darwin`){let e=await ga();return{name:await ya(e),id:e}}if(h.default.platform===`linux`){let{stdout:e}=await wa(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:Ta(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(h.default.platform===`win32`)return Ca();throw Error(`Only macOS, Linux, and Windows are supported`)}const Da=(0,f.promisify)(C.default.execFile),Oa=S.default.dirname((0,u.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),ka=S.default.join(Oa,`xdg-open`),{platform:Aa,arch:ja}=h.default;async function Ma(){let e=await pa(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=c.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await Da(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const Na=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},Pa=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return Na(e.app,t=>Pa({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return Na(t,t=>Pa({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=ua?await Ma():await Ea();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),Pa({...e,app:{name:Ra[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(Aa===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(Aa===`win32`||ua&&!ca()&&!t){r=await pa(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),ua||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=c.Buffer.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!Oa||Oa===`/`,t=!1;try{await w.default.access(ka,w.constants.X_OK),t=!0}catch{}r=h.default.versions.electron??(Aa===`android`||e||!t)?`xdg-open`:ka}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}Aa===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=C.default.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},Fa=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return Pa({...t,target:e})};function Ia(e){if(typeof e==`string`||Array.isArray(e))return e;let{[ja]:t}=e;if(!t)throw Error(`${ja} is not supported`);return t}function La({[Aa]:e},{wsl:t}){if(t&&ua)return Ia(t);if(!e)throw Error(`${Aa} is not supported`);return Ia(e)}const Ra={};ma(Ra,`chrome`,()=>La({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),ma(Ra,`brave`,()=>La({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),ma(Ra,`firefox`,()=>La({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),ma(Ra,`edge`,()=>La({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),ma(Ra,`browser`,()=>`browser`),ma(Ra,`browserPrivate`,()=>`browserPrivate`);var za=Fa;function Ba(e){let t=e||Ua();if((0,i.existsSync)(t)){let e=(0,i.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function Va(e,t){let n=t||Ua();(0,i.existsSync)((0,r.dirname)(n))||(0,i.mkdirSync)((0,r.dirname)(n),{recursive:!0}),(0,i.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function Ha(e){let t=e||Ua();(0,i.existsSync)(t)&&(0,i.unlinkSync)(t)}function Ua(){let e=Pn(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,r.join)(e[0],`auth.json`)}function Wa(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,v.useState)(),[s,c]=(0,v.useState)(()=>Ba(i)),[l,u]=(0,v.useState)(),d=(0,v.useRef)(n),f=(0,v.useRef)(r);(0,v.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,v.useCallback)(async()=>{u(void 0);try{let e=Ba(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new Cn({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=(0,v.useCallback)(async()=>{u(void 0);try{let e=new Cn,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();Va(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=(0,v.useCallback)(()=>{Ha(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,v.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function Ga(e){let{directory:n,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,v.useMemo)(()=>t.resolveConfig(n),[n]),[s,c]=(0,v.useState)(void 0),[l,u]=(0,v.useState)(void 0),[d,f]=(0,v.useState)(`building`),p=(0,v.useRef)(r),m=(0,v.useRef)(i),h=(0,v.useRef)(a);return(0,v.useEffect)(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),(0,v.useEffect)(()=>{let e=new AbortController;return o.build({cwd:n,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[n]),(0,v.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Ka(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function qa(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Ja=100,Ya=/^\.+(\\|\/)|^\.+$/,Xa=/[. ]+$/,Za=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Qa=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,$a=e=>e===``,eo=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,to=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let no;function ro(){return no??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),no}function io(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Ka().test(n)||[...n].some(e=>Qa.test(e)&&!$a(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(to,` `),n.length>0&&(e=e.replaceAll(eo,`$1`)),e=e.replace(Xa,``),e=e.replace(Ya,n),e=e.replace(Ka(),n),e=e.replaceAll(Za,e=>$a(e)?e:n),e.length===0&&(e=n),e=qa().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=ao(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=ao(n,a)+i}}return e}function ao(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of ro().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function oo(e){return`${e}.lock`}function so(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function co(e,t={}){let n=oo(e),r=process.pid.toString();try{return l.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(l.readFileSync(n,`utf8`),10)}catch{return l.unlinkSync(n),co(e,{...t,stale:0})}if(!so(i))try{return l.unlinkSync(n),co(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return co(e,{...t,stale:0});throw n}return!1}}async function lo(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=S.resolve(e),i=0;for(;i<=n.retries;){if(co(r,n))return()=>uo(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function uo(e){let t=S.resolve(e),n=oo(t);try{if(parseInt(l.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}l.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function fo(e){let t=S.resolve(e),n=oo(t);try{if(!l.existsSync(n))return{locked:!1};let e=l.readFileSync(n,`utf8`),t=parseInt(e,10);return so(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const po=e=>{l.mkdirSync(e,{recursive:!0})},mo=e=>{try{l.fdatasyncSync(e)}catch{}try{l.closeSync(e)}catch{}},ho=e=>{try{let t=l.openSync(e,`r`);try{l.fsyncSync(t)}finally{l.closeSync(t)}}catch{}},go=(e,t)=>{let n=S.dirname(e);po(n);let r=S.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=l.openSync(r,`w`),l.writeFileSync(i,t,`utf-8`),mo(i),i=void 0,l.renameSync(r,e),ho(e),ho(n)}catch(e){if(i!==void 0)try{l.closeSync(i)}catch{}try{l.rmSync(r,{force:!0})}catch{}throw e}},_o=(e,t)=>{let n=new Map,r,i=e=>{if(l.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(l.readFileSync(e,`utf-8`))},a=(e,t)=>{go(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=S.join(e,`index.json`);po(e),l.existsSync(t)||l.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await lo(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=S.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=S.join(e,`index.json`);a(n,t)},u=async t=>{let n=(await s()).ids[t];if(n)return S.join(e,n)},d=async t=>{let n=(await s()).ids[t];if(!n)return;let r=S.join(e,n);if(l.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(l.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),l=io(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=S.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!l.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=S.join(e,i),a=l.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=fo(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await u(r);if(!a){let t=io(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=S.join(e,t);po(e),l.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=fo(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await lo(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=S.join(e,n);try{l.rmSync(i,{force:!0}),ho(e)}catch{}}}finally{await t()}},async release(){p(),n.delete(r)}}},dispose(){n.clear()}}},vo=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,u=S.join(e,`index.json`),d=()=>{try{if(!l.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=l.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let i=S.join(e,n);try{let e=l.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),f(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=fo(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(l.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),f(t,e,s.locked,s.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),p(e,t,n)},r))},g=()=>{if(a)return;try{l.mkdirSync(e,{recursive:!0})}catch{}a=l.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),o=setTimeout(t,n)};m(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&g(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function yo({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=bo}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=(0,g.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const bo=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(t+1).filter(g.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>n.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},xo=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function So(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Co=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=_o(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=vo(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!So(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!(0,g.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await yo({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function wo(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=(0,v.useRef)(null),[s,c]=(0,v.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,v.useEffect)(()=>{o.current&&o.current.dispose();let e=new Co({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),(0,v.useEffect)(()=>{o.current&&o.current.setAgent(n)},[n]);let l=(0,v.useCallback)(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=(0,v.useCallback)(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=(0,v.useCallback)(()=>{o.current&&o.current.stopStreaming()},[]),f=(0,v.useCallback)(async()=>{o.current&&await o.current.resetChat()},[]),p=(0,v.useCallback)(()=>{o.current&&o.current.clearQueue()},[]),m=(0,v.useCallback)(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=(0,v.useCallback)(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function To(e){let t=(0,r.join)(e,`data`,`devhook.txt`);if((0,i.mkdirSync)((0,r.dirname)(t),{recursive:!0}),(0,i.existsSync)(t))return(0,i.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,i.writeFileSync)(t,n),n}const Eo=(e,t)=>e.json({error:t},400),Do=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Oo=()=>new n.Hono,ko=Oo().get(`/:key`,async e=>{let{key:t,err:n}=Do(e);if(n)return Eo(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,n.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Eo(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Eo(t,`Value must be a string`):Eo(t,`Value is required`)}),async e=>{let{key:t,err:n}=Do(e);if(n)return Eo(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Do(e);return n?Eo(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),Ao=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},jo=n.validator(`param`,e=>({id:e.id})),Mo=Oo().post(`/:key`,async e=>{let{key:t,err:n}=Ao(e);return n?Eo(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,jo,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,jo,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,n.validator(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):Eo(e,`ID is required`)}).delete(`/:id/messages`,jo,n.validator(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,jo,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,jo,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,jo,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),No=Oo().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),Po=new n.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,ko).route(`/chat`,Mo).route(`/otlp`,No);var Fo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Io(e){return typeof e==`string`&&Fo.test(e)}var Lo=Io;function Ro(e){if(!Lo(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var zo=Ro;const Bo=[];for(let e=0;e<256;++e)Bo.push((e+256).toString(16).slice(1));function Vo(e,t=0){return(Bo[e[t+0]]+Bo[e[t+1]]+Bo[e[t+2]]+Bo[e[t+3]]+`-`+Bo[e[t+4]]+Bo[e[t+5]]+`-`+Bo[e[t+6]]+Bo[e[t+7]]+`-`+Bo[e[t+8]]+Bo[e[t+9]]+`-`+Bo[e[t+10]]+Bo[e[t+11]]+Bo[e[t+12]]+Bo[e[t+13]]+Bo[e[t+14]]+Bo[e[t+15]]).toLowerCase()}function Ho(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}const Uo=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Wo=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Go(e,t,n,r,i,a){let o=typeof n==`string`?Ho(n):n,s=typeof r==`string`?zo(r):r;if(typeof r==`string`&&(r=zo(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return Vo(c)}function Ko(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,p.createHash)(`sha1`).update(e).digest()}var qo=Ko;function Jo(e,t,n,r){return Go(80,qo,e,t,n,r)}Jo.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Jo.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Yo=Jo;function Xo(e){let t=(0,S.join)(e.dataDirectory,`chats`),r={},i=(0,S.join)(e.dataDirectory,`storage.json`);l.existsSync(i)&&(r=JSON.parse(l.readFileSync(i,`utf-8`)));let a=new Map,o=n=>{let r=a.get(n);return r||(r=new Co({chatId:n,chatsDirectory:t}),r.setAgent(e.getAgent()),a.set(n,r)),r},s={async upsert(e){let t=Yo(JSON.stringify(e),Yo.URL),n=o(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=o(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return o(e).getState().messages},async sendMessages(e,t,n){let r=o(e),i=t.map(e=>xo(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await o(e).deleteMessages(t)},async start(e){await o(e).start()},async stop(e){await o(e).stop()},async delete(e){await o(e).resetChat()}},c={get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,l.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],l.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},u=(0,m.createServer)(n.createServerAdapter(e=>Po.fetch(e,{chat:s,store:c})));u.listen(e.port??0);let d=_o(t,`id`);return{url:`http://127.0.0.1:${u.address().port}`,chatsDirectory:t,getChatManager:o,listChats:()=>d.list(),dispose:()=>{for(let e of a.values())e.dispose();a.clear(),d.dispose(),u.close()}}}function Zo({agent:e,capabilities:t,messages:r}){let[i,a]=(0,v.useState)(void 0),[o,s]=(0,v.useState)(!0),[c,l]=(0,v.useState)(void 0),u=(0,v.useRef)(c);(0,v.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,v.useState)(()=>n.lastUIOptions(r));(0,v.useEffect)(()=>{f(e=>{let t=n.lastUIOptions(r);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[r]);let[p,m]=(0,v.useState)(void 0),h=(0,v.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=(0,v.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))h(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);(0,v.useEffect)(()=>{if(!d&&!c){m(void 0);return}g()},[d,c,g]);let _=(0,v.useRef)(void 0),y=(0,v.useRef)(void 0);(0,v.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),_.current=void 0)},[e]),(0,v.useEffect)(()=>{if(t&&!t.ui||!e){l(void 0),m(void 0),a(void 0),_.current=void 0;return}let n=p?JSON.stringify(p):``;if(_.current===n){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),_.current=n)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,t,p]);let b=(0,v.useCallback)((e,t)=>{g({[e]:t})},[g]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Qo(e){let t=(0,v.useRef)(e.onRequest);(0,v.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let n=(0,v.useRef)(e.id??crypto.randomUUID()),[r,i]=(0,v.useState)(`disconnected`);return(0,v.useEffect)(()=>{if(e.disabled){i(`disconnected`);return}let r=!1,a,o,s=!1,c=()=>{if(!(r||s)){if(s=!0,a){try{a.dispose()}catch{}a=void 0}a=new Cn({baseURL:`https://blink.so`}).devhook.listen({id:n.current,onRequest:async e=>t.current(e),onConnect:()=>{s=!1,i(`connected`)},onDisconnect:()=>{s=!1,i(`disconnected`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))},onError:e=>{s=!1,i(`error`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))}})}};return c(),()=>{if(r=!0,o&&=(clearTimeout(o),void 0),a){try{a.dispose()}catch{}a=void 0}}},[e.disabled]),{id:n.current,status:r}}var $o=e.__commonJSMin(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),es=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=$o().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
128
|
+
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},ea=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&Nr(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},ta=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=$i();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let na;function ra(){try{return a.default.statSync(`/.dockerenv`),!0}catch{return!1}}function ia(){try{return a.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function aa(){return na===void 0&&(na=ra()||ia()),na}let oa;const sa=()=>{try{return a.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function ca(){return oa===void 0&&(oa=sa()||aa()),oa}const la=()=>{if(m.default.platform!==`linux`)return!1;if(T.default.release().toLowerCase().includes(`microsoft`))return!ca();try{return a.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!ca():!1}catch{return!1}};var ua=m.default.env.__IS_WSL_TEST__?la:la();const da=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await w.default.access(n,w.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await w.default.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),fa=async()=>`${await da()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,pa=async()=>ua?fa():`${m.default.env.SYSTEMROOT||m.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function ma(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const ha=(0,c.promisify)(C.execFile);async function ga(){if(m.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await ha(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const _a=(0,c.promisify)(C.execFile);async function va(e,{humanReadableOutput:t=!0,signal:n}={}){if(m.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await _a(`osascript`,[`-e`,e,r],i);return a.trim()}async function ya(e){return va(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const ba=(0,c.promisify)(C.execFile),xa={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var Sa=class extends Error{};async function Ca(e=ba){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new Sa(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=xa[r];if(!i)throw new Sa(`Unknown browser ID: ${r}`);return i}const wa=(0,c.promisify)(C.execFile),Ta=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Ea(){if(m.default.platform===`darwin`){let e=await ga();return{name:await ya(e),id:e}}if(m.default.platform===`linux`){let{stdout:e}=await wa(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:Ta(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(m.default.platform===`win32`)return Ca();throw Error(`Only macOS, Linux, and Windows are supported`)}const Da=(0,c.promisify)(C.default.execFile),Oa=S.default.dirname((0,o.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),ka=S.default.join(Oa,`xdg-open`),{platform:Aa,arch:ja}=m.default;async function Ma(){let e=await pa(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=i.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await Da(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),a=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[a]?{id:o[a]}:{}}const Na=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},Pa=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return Na(e.app,t=>Pa({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return Na(t,t=>Pa({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=ua?await Ma():await Ea();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),Pa({...e,app:{name:Ra[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,a=[],o={};if(Aa===`darwin`)r=`open`,e.wait&&a.push(`--wait-apps`),e.background&&a.push(`--background`),e.newInstance&&a.push(`--new`),t&&a.push(`-a`,t);else if(Aa===`win32`||ua&&!ca()&&!t){r=await pa(),a.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),ua||(o.windowsVerbatimArguments=!0);let s=[`Start`];e.wait&&s.push(`-Wait`),t?(s.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&s.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),s.push(`-ArgumentList`,n.join(`,`))),e.target=i.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!Oa||Oa===`/`,t=!1;try{await w.default.access(ka,w.constants.X_OK),t=!0}catch{}r=m.default.versions.electron??(Aa===`android`||e||!t)?`xdg-open`:ka}n.length>0&&a.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}Aa===`darwin`&&n.length>0&&a.push(`--args`,...n),e.target&&a.push(e.target);let s=C.default.spawn(r,a,o);return e.wait?new Promise((t,n)=>{s.once(`error`,n),s.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(s)})}):(s.unref(),s)},Fa=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return Pa({...t,target:e})};function Ia(e){if(typeof e==`string`||Array.isArray(e))return e;let{[ja]:t}=e;if(!t)throw Error(`${ja} is not supported`);return t}function La({[Aa]:e},{wsl:t}){if(t&&ua)return Ia(t);if(!e)throw Error(`${Aa} is not supported`);return Ia(e)}const Ra={};ma(Ra,`chrome`,()=>La({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),ma(Ra,`brave`,()=>La({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),ma(Ra,`firefox`,()=>La({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),ma(Ra,`edge`,()=>La({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),ma(Ra,`browser`,()=>`browser`),ma(Ra,`browserPrivate`,()=>`browserPrivate`);var za=Fa;function Ba(e){let t=e||Ua();if((0,p.existsSync)(t)){let e=(0,p.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function Va(e,t){let n=t||Ua();(0,p.existsSync)((0,d.dirname)(n))||(0,p.mkdirSync)((0,d.dirname)(n),{recursive:!0}),(0,p.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function Ha(e){let t=e||Ua();(0,p.existsSync)(t)&&(0,p.unlinkSync)(t)}function Ua(){let e=Pn(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,d.join)(e[0],`auth.json`)}function Wa(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,v.useState)(),[s,c]=(0,v.useState)(()=>Ba(i)),[l,u]=(0,v.useState)(),d=(0,v.useRef)(n),f=(0,v.useRef)(r);(0,v.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,v.useCallback)(async()=>{u(void 0);try{let e=Ba(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new Cn({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=(0,v.useCallback)(async()=>{u(void 0);try{let e=new Cn,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();Va(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=(0,v.useCallback)(()=>{Ha(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,v.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function Ga(e){let{directory:t,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,v.useMemo)(()=>n.resolveConfig(t),[t]),[s,c]=(0,v.useState)(void 0),[l,u]=(0,v.useState)(void 0),[d,f]=(0,v.useState)(`building`),p=(0,v.useRef)(r),m=(0,v.useRef)(i),h=(0,v.useRef)(a);return(0,v.useEffect)(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),(0,v.useEffect)(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),(0,v.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Ka(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function qa(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Ja=100,Ya=/^\.+(\\|\/)|^\.+$/,Xa=/[. ]+$/,Za=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Qa=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,$a=e=>e===``,eo=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,to=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let no;function ro(){return no??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),no}function io(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Ka().test(n)||[...n].some(e=>Qa.test(e)&&!$a(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(to,` `),n.length>0&&(e=e.replaceAll(eo,`$1`)),e=e.replace(Xa,``),e=e.replace(Ya,n),e=e.replace(Ka(),n),e=e.replaceAll(Za,e=>$a(e)?e:n),e.length===0&&(e=n),e=qa().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=ao(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=ao(n,a)+i}}return e}function ao(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of ro().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function oo(e){return`${e}.lock`}function so(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function co(e,t={}){let n=oo(e),r=process.pid.toString();try{return a.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(a.readFileSync(n,`utf8`),10)}catch{return a.unlinkSync(n),co(e,{...t,stale:0})}if(!so(i))try{return a.unlinkSync(n),co(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return co(e,{...t,stale:0});throw n}return!1}}async function lo(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=S.resolve(e),i=0;for(;i<=n.retries;){if(co(r,n))return()=>uo(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function uo(e){let t=S.resolve(e),n=oo(t);try{if(parseInt(a.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}a.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function fo(e){let t=S.resolve(e),n=oo(t);try{if(!a.existsSync(n))return{locked:!1};let e=a.readFileSync(n,`utf8`),t=parseInt(e,10);return so(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const po=e=>{a.mkdirSync(e,{recursive:!0})},mo=e=>{try{a.fdatasyncSync(e)}catch{}try{a.closeSync(e)}catch{}},ho=e=>{try{let t=a.openSync(e,`r`);try{a.fsyncSync(t)}finally{a.closeSync(t)}}catch{}},go=(e,t)=>{let n=S.dirname(e);po(n);let r=S.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=a.openSync(r,`w`),a.writeFileSync(i,t,`utf-8`),mo(i),i=void 0,a.renameSync(r,e),ho(e),ho(n)}catch(e){if(i!==void 0)try{a.closeSync(i)}catch{}try{a.rmSync(r,{force:!0})}catch{}throw e}},_o=(e,t)=>{let n=new Map,r,i=e=>{if(a.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(a.readFileSync(e,`utf-8`))},o=(e,t)=>{go(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=S.join(e,`index.json`);po(e),a.existsSync(t)||a.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await lo(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=S.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=S.join(e,`index.json`);o(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return S.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=S.join(e,n);if(a.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(a.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),a=io(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=a,t.current=i;let r=S.join(e,a);o(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!a.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=S.join(e,i),o=a.statSync(t,{throwIfNoEntry:!1});if(!o)continue;let s=fo(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:o.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let o=await u(r);if(!o){let t=io(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=S.join(e,t);po(e),a.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),o=i}finally{await n()}}if(i?.force){let e=fo(o);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await lo(o,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let i=S.join(e,n);try{a.rmSync(i,{force:!0}),ho(e)}catch{}}}finally{await t()}},async release(){p(),n.delete(r)}}},dispose(){n.clear()}}},vo=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,o,s,c=new Map,l=new Map,u=S.join(e,`index.json`),d=()=>{try{if(!a.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=a.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let i=S.join(e,n);try{let e=a.statSync(i,{throwIfNoEntry:!1}),o=l.get(n);if(!e){o&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=o?{locked:o.locked,pid:o.pid}:{locked:!1,pid:void 0};if((r||!o)&&(c=fo(i)),!o||o.mtime!==s||o.locked!==c.locked||o.pid!==c.pid){let e;e=!o||o.mtime!==s?JSON.parse(a.readFileSync(i,`utf-8`)):o.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},g=()=>{if(o)return;try{a.mkdirSync(e,{recursive:!0})}catch{}o=a.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return i.size===0&&g(),i.add(e),()=>{if(i.delete(e),i.size===0){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function yo({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=bo}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=(0,h.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const bo=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(h.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},xo=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function So(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Co=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=_o(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=vo(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!So(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!(0,h.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await yo({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function wo(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=(0,v.useRef)(null),[s,c]=(0,v.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,v.useEffect)(()=>{o.current&&o.current.dispose();let e=new Co({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),(0,v.useEffect)(()=>{o.current&&o.current.setAgent(n)},[n]);let l=(0,v.useCallback)(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=(0,v.useCallback)(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=(0,v.useCallback)(()=>{o.current&&o.current.stopStreaming()},[]),f=(0,v.useCallback)(async()=>{o.current&&await o.current.resetChat()},[]),p=(0,v.useCallback)(()=>{o.current&&o.current.clearQueue()},[]),m=(0,v.useCallback)(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=(0,v.useCallback)(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function To(e){let t=(0,d.join)(e,`data`,`devhook.txt`);if((0,p.mkdirSync)((0,d.dirname)(t),{recursive:!0}),(0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,p.writeFileSync)(t,n),n}const Eo=(e,t)=>e.json({error:t},400),Do=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Oo=()=>new t.Hono,ko=Oo().get(`/:key`,async e=>{let{key:t,err:n}=Do(e);if(n)return Eo(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Eo(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Eo(t,`Value must be a string`):Eo(t,`Value is required`)}),async e=>{let{key:t,err:n}=Do(e);if(n)return Eo(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Do(e);return n?Eo(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),Ao=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},jo=t.validator(`param`,e=>({id:e.id})),Mo=Oo().post(`/:key`,async e=>{let{key:t,err:n}=Ao(e);return n?Eo(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,jo,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,jo,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,t.validator(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):Eo(e,`ID is required`)}).delete(`/:id/messages`,jo,t.validator(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,jo,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,jo,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,jo,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),No=Oo().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),Po=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,ko).route(`/chat`,Mo).route(`/otlp`,No);var Fo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Io(e){return typeof e==`string`&&Fo.test(e)}var Lo=Io;function Ro(e){if(!Lo(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var zo=Ro;const Bo=[];for(let e=0;e<256;++e)Bo.push((e+256).toString(16).slice(1));function Vo(e,t=0){return(Bo[e[t+0]]+Bo[e[t+1]]+Bo[e[t+2]]+Bo[e[t+3]]+`-`+Bo[e[t+4]]+Bo[e[t+5]]+`-`+Bo[e[t+6]]+Bo[e[t+7]]+`-`+Bo[e[t+8]]+Bo[e[t+9]]+`-`+Bo[e[t+10]]+Bo[e[t+11]]+Bo[e[t+12]]+Bo[e[t+13]]+Bo[e[t+14]]+Bo[e[t+15]]).toLowerCase()}function Ho(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}const Uo=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Wo=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Go(e,t,n,r,i,a){let o=typeof n==`string`?Ho(n):n,s=typeof r==`string`?zo(r):r;if(typeof r==`string`&&(r=zo(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return Vo(c)}function Ko(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,l.createHash)(`sha1`).update(e).digest()}var qo=Ko;function Jo(e,t,n,r){return Go(80,qo,e,t,n,r)}Jo.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Jo.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Yo=Jo;function Xo(e){let n=(0,S.join)(e.dataDirectory,`chats`),r={},i=(0,S.join)(e.dataDirectory,`storage.json`);a.existsSync(i)&&(r=JSON.parse(a.readFileSync(i,`utf-8`)));let o=new Map,s=t=>{let r=o.get(t);return r||(r=new Co({chatId:t,chatsDirectory:n}),r.setAgent(e.getAgent()),o.set(t,r)),r},c={async upsert(e){let t=Yo(JSON.stringify(e),Yo.URL),n=s(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=s(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return s(e).getState().messages},async sendMessages(e,t,n){let r=s(e),i=t.map(e=>xo(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await s(e).deleteMessages(t)},async start(e){await s(e).start()},async stop(e){await s(e).stop()},async delete(e){await s(e).resetChat()}},l={get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,a.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],a.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},d=(0,u.createServer)(t.createServerAdapter(e=>Po.fetch(e,{chat:c,store:l})));d.listen(e.port??0);let f=_o(n,`id`);return{url:`http://127.0.0.1:${d.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of o.values())e.dispose();o.clear(),f.dispose(),d.close()}}}function Zo({agent:e,capabilities:n,messages:r}){let[i,a]=(0,v.useState)(void 0),[o,s]=(0,v.useState)(!0),[c,l]=(0,v.useState)(void 0),u=(0,v.useRef)(c);(0,v.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,v.useState)(()=>t.lastUIOptions(r));(0,v.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,v.useState)(void 0),h=(0,v.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=(0,v.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))h(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);(0,v.useEffect)(()=>{if(!d&&!c){m(void 0);return}g()},[d,c,g]);let _=(0,v.useRef)(void 0),y=(0,v.useRef)(void 0);(0,v.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),_.current=void 0)},[e]),(0,v.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),_.current=void 0;return}let t=p?JSON.stringify(p):``;if(_.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),_.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,v.useCallback)((e,t)=>{g({[e]:t})},[g]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Qo(e){let t=(0,v.useRef)(e.onRequest);(0,v.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let n=(0,v.useRef)(e.id??crypto.randomUUID()),[r,i]=(0,v.useState)(`disconnected`);return(0,v.useEffect)(()=>{if(e.disabled){i(`disconnected`);return}let r=!1,a,o,s=!1,c=()=>{if(!(r||s)){if(s=!0,a){try{a.dispose()}catch{}a=void 0}a=new Cn({baseURL:`https://blink.so`}).devhook.listen({id:n.current,onRequest:async e=>t.current(e),onConnect:()=>{s=!1,i(`connected`)},onDisconnect:()=>{s=!1,i(`disconnected`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))},onError:e=>{s=!1,i(`error`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))}})}};return c(),()=>{if(r=!0,o&&=(clearTimeout(o),void 0),a){try{a.dispose()}catch{}a=void 0}}},[e.disabled]),{id:n.current,status:r}}var $o=e.__commonJSMin(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),es=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=$o().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
129
129
|
`);let r;for(;(r=f.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
|
|
130
|
-
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),ts=e.__toESM(es(),1);async function ns(e,t){let n=e;for(;n!==(0,r.dirname)(n);){let e=(0,r.join)(n,t);try{return await(0,o.stat)(e),e}catch{}n=(0,r.dirname)(n)}}function rs(e,t=`.env.local`){let[n,r]=(0,v.useState)({});return(0,v.useEffect)(()=>{let n,a=e=>{try{let t=(0,i.readFileSync)(e,`utf-8`),n=(0,ts.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return ns(e,t).then(e=>{if(!e){r({});return}a(e),n=(0,i.watch)(e,{persistent:!1},()=>{a(e)})}),()=>{n&&n.close()}},[e,t]),n}const os=(e,t)=>{let n=typeof e==`string`;typeof e==`string`&&(e=t.encode(e));let r=new Uint8Array(1+e.byteLength);return r[0]=n?0:1,r.set(new Uint8Array(e),1),r},ss=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1));let cs=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),ls=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({});const us={[cs.REQUEST]:b.z.string(),[cs.PROXY_INIT]:b.z.object({method:b.z.string(),headers:b.z.record(b.z.string(),b.z.string()),url:b.z.string()}),[cs.PROXY_BODY]:b.z.instanceof(Uint8Array),[cs.PROXY_WEBSOCKET_MESSAGE]:b.z.object({type:b.z.enum([`text`,`binary`]),data:b.z.instanceof(Uint8Array)}),[cs.PROXY_WEBSOCKET_CLOSE]:b.z.object({code:b.z.number().optional(),reason:b.z.string().optional()})},ds={[ls.RESPONSE]:b.z.string(),[ls.NOTIFICATION]:b.z.string(),[ls.PROXY_INIT]:b.z.object({status_code:b.z.number(),status_message:b.z.string(),headers:b.z.record(b.z.string(),b.z.string())}),[ls.PROXY_DATA]:b.z.instanceof(Uint8Array),[ls.PROXY_WEBSOCKET_MESSAGE]:b.z.instanceof(Uint8Array),[ls.PROXY_WEBSOCKET_CLOSE]:b.z.object({code:b.z.number(),reason:b.z.string()})},fs={[cs.PROXY_INIT]:{method:b.z.string(),headers:b.z.record(b.z.string(),b.z.string()),url:b.z.string()}},ps={process_execute:b.z.object({command:b.z.string(),args:b.z.array(b.z.string()),env_file:b.z.string().optional(),env:b.z.record(b.z.string(),b.z.string()).optional(),cwd:b.z.string().optional()}),process_send_input:b.z.object({pid:b.z.number(),data:b.z.string()}),process_wait:b.z.object({pid:b.z.number(),output_idle_timeout_ms:b.z.number().optional(),timeout_ms:b.z.number().optional()}),process_list:b.z.object({include_dead:b.z.boolean().optional()}),process_read_plain_output:b.z.object({pid:b.z.number(),start_line:b.z.number().optional(),end_line:b.z.number().optional()}),process_kill:b.z.object({pid:b.z.number(),signal:b.z.string().optional()}),set_env:b.z.object({env:b.z.record(b.z.string(),b.z.string())}),read_file:b.z.object({path:b.z.string(),line_start:b.z.number().optional(),line_end:b.z.number().optional()}),write_file:b.z.object({path:b.z.string(),content:b.z.string(),base64:b.z.boolean().optional(),mode:b.z.number().optional()}),read_directory:b.z.object({path:b.z.string()}),watch_directory:b.z.object({path:b.z.string()}),deploy_static_files:b.z.object({path:b.z.string()})},ms=b.z.object({pid:b.z.number(),command:b.z.string(),args:b.z.array(b.z.string()),title:b.z.string().optional(),cwd:b.z.string(),env:b.z.record(b.z.string(),b.z.string()),exit_code:b.z.number().optional(),exit_signal:b.z.number().optional(),duration_ms:b.z.number().optional(),output_total_lines:b.z.number()}),hs=ms.extend({ansi_output:b.z.string(),plain_output:b.z.object({lines:b.z.array(b.z.string()),total_lines:b.z.number()})}),gs={process_execute:b.z.object({pid:b.z.number()}),process_send_input:b.z.object({}),process_wait:hs,process_list:b.z.object({processes:b.z.array(ms)}),process_read_plain_output:b.z.object({lines:b.z.array(b.z.string()),total_lines:b.z.number(),duration_ms:b.z.number(),exit_code:b.z.number().optional(),exit_signal:b.z.number().optional()}),process_kill:b.z.object({}),set_env:b.z.object({}),read_file:b.z.object({total_lines:b.z.number(),lines_read:b.z.number(),start_line:b.z.number(),content:b.z.string(),mime_type:b.z.string()}),write_file:b.z.object({}),read_directory:b.z.object({entries:b.z.array(b.z.object({name:b.z.string(),type:b.z.enum([`file`,`directory`,`symlink`])}))}),watch_directory:b.z.object({}),deploy_static_files:b.z.object({deployment_id:b.z.string()})},_s=b.z.object({type:b.z.enum([`create`,`update`,`delete`]),path:b.z.string()}),vs=b.z.object({type:b.z.enum([`context`,`added`,`deleted`]),content:b.z.string(),oldLineNumber:b.z.number().optional(),newLineNumber:b.z.number().optional()}),ys=b.z.object({oldStart:b.z.number(),oldLines:b.z.number(),newStart:b.z.number(),newLines:b.z.number(),lines:b.z.array(vs)}),bs=b.z.object({path:b.z.string(),status:b.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:b.z.string().optional(),insertions:b.z.number(),deletions:b.z.number(),chunks:b.z.array(ys)}),xs=b.z.object({totalFiles:b.z.number(),totalInsertions:b.z.number(),totalDeletions:b.z.number(),netChange:b.z.number(),startHash:b.z.string().optional(),currentHash:b.z.string().optional(),timespan:b.z.number(),files:b.z.array(bs)}),Ss=b.z.object({path:b.z.string(),status:b.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:b.z.boolean()}),Cs=b.z.object({hash:b.z.string(),shortHash:b.z.string(),message:b.z.string(),author:b.z.string(),email:b.z.string(),date:b.z.date(),timestamp:b.z.date(),filesChanged:b.z.number(),insertions:b.z.number(),deletions:b.z.number(),commitDiff:b.z.array(bs).optional()}),ws=b.z.object({files:b.z.array(Ss),branch:b.z.string(),ahead:b.z.number(),behind:b.z.number(),timestamp:b.z.date(),sessionDiff:xs.optional(),workingDirectoryDiff:xs.optional(),newCommits:b.z.array(Cs),currentCommit:b.z.object({hash:b.z.string(),shortHash:b.z.string(),message:b.z.string(),author:b.z.string(),date:b.z.date()}).optional(),diffSkipped:b.z.boolean().optional(),payloadTruncated:b.z.boolean().optional(),estimatedSizeKB:b.z.number().optional()}),Ts=b.z.object({debounceDelay:b.z.number().optional(),gitStatusInterval:b.z.number().optional(),ignoreDotfiles:b.z.boolean().optional(),ignored:b.z.array(b.z.string()).optional(),watchGit:b.z.boolean().optional(),includeDiffs:b.z.boolean().optional(),maxDiffFiles:b.z.number().optional(),maxPayloadSizeKB:b.z.number().optional(),truncateLargeDiffs:b.z.boolean().optional()}),Es={process_status:b.z.object({status:ms}),process_output:b.z.object({pid:b.z.number(),output:b.z.string()}),file_change:b.z.object({changes:b.z.array(_s)}),git_status:ws};var Ds=class{notificationCallbacks=new Map;disposables=[];requestHandlers=new Map;send;jwt;requestTimeoutMS;constructor({send:e,jwt:t,requestTimeoutMS:n}){this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}},Os=e.__commonJSMin(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),ks=e.__commonJSMin(((e,t)=>{let{EMPTY_BUFFER:n}=Os(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),As=e.__commonJSMin(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),js=e.__commonJSMin(((e,t)=>{let n=require(`zlib`),r=ks(),i=As(),{kStatusCode:a}=Os(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!p){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;p=new i(e)}}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??(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(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw 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 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 Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),Ms=e.__commonJSMin(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=Os(),i=[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 a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),Ns=e.__commonJSMin(((e,t)=>{let{Writable:n}=require(`stream`),r=js(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Os(),{concat:c,toArrayBuffer:l,unmask:u}=ks(),{isValidStatusCode:d,isValidUTF8:f}=Ms(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=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=0}_write(e,t,n){if(this._opcode===8&&this._state==0)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 t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(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 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6: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){let t=this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`);e(t);return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(!this._fragmented){let t=this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let t=this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`);e(t);return}if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`);e(t);return}}else{let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){let t=this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`);e(t);return}}else if(this._masked){let t=this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`);e(t);return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2: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>2**21-1){let t=this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`);e(t);return}this._payloadLength=n*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=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;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&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let e=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);t(e);return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){let t=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);e(t);return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){let e=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);t(e);return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),Ps=e.__commonJSMin(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=js(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Os(),{isBlob:c,isValidStatusCode:l}=Ms(),{mask:u,toBuffer:d}=ks(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{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=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],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)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),Fs=e.__commonJSMin(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Os(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Is=e.__commonJSMin(((e,t)=>{let{tokenChars:n}=Ms();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),Ls=e.__commonJSMin(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=js(),p=Ns(),m=Ps(),{isBlob:h}=Ms(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=Os(),{EventTarget:{addEventListener:w,removeEventListener:T}}=Fs(),{format:E,parse:D}=Is(),{toBuffer:O}=ks(),k=Symbol(`kAborted`),A=[8,13],j=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),P(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.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(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,z),i.on(`drain`,B),i.on(`error`,V),i.on(`message`,U),i.on(`ping`,te),i.on(`pong`,W),a.onerror=G,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,K),t.on(`data`,ie),t.on(`end`,ae),t.on(`error`,oe),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){L(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),re(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||_,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||_,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||_,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){L(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),N.prototype.addEventListener=w,N.prototype.removeEventListener=T,t.exports=N;function P(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:A[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!A.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${A.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;F(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),_=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?ee:I),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=E({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!M.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{L(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[k]||(x=e._req=null,F(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){L(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{let t=SyntaxError(`Invalid URL: ${i}`);F(e,t);return}P(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||L(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){L(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+v).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){L(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){L(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){L(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=D(u)}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){L(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function F(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function I(e){return e.path=e.socketPath,a.connect(e)}function ee(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function L(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,L),t.setHeader?(t[k]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(F,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function R(e,t,n){if(t){let n=h(t)?t.size:O(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${j[e.readyState]})`);process.nextTick(n,t)}}function z(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,ie),process.nextTick(ne,n._socket),e===1005?n.close():n.close(e,t))}function B(){let e=this[S];e.isPaused||e._socket.resume()}function V(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,ie),process.nextTick(ne,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function H(){this[S].emitClose()}function U(e,t){this[S].emit(`message`,e,t)}function te(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function W(e){this[S].emit(`pong`,e)}function ne(e){e.resume()}function G(e){let t=this[S];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,re(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function re(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function K(){let e=this[S];this.removeListener(`close`,K),this.removeListener(`data`,ie),this.removeListener(`end`,ae),e._readyState=N.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,H),e._receiver.on(`finish`,H))}function ie(e){this[S]._receiver.write(e)||this.pause()}function ae(){let e=this[S];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function oe(){let e=this[S];this.removeListener(`error`,oe),this.on(`error`,C),e&&(e._readyState=N.CLOSING,this.destroy())}})),Rs=e.__commonJSMin(((e,t)=>{Ls();let{Duplex:n}=require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),zs=e.__commonJSMin(((e,t)=>{let{tokenChars:n}=Ms();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),Bs=e.__commonJSMin(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=Is(),s=js(),c=zs(),l=Ls(),{GUID:u,kWebSocket:d}=Os(),f=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=p(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(m,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,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(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,h);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){_(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){_(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!f.test(i)){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){g(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{_(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let p=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&p!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(p);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{_(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={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(a,(a,o,s,c)=>{if(!a)return g(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return g(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[d])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return g(i,503);let f=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+u).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(f.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});f.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,f,r),i.write(f.concat(`\r
|
|
130
|
+
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),ts=e.__toESM(es(),1);async function ns(e,t){let n=e;for(;n!==(0,d.dirname)(n);){let e=(0,d.join)(n,t);try{return await(0,g.stat)(e),e}catch{}n=(0,d.dirname)(n)}}function rs(e,t=`.env.local`){let[n,r]=(0,v.useState)({});return(0,v.useEffect)(()=>{let n,i=e=>{try{let t=(0,p.readFileSync)(e,`utf-8`),n=(0,ts.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return ns(e,t).then(e=>{if(!e){r({});return}i(e),n=(0,p.watch)(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}const os=(e,t)=>{let n=typeof e==`string`;typeof e==`string`&&(e=t.encode(e));let r=new Uint8Array(1+e.byteLength);return r[0]=n?0:1,r.set(new Uint8Array(e),1),r},ss=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1));let cs=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),ls=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({});const us={[cs.REQUEST]:b.z.string(),[cs.PROXY_INIT]:b.z.object({method:b.z.string(),headers:b.z.record(b.z.string(),b.z.string()),url:b.z.string()}),[cs.PROXY_BODY]:b.z.instanceof(Uint8Array),[cs.PROXY_WEBSOCKET_MESSAGE]:b.z.object({type:b.z.enum([`text`,`binary`]),data:b.z.instanceof(Uint8Array)}),[cs.PROXY_WEBSOCKET_CLOSE]:b.z.object({code:b.z.number().optional(),reason:b.z.string().optional()})},ds={[ls.RESPONSE]:b.z.string(),[ls.NOTIFICATION]:b.z.string(),[ls.PROXY_INIT]:b.z.object({status_code:b.z.number(),status_message:b.z.string(),headers:b.z.record(b.z.string(),b.z.string())}),[ls.PROXY_DATA]:b.z.instanceof(Uint8Array),[ls.PROXY_WEBSOCKET_MESSAGE]:b.z.instanceof(Uint8Array),[ls.PROXY_WEBSOCKET_CLOSE]:b.z.object({code:b.z.number(),reason:b.z.string()})},fs={[cs.PROXY_INIT]:{method:b.z.string(),headers:b.z.record(b.z.string(),b.z.string()),url:b.z.string()}},ps={process_execute:b.z.object({command:b.z.string(),args:b.z.array(b.z.string()),env_file:b.z.string().optional(),env:b.z.record(b.z.string(),b.z.string()).optional(),cwd:b.z.string().optional()}),process_send_input:b.z.object({pid:b.z.number(),data:b.z.string()}),process_wait:b.z.object({pid:b.z.number(),output_idle_timeout_ms:b.z.number().optional(),timeout_ms:b.z.number().optional()}),process_list:b.z.object({include_dead:b.z.boolean().optional()}),process_read_plain_output:b.z.object({pid:b.z.number(),start_line:b.z.number().optional(),end_line:b.z.number().optional()}),process_kill:b.z.object({pid:b.z.number(),signal:b.z.string().optional()}),set_env:b.z.object({env:b.z.record(b.z.string(),b.z.string())}),read_file:b.z.object({path:b.z.string(),line_start:b.z.number().optional(),line_end:b.z.number().optional()}),write_file:b.z.object({path:b.z.string(),content:b.z.string(),base64:b.z.boolean().optional(),mode:b.z.number().optional()}),read_directory:b.z.object({path:b.z.string()}),watch_directory:b.z.object({path:b.z.string()}),deploy_static_files:b.z.object({path:b.z.string()})},ms=b.z.object({pid:b.z.number(),command:b.z.string(),args:b.z.array(b.z.string()),title:b.z.string().optional(),cwd:b.z.string(),env:b.z.record(b.z.string(),b.z.string()),exit_code:b.z.number().optional(),exit_signal:b.z.number().optional(),duration_ms:b.z.number().optional(),output_total_lines:b.z.number()}),hs=ms.extend({ansi_output:b.z.string(),plain_output:b.z.object({lines:b.z.array(b.z.string()),total_lines:b.z.number()})}),gs={process_execute:b.z.object({pid:b.z.number()}),process_send_input:b.z.object({}),process_wait:hs,process_list:b.z.object({processes:b.z.array(ms)}),process_read_plain_output:b.z.object({lines:b.z.array(b.z.string()),total_lines:b.z.number(),duration_ms:b.z.number(),exit_code:b.z.number().optional(),exit_signal:b.z.number().optional()}),process_kill:b.z.object({}),set_env:b.z.object({}),read_file:b.z.object({total_lines:b.z.number(),lines_read:b.z.number(),start_line:b.z.number(),content:b.z.string(),mime_type:b.z.string()}),write_file:b.z.object({}),read_directory:b.z.object({entries:b.z.array(b.z.object({name:b.z.string(),type:b.z.enum([`file`,`directory`,`symlink`])}))}),watch_directory:b.z.object({}),deploy_static_files:b.z.object({deployment_id:b.z.string()})},_s=b.z.object({type:b.z.enum([`create`,`update`,`delete`]),path:b.z.string()}),vs=b.z.object({type:b.z.enum([`context`,`added`,`deleted`]),content:b.z.string(),oldLineNumber:b.z.number().optional(),newLineNumber:b.z.number().optional()}),ys=b.z.object({oldStart:b.z.number(),oldLines:b.z.number(),newStart:b.z.number(),newLines:b.z.number(),lines:b.z.array(vs)}),bs=b.z.object({path:b.z.string(),status:b.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:b.z.string().optional(),insertions:b.z.number(),deletions:b.z.number(),chunks:b.z.array(ys)}),xs=b.z.object({totalFiles:b.z.number(),totalInsertions:b.z.number(),totalDeletions:b.z.number(),netChange:b.z.number(),startHash:b.z.string().optional(),currentHash:b.z.string().optional(),timespan:b.z.number(),files:b.z.array(bs)}),Ss=b.z.object({path:b.z.string(),status:b.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:b.z.boolean()}),Cs=b.z.object({hash:b.z.string(),shortHash:b.z.string(),message:b.z.string(),author:b.z.string(),email:b.z.string(),date:b.z.date(),timestamp:b.z.date(),filesChanged:b.z.number(),insertions:b.z.number(),deletions:b.z.number(),commitDiff:b.z.array(bs).optional()}),ws=b.z.object({files:b.z.array(Ss),branch:b.z.string(),ahead:b.z.number(),behind:b.z.number(),timestamp:b.z.date(),sessionDiff:xs.optional(),workingDirectoryDiff:xs.optional(),newCommits:b.z.array(Cs),currentCommit:b.z.object({hash:b.z.string(),shortHash:b.z.string(),message:b.z.string(),author:b.z.string(),date:b.z.date()}).optional(),diffSkipped:b.z.boolean().optional(),payloadTruncated:b.z.boolean().optional(),estimatedSizeKB:b.z.number().optional()}),Ts=b.z.object({debounceDelay:b.z.number().optional(),gitStatusInterval:b.z.number().optional(),ignoreDotfiles:b.z.boolean().optional(),ignored:b.z.array(b.z.string()).optional(),watchGit:b.z.boolean().optional(),includeDiffs:b.z.boolean().optional(),maxDiffFiles:b.z.number().optional(),maxPayloadSizeKB:b.z.number().optional(),truncateLargeDiffs:b.z.boolean().optional()}),Es={process_status:b.z.object({status:ms}),process_output:b.z.object({pid:b.z.number(),output:b.z.string()}),file_change:b.z.object({changes:b.z.array(_s)}),git_status:ws};var Ds=class{notificationCallbacks=new Map;disposables=[];requestHandlers=new Map;send;jwt;requestTimeoutMS;constructor({send:e,jwt:t,requestTimeoutMS:n}){this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}},Os=e.__commonJSMin(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),ks=e.__commonJSMin(((e,t)=>{let{EMPTY_BUFFER:n}=Os(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=require(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),As=e.__commonJSMin(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),js=e.__commonJSMin(((e,t)=>{let n=require(`zlib`),r=ks(),i=As(),{kStatusCode:a}=Os(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!p){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;p=new i(e)}}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??(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(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw 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 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 Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),Ms=e.__commonJSMin(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=Os(),i=[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 a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),Ns=e.__commonJSMin(((e,t)=>{let{Writable:n}=require(`stream`),r=js(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Os(),{concat:c,toArrayBuffer:l,unmask:u}=ks(),{isValidStatusCode:d,isValidUTF8:f}=Ms(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=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=0}_write(e,t,n){if(this._opcode===8&&this._state==0)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 t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(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 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6: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){let t=this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`);e(t);return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(!this._fragmented){let t=this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let t=this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`);e(t);return}if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`);e(t);return}}else{let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){let t=this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`);e(t);return}}else if(this._masked){let t=this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`);e(t);return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2: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>2**21-1){let t=this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`);e(t);return}this._payloadLength=n*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=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;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&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let e=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);t(e);return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){let t=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);e(t);return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){let e=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);t(e);return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),Ps=e.__commonJSMin(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=js(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Os(),{isBlob:c,isValidStatusCode:l}=Ms(),{mask:u,toBuffer:d}=ks(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{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=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],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)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),Fs=e.__commonJSMin(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Os(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Is=e.__commonJSMin(((e,t)=>{let{tokenChars:n}=Ms();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),Ls=e.__commonJSMin(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=js(),p=Ns(),m=Ps(),{isBlob:h}=Ms(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=Os(),{EventTarget:{addEventListener:w,removeEventListener:T}}=Fs(),{format:E,parse:D}=Is(),{toBuffer:O}=ks(),k=Symbol(`kAborted`),A=[8,13],j=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),P(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.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(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,z),i.on(`drain`,B),i.on(`error`,V),i.on(`message`,U),i.on(`ping`,te),i.on(`pong`,W),a.onerror=G,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,K),t.on(`data`,ie),t.on(`end`,ae),t.on(`error`,oe),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){L(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),re(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||_,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||_,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||_,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){L(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),N.prototype.addEventListener=w,N.prototype.removeEventListener=T,t.exports=N;function P(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:A[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!A.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${A.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;F(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),_=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?ee:I),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=E({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!M.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{L(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[k]||(x=e._req=null,F(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){L(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{let t=SyntaxError(`Invalid URL: ${i}`);F(e,t);return}P(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||L(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){L(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+v).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){L(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){L(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){L(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=D(u)}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){L(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function F(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function I(e){return e.path=e.socketPath,a.connect(e)}function ee(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function L(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,L),t.setHeader?(t[k]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(F,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function R(e,t,n){if(t){let n=h(t)?t.size:O(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${j[e.readyState]})`);process.nextTick(n,t)}}function z(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,ie),process.nextTick(ne,n._socket),e===1005?n.close():n.close(e,t))}function B(){let e=this[S];e.isPaused||e._socket.resume()}function V(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,ie),process.nextTick(ne,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function H(){this[S].emitClose()}function U(e,t){this[S].emit(`message`,e,t)}function te(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function W(e){this[S].emit(`pong`,e)}function ne(e){e.resume()}function G(e){let t=this[S];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,re(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function re(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function K(){let e=this[S];this.removeListener(`close`,K),this.removeListener(`data`,ie),this.removeListener(`end`,ae),e._readyState=N.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,H),e._receiver.on(`finish`,H))}function ie(e){this[S]._receiver.write(e)||this.pause()}function ae(){let e=this[S];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function oe(){let e=this[S];this.removeListener(`error`,oe),this.on(`error`,C),e&&(e._readyState=N.CLOSING,this.destroy())}})),Rs=e.__commonJSMin(((e,t)=>{Ls();let{Duplex:n}=require(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),zs=e.__commonJSMin(((e,t)=>{let{tokenChars:n}=Ms();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),Bs=e.__commonJSMin(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=Is(),s=js(),c=zs(),l=Ls(),{GUID:u,kWebSocket:d}=Os(),f=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=p(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(m,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,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(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,h);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){_(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){_(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!f.test(i)){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){g(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{_(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let p=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&p!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(p);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{_(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={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(a,(a,o,s,c)=>{if(!a)return g(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return g(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[d])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return g(i,503);let f=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+u).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(f.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});f.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,f,r),i.write(f.concat(`\r
|
|
131
131
|
`).join(`\r
|
|
132
132
|
`)),i.removeListener(`error`,h),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(m,this)})),l(p,r)}};function p(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function m(e){e._state=2,e.emit(`close`)}function h(){this.destroy()}function g(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
|
|
133
133
|
`)+`\r
|
|
134
134
|
\r
|
|
135
|
-
`+n)}function _(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,_),e.emit(`wsClientError`,r,n,t)}else g(n,r,i,a)}})),Vs=e.__toESM(Rs(),1),Hs=e.__toESM(Ns(),1),Us=e.__toESM(Ps(),1),Ws=e.__toESM(Ls(),1),Gs=e.__toESM(Bs(),1),Ks=Object.create,qs=Object.defineProperty,Js=Object.getOwnPropertyDescriptor,Ys=Object.getOwnPropertyNames,Xs=Object.getPrototypeOf,Zs=Object.prototype.hasOwnProperty,Qs=(e,t)=>function(){return t||(0,e[Ys(e)[0]])((t={exports:{}}).exports,t),t.exports},$s=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ys(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Zs.call(e,s)&&s!==n&&qs(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Js(t,s))||r.enumerable});return e},ec=(e,t,n)=>(n=e==null?{}:Ks(Xs(e)),$s(t||!e||!e.__esModule?qs(n,`default`,{value:e,enumerable:!0}):n,e)),tc=(0,y.createRequire)(require(`url`).pathToFileURL(__filename).href),nc=class{listeners=[];get event(){return e=>(this.listeners.push(e),{dispose:()=>{this.listeners=this.listeners.filter(t=>t!==e)}})}emit(e){for(let t=this.listeners.length-1;t>=0;t--)this.listeners[t]?.(e)}dispose(){this.listeners=[]}};let rc=function(e){return e[e.DATA=0]=`DATA`,e[e.CLOSE=1]=`CLOSE`,e[e.ERROR=2]=`ERROR`,e}({}),ic=function(e){return e[e.NEW=1]=`NEW`,e}({});var ac=class{static MAX_POOL_SIZE=100;static COMMON_SIZES=[64,256,1024,4096,16384];static pools=new Map;static{for(let e of this.COMMON_SIZES)this.pools.set(e,[])}static acquire(e){for(let t of this.COMMON_SIZES)if(t>=e){let e=this.pools.get(t);if(e&&e.length>0)return e.pop();break}return new Uint8Array(e)}static release(e){let t=e.length;for(let n of this.COMMON_SIZES)if(n===t){let t=this.pools.get(n);t&&t.length<this.MAX_POOL_SIZE&&t.push(e);break}}},oc=class e{static HEADER_SIZE=4;static MAX_FRAME_SIZE=1024*1024-e.HEADER_SIZE;static encode(e){let t=e.payload.length;if(t>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${t} > ${this.MAX_FRAME_SIZE}`);let n=this.HEADER_SIZE+t,r=ac.acquire(n),i=e.streamId<<8|e.type<<4|e.flags&15;return r[0]=i>>>24&255,r[1]=i>>>16&255,r[2]=i>>>8&255,r[3]=i&255,t>0&&r.set(e.payload,this.HEADER_SIZE),r.length===n?r:r.subarray(0,n)}static encodeTyped(t,n,r,i,a){let o=1+a.length;if(o>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${o} > ${this.MAX_FRAME_SIZE}`);let s=this.HEADER_SIZE+o,c=ac.acquire(s),l=t<<8|n<<4|r&15;return c[0]=l>>>24&255,c[1]=l>>>16&255,c[2]=l>>>8&255,c[3]=l&255,c[e.HEADER_SIZE]=i&255,a.length>0&&c.set(a,e.HEADER_SIZE+1),c.length===s?c:c.subarray(0,s)}static decode(t){if(t.length<e.HEADER_SIZE)throw Error(`Invalid frame: too short (${t.length} < ${e.HEADER_SIZE})`);let n=t[0]<<24|t[1]<<16|t[2]<<8|t[3],r=n>>>8,i=n&255,a=i>>>4,o=i&15,s=t.length>e.HEADER_SIZE?t.subarray(e.HEADER_SIZE):new Uint8Array;return{streamId:r,type:a,flags:o,payload:s}}static releaseBuffer(e){ac.release(e)}static getMaxPayloadSize(){return e.MAX_FRAME_SIZE}},sc=class{_onData;_onClose;_onError;_disposed=!1;_id;constructor(e,t,n){this.send=t,this.sendTypedCb=n,this._id=e}get id(){return this._id}get onData(){return this._onData||=new nc,this._onData.event}get onClose(){return this._onClose||=new nc,this._onClose.event}get onError(){return this._onError||=new nc,this._onError.event}write(e,t=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let n=oc.getMaxPayloadSize();if(e.length<=n){this.send({streamId:this.id,type:rc.DATA,flags:t?ic.NEW:0,payload:e});return}let r=0,i=!0;for(;r<e.length;){let a=e.length-r,o=a>n?n:a,s=e.subarray(r,r+o);this.send({streamId:this.id,type:rc.DATA,flags:t&&i?ic.NEW:0,payload:s}),r+=o,i=!1}}writeTyped(e,t,n=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);if(!this.sendTypedCb){let r=new Uint8Array(1+t.length);r[0]=e&255,t.length&&r.set(t,1),this.write(r,n);return}let r=oc.getMaxPayloadSize()-1;if(t.length<=r){this.sendTypedCb(this.id,n?ic.NEW:0,e,t);return}let i=0,a=!0;for(;i<t.length;){let o=t.length-i,s=o>r?r:o,c=t.subarray(i,i+s);this.sendTypedCb(this.id,n&&a?ic.NEW:0,e,c),i+=s,a=!1}}close(){this._disposed||(this.send({streamId:this.id,type:rc.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(e){this._disposed||this.send({streamId:this.id,type:rc.ERROR,flags:0,payload:new TextEncoder().encode(e)})}_handleFrame(e){if(!this._disposed)switch(e.type){case rc.DATA:this._onData?.emit(e.payload);break;case rc.CLOSE:this._onClose?.emit(),this._dispose();break;case rc.ERROR:let t=new TextDecoder().decode(e.payload);this._onError?.emit(t),this._dispose();break}}_dispose(){this._disposed||(this._disposed=!0,this._onData?.dispose(),this._onClose?.dispose(),this._onError?.dispose(),this._onData=void 0,this._onClose=void 0,this._onError=void 0)}_reset(e,t,n){this._dispose(),this._id=e,this.send=t,this.sendTypedCb=n,this._disposed=!1}get createdByClient(){return this.id%2==1}get disposed(){return this._disposed}},cc=class{static MAX_POOL_SIZE=200;static pool=[];static acquire(e,t,n){let r=this.pool.pop();return r?(r._reset(e,t,n),r):new sc(e,t,n)}static release(e){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(e)}},lc=class{_onNextStreamIDChange=new nc;onNextStreamIDChange=this._onNextStreamIDChange.event;_onStream=new nc;onStream=this._onStream.event;streams=[];streamCount=0;nextStreamId=1;send;releaseAfterSend;constructor(e){this.nextStreamId=e.initialNextStreamID??(e.isClient?1:2),this.send=e.send,this.releaseAfterSend=!!e.releaseAfterSend}getStream(e){return this.streams[e]}createStream(e){e===void 0&&(e=this.nextStreamId,this.nextStreamId+=2,this._onNextStreamIDChange.emit(this.nextStreamId));let t=this.streams[e];if(t&&!t.disposed)throw Error(`Stream ${e} already exists`);let n=cc.acquire(e,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r));return this.streams[e]=n,this.streamCount++,n}sendFrame(e){let t=oc.encode(e);try{this.send(t)}finally{this.releaseAfterSend&&oc.releaseBuffer(t)}}sendFrameTyped(e,t,n,r){let i=oc.encodeTyped(e,rc.DATA,n,t,r);try{this.send(i)}finally{this.releaseAfterSend&&oc.releaseBuffer(i)}}handleMessage(e){this.handleFrame(oc.decode(e))}handleFrame(e){let t=this.streams[e.streamId];(!t||t.disposed)&&(t=cc.acquire(e.streamId,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r)),this.streams[e.streamId]=t,this.streamCount++,this._onStream.emit(t)),t._handleFrame(e),(e.type===rc.CLOSE||e.type===rc.ERROR)&&(this.streams[e.streamId]=void 0,this.streamCount--,cc.release(t))}get activeStreamCount(){return this.streamCount}dispose(){for(let e of this.streams)e&&!e.disposed&&(e.close(),cc.release(e));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}};const uc=`End-Of-Stream`;var dc=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},fc=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},pc=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new dc;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new fc;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new dc;return n}},mc=class extends pc{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},hc=class extends mc{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},gc=class extends pc{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new dc;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function _c(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new gc(t):new hc(t)}catch(t){if(t instanceof TypeError)return new gc(e.getReader());throw t}}var vc=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new dc;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new dc;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new dc;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new dc;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};const yc=256e3;var bc=class extends vc{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new dc;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof dc)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new dc}return r}async ignore(e){let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},xc=class extends vc{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new dc;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function Sc(e,t){let n=_c(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new bc(n,r)}function Cc(e,t){return new xc(e,t)}const wc={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},Tc={};for(let[e,t]of Object.entries(wc))Tc[t]=Number.parseInt(e);function Ec(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?Dc(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return Oc(e);case`ascii`:return kc(e);case`latin1`:case`iso-8859-1`:return Ac(e);case`windows-1252`:return jc(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function Dc(e){let t=``,n=0;for(;n<e.length;){let r=e[n++];if(r<128)t+=String.fromCharCode(r);else if(r<224){let i=e[n++]&63;t+=String.fromCharCode((r&31)<<6|i)}else if(r<240){let i=e[n++]&63,a=e[n++]&63;t+=String.fromCharCode((r&15)<<12|i<<6|a)}else{let i=e[n++]&63,a=e[n++]&63,o=e[n++]&63,s=(r&7)<<18|i<<12|a<<6|o;s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(s&1023))}}return t}function Oc(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function kc(e){return String.fromCharCode(...e.map(e=>e&127))}function Ac(e){return String.fromCharCode(...e)}function jc(e){let t=``;for(let n of e)n>=128&&n<=159&&wc[n]?t+=wc[n]:t+=String.fromCharCode(n);return t}function Mc(e){return new DataView(e.buffer,e.byteOffset)}const Nc={len:1,get(e,t){return Mc(e).getUint8(t)},put(e,t,n){return Mc(e).setUint8(t,n),t+1}},Pc={len:2,get(e,t){return Mc(e).getUint16(t,!0)},put(e,t,n){return Mc(e).setUint16(t,n,!0),t+2}},Fc={len:2,get(e,t){return Mc(e).getUint16(t)},put(e,t,n){return Mc(e).setUint16(t,n),t+2}},Ic={len:4,get(e,t){return Mc(e).getUint32(t,!0)},put(e,t,n){return Mc(e).setUint32(t,n,!0),t+4}},Lc={len:4,get(e,t){return Mc(e).getUint32(t)},put(e,t,n){return Mc(e).setUint32(t,n),t+4}},Rc={len:4,get(e,t){return Mc(e).getInt32(t)},put(e,t,n){return Mc(e).setInt32(t,n),t+4}},zc={len:8,get(e,t){return Mc(e).getBigUint64(t,!0)},put(e,t,n){return Mc(e).setBigUint64(t,n,!0),t+8}};var Bc=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return Ec(n,this.encoding)}},Vc=(0,a.createRequire)(`/`);try{Vc(`worker_threads`).Worker}catch{}var Hc=Uint8Array,Uc=Uint16Array,Wc=Int32Array,Gc=new Hc([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Kc=new Hc([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),qc=new Hc([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Jc=function(e,t){for(var n=new Uc(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Wc(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Yc=Jc(Gc,2),Xc=Yc.b,Zc=Yc.r;Xc[28]=258,Zc[258]=28;var Qc=Jc(Kc,0),$c=Qc.b;Qc.r;for(var el=new Uc(32768),tl=0;tl<32768;++tl){var nl=(tl&43690)>>1|(tl&21845)<<1;nl=(nl&52428)>>2|(nl&13107)<<2,nl=(nl&61680)>>4|(nl&3855)<<4,el[tl]=((nl&65280)>>8|(nl&255)<<8)>>1}for(var rl=(function(e,t,n){for(var r=e.length,i=0,a=new Uc(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Uc(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Uc(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[el[d]>>c]=l}else for(s=new Uc(r),i=0;i<r;++i)e[i]&&(s[i]=el[o[e[i]-1]++]>>15-e[i]);return s}),il=new Hc(288),tl=0;tl<144;++tl)il[tl]=8;for(var tl=144;tl<256;++tl)il[tl]=9;for(var tl=256;tl<280;++tl)il[tl]=7;for(var tl=280;tl<288;++tl)il[tl]=8;for(var al=new Hc(32),tl=0;tl<32;++tl)al[tl]=5;var ol=rl(il,9,1),sl=rl(al,5,1),cl=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},ll=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},ul=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},dl=function(e){return(e+7)/8|0},fl=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Hc(e.subarray(t,n))},pl=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],ml=function(e,t,n){var r=Error(t||pl[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,ml),!n)throw r;return r},hl=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new Hc(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new Hc(i*3));var l=function(e){var t=n.length;if(e>t){var r=new Hc(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=ll(e,d,1);var v=ll(e,d+1,3);if(d+=3,v)if(v==1)p=ol,m=sl,h=9,g=5;else if(v==2){var y=ll(e,d,31)+257,b=ll(e,d+10,15)+4,x=y+ll(e,d+5,31)+1;d+=14;for(var S=new Hc(x),C=new Hc(19),w=0;w<b;++w)C[qc[w]]=ll(e,d+w*3,7);d+=b*3;for(var T=cl(C),E=(1<<T)-1,D=rl(C,T,1),w=0;w<x;){var O=D[ll(e,d,E)];d+=O&15;var k=O>>4;if(k<16)S[w++]=k;else{var A=0,j=0;for(k==16?(j=3+ll(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+ll(e,d,7),d+=3):k==18&&(j=11+ll(e,d,127),d+=7);j--;)S[w++]=A}}var M=S.subarray(0,y),N=S.subarray(y);h=cl(M),g=cl(N),p=rl(M,h,1),m=rl(N,g,1)}else ml(1);else{var k=dl(d)+4,P=e[k-4]|e[k-3]<<8,F=k+P;if(F>i){c&&ml(0);break}s&&l(f+P),n.set(e.subarray(k,F),f),t.b=f+=P,t.p=d=F*8,t.f=u;continue}if(d>_){c&&ml(0);break}}s&&l(f+131072);for(var I=(1<<h)-1,ee=(1<<g)-1,L=d;;L=d){var A=p[ul(e,d)&I],R=A>>4;if(d+=A&15,d>_){c&&ml(0);break}if(A||ml(2),R<256)n[f++]=R;else if(R==256){L=d,p=null;break}else{var z=R-254;if(R>264){var w=R-257,B=Gc[w];z=ll(e,d,(1<<B)-1)+Xc[w],d+=B}var V=m[ul(e,d)&ee],H=V>>4;V||ml(3),d+=V&15;var N=$c[H];if(H>3){var B=Kc[H];N+=ul(e,d)&(1<<B)-1,d+=B}if(d>_){c&&ml(0);break}s&&l(f+131072);var U=f+z;if(f<N){var te=a-N,W=Math.min(N,U);for(te+f<0&&ml(3);f<W;++f)n[f]=r[te+f]}for(;f<U;++f)n[f]=n[f-N]}}t.l=p,t.p=L,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?fl(n,0,f):n.subarray(0,f)},gl=new Hc(0),_l=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&ml(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},vl=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},yl=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&ml(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&ml(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function bl(e,t){return hl(e,{i:2},t&&t.out,t&&t.dictionary)}function xl(e,t){var n=_l(e);return n+8>e.length&&ml(6,`invalid gzip data`),hl(e.subarray(n,-8),{i:2},t&&t.out||new Hc(vl(e)),t&&t.dictionary)}function Sl(e,t){return hl(e.subarray(yl(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function Cl(e,t){return e[0]==31&&e[1]==139&&e[2]==8?xl(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?bl(e,t):Sl(e,t)}var wl=typeof TextDecoder<`u`&&new TextDecoder;try{wl.decode(gl,{stream:!0})}catch{}var Tl=Qs({"../../node_modules/ms/index.js":((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})}),El=Qs({"../../node_modules/debug/src/common.js":((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Tl(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})}),Dl=Qs({"../../node_modules/debug/src/browser.js":((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=El()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),Ol=Qs({"../../node_modules/has-flag/index.js":((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})}),kl=Qs({"../../node_modules/supports-color/index.js":((e,t)=>{let n=tc(`os`),r=tc(`tty`),i=Ol(),{env:a}=process,o;i(`no-color`)||i(`no-colors`)||i(`color=false`)||i(`color=never`)?o=0:(i(`color`)||i(`colors`)||i(`color=true`)||i(`color=always`))&&(o=1);function s(){if(`FORCE_COLOR`in a)return a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(a.FORCE_COLOR,10),3)}function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let c=s();c!==void 0&&(o=c);let l=r?o:c;if(l===0)return 0;if(r){if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2}if(e&&!t&&l===void 0)return 0;let u=l||0;if(a.TERM===`dumb`)return u;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in a)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`,`DRONE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:u;if(`TEAMCITY_VERSION`in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in a){let e=Number.parseInt((a.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(a.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||`COLORTERM`in a?1:u}function u(e,t={}){let n=l(e,{streamIsTTY:e&&e.isTTY,...t});return c(n)}t.exports={supportsColor:u,stdout:u({isTTY:r.isatty(1)}),stderr:u({isTTY:r.isatty(2)})}})}),Al=Qs({"../../node_modules/debug/src/node.js":((e,t)=>{let n=tc(`tty`),r=tc(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=kl();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
135
|
+
`+n)}function _(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,_),e.emit(`wsClientError`,r,n,t)}else g(n,r,i,a)}})),Vs=e.__toESM(Rs(),1),Hs=e.__toESM(Ns(),1),Us=e.__toESM(Ps(),1),Ws=e.__toESM(Ls(),1),Gs=e.__toESM(Bs(),1),Ks=Object.create,qs=Object.defineProperty,Js=Object.getOwnPropertyDescriptor,Ys=Object.getOwnPropertyNames,Xs=Object.getPrototypeOf,Zs=Object.prototype.hasOwnProperty,Qs=(e,t)=>function(){return t||(0,e[Ys(e)[0]])((t={exports:{}}).exports,t),t.exports},$s=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ys(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Zs.call(e,s)&&s!==n&&qs(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Js(t,s))||r.enumerable});return e},ec=(e,t,n)=>(n=e==null?{}:Ks(Xs(e)),$s(t||!e||!e.__esModule?qs(n,`default`,{value:e,enumerable:!0}):n,e)),tc=(0,y.createRequire)(require(`url`).pathToFileURL(__filename).href),nc=class{listeners=[];get event(){return e=>(this.listeners.push(e),{dispose:()=>{this.listeners=this.listeners.filter(t=>t!==e)}})}emit(e){for(let t=this.listeners.length-1;t>=0;t--)this.listeners[t]?.(e)}dispose(){this.listeners=[]}};let rc=function(e){return e[e.DATA=0]=`DATA`,e[e.CLOSE=1]=`CLOSE`,e[e.ERROR=2]=`ERROR`,e}({}),ic=function(e){return e[e.NEW=1]=`NEW`,e}({});var ac=class{static MAX_POOL_SIZE=100;static COMMON_SIZES=[64,256,1024,4096,16384];static pools=new Map;static{for(let e of this.COMMON_SIZES)this.pools.set(e,[])}static acquire(e){for(let t of this.COMMON_SIZES)if(t>=e){let e=this.pools.get(t);if(e&&e.length>0)return e.pop();break}return new Uint8Array(e)}static release(e){let t=e.length;for(let n of this.COMMON_SIZES)if(n===t){let t=this.pools.get(n);t&&t.length<this.MAX_POOL_SIZE&&t.push(e);break}}},oc=class e{static HEADER_SIZE=4;static MAX_FRAME_SIZE=1024*1024-e.HEADER_SIZE;static encode(e){let t=e.payload.length;if(t>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${t} > ${this.MAX_FRAME_SIZE}`);let n=this.HEADER_SIZE+t,r=ac.acquire(n),i=e.streamId<<8|e.type<<4|e.flags&15;return r[0]=i>>>24&255,r[1]=i>>>16&255,r[2]=i>>>8&255,r[3]=i&255,t>0&&r.set(e.payload,this.HEADER_SIZE),r.length===n?r:r.subarray(0,n)}static encodeTyped(t,n,r,i,a){let o=1+a.length;if(o>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${o} > ${this.MAX_FRAME_SIZE}`);let s=this.HEADER_SIZE+o,c=ac.acquire(s),l=t<<8|n<<4|r&15;return c[0]=l>>>24&255,c[1]=l>>>16&255,c[2]=l>>>8&255,c[3]=l&255,c[e.HEADER_SIZE]=i&255,a.length>0&&c.set(a,e.HEADER_SIZE+1),c.length===s?c:c.subarray(0,s)}static decode(t){if(t.length<e.HEADER_SIZE)throw Error(`Invalid frame: too short (${t.length} < ${e.HEADER_SIZE})`);let n=t[0]<<24|t[1]<<16|t[2]<<8|t[3],r=n>>>8,i=n&255,a=i>>>4,o=i&15,s=t.length>e.HEADER_SIZE?t.subarray(e.HEADER_SIZE):new Uint8Array;return{streamId:r,type:a,flags:o,payload:s}}static releaseBuffer(e){ac.release(e)}static getMaxPayloadSize(){return e.MAX_FRAME_SIZE}},sc=class{_onData;_onClose;_onError;_disposed=!1;_id;constructor(e,t,n){this.send=t,this.sendTypedCb=n,this._id=e}get id(){return this._id}get onData(){return this._onData||=new nc,this._onData.event}get onClose(){return this._onClose||=new nc,this._onClose.event}get onError(){return this._onError||=new nc,this._onError.event}write(e,t=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let n=oc.getMaxPayloadSize();if(e.length<=n){this.send({streamId:this.id,type:rc.DATA,flags:t?ic.NEW:0,payload:e});return}let r=0,i=!0;for(;r<e.length;){let a=e.length-r,o=a>n?n:a,s=e.subarray(r,r+o);this.send({streamId:this.id,type:rc.DATA,flags:t&&i?ic.NEW:0,payload:s}),r+=o,i=!1}}writeTyped(e,t,n=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);if(!this.sendTypedCb){let r=new Uint8Array(1+t.length);r[0]=e&255,t.length&&r.set(t,1),this.write(r,n);return}let r=oc.getMaxPayloadSize()-1;if(t.length<=r){this.sendTypedCb(this.id,n?ic.NEW:0,e,t);return}let i=0,a=!0;for(;i<t.length;){let o=t.length-i,s=o>r?r:o,c=t.subarray(i,i+s);this.sendTypedCb(this.id,n&&a?ic.NEW:0,e,c),i+=s,a=!1}}close(){this._disposed||(this.send({streamId:this.id,type:rc.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(e){this._disposed||this.send({streamId:this.id,type:rc.ERROR,flags:0,payload:new TextEncoder().encode(e)})}_handleFrame(e){if(!this._disposed)switch(e.type){case rc.DATA:this._onData?.emit(e.payload);break;case rc.CLOSE:this._onClose?.emit(),this._dispose();break;case rc.ERROR:let t=new TextDecoder().decode(e.payload);this._onError?.emit(t),this._dispose();break}}_dispose(){this._disposed||(this._disposed=!0,this._onData?.dispose(),this._onClose?.dispose(),this._onError?.dispose(),this._onData=void 0,this._onClose=void 0,this._onError=void 0)}_reset(e,t,n){this._dispose(),this._id=e,this.send=t,this.sendTypedCb=n,this._disposed=!1}get createdByClient(){return this.id%2==1}get disposed(){return this._disposed}},cc=class{static MAX_POOL_SIZE=200;static pool=[];static acquire(e,t,n){let r=this.pool.pop();return r?(r._reset(e,t,n),r):new sc(e,t,n)}static release(e){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(e)}},lc=class{_onNextStreamIDChange=new nc;onNextStreamIDChange=this._onNextStreamIDChange.event;_onStream=new nc;onStream=this._onStream.event;streams=[];streamCount=0;nextStreamId=1;send;releaseAfterSend;constructor(e){this.nextStreamId=e.initialNextStreamID??(e.isClient?1:2),this.send=e.send,this.releaseAfterSend=!!e.releaseAfterSend}getStream(e){return this.streams[e]}createStream(e){e===void 0&&(e=this.nextStreamId,this.nextStreamId+=2,this._onNextStreamIDChange.emit(this.nextStreamId));let t=this.streams[e];if(t&&!t.disposed)throw Error(`Stream ${e} already exists`);let n=cc.acquire(e,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r));return this.streams[e]=n,this.streamCount++,n}sendFrame(e){let t=oc.encode(e);try{this.send(t)}finally{this.releaseAfterSend&&oc.releaseBuffer(t)}}sendFrameTyped(e,t,n,r){let i=oc.encodeTyped(e,rc.DATA,n,t,r);try{this.send(i)}finally{this.releaseAfterSend&&oc.releaseBuffer(i)}}handleMessage(e){this.handleFrame(oc.decode(e))}handleFrame(e){let t=this.streams[e.streamId];(!t||t.disposed)&&(t=cc.acquire(e.streamId,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r)),this.streams[e.streamId]=t,this.streamCount++,this._onStream.emit(t)),t._handleFrame(e),(e.type===rc.CLOSE||e.type===rc.ERROR)&&(this.streams[e.streamId]=void 0,this.streamCount--,cc.release(t))}get activeStreamCount(){return this.streamCount}dispose(){for(let e of this.streams)e&&!e.disposed&&(e.close(),cc.release(e));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}};const uc=`End-Of-Stream`;var dc=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},fc=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},pc=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new dc;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new fc;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new dc;return n}},mc=class extends pc{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},hc=class extends mc{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},gc=class extends pc{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new dc;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function _c(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new gc(t):new hc(t)}catch(t){if(t instanceof TypeError)return new gc(e.getReader());throw t}}var vc=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new dc;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new dc;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new dc;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new dc;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};const yc=256e3;var bc=class extends vc{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new dc;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof dc)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new dc}return r}async ignore(e){let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},xc=class extends vc{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new dc;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function Sc(e,t){let n=_c(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new bc(n,r)}function Cc(e,t){return new xc(e,t)}const wc={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},Tc={};for(let[e,t]of Object.entries(wc))Tc[t]=Number.parseInt(e);function Ec(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?Dc(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return Oc(e);case`ascii`:return kc(e);case`latin1`:case`iso-8859-1`:return Ac(e);case`windows-1252`:return jc(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function Dc(e){let t=``,n=0;for(;n<e.length;){let r=e[n++];if(r<128)t+=String.fromCharCode(r);else if(r<224){let i=e[n++]&63;t+=String.fromCharCode((r&31)<<6|i)}else if(r<240){let i=e[n++]&63,a=e[n++]&63;t+=String.fromCharCode((r&15)<<12|i<<6|a)}else{let i=e[n++]&63,a=e[n++]&63,o=e[n++]&63,s=(r&7)<<18|i<<12|a<<6|o;s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(s&1023))}}return t}function Oc(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function kc(e){return String.fromCharCode(...e.map(e=>e&127))}function Ac(e){return String.fromCharCode(...e)}function jc(e){let t=``;for(let n of e)n>=128&&n<=159&&wc[n]?t+=wc[n]:t+=String.fromCharCode(n);return t}function Mc(e){return new DataView(e.buffer,e.byteOffset)}const Nc={len:1,get(e,t){return Mc(e).getUint8(t)},put(e,t,n){return Mc(e).setUint8(t,n),t+1}},Pc={len:2,get(e,t){return Mc(e).getUint16(t,!0)},put(e,t,n){return Mc(e).setUint16(t,n,!0),t+2}},Fc={len:2,get(e,t){return Mc(e).getUint16(t)},put(e,t,n){return Mc(e).setUint16(t,n),t+2}},Ic={len:4,get(e,t){return Mc(e).getUint32(t,!0)},put(e,t,n){return Mc(e).setUint32(t,n,!0),t+4}},Lc={len:4,get(e,t){return Mc(e).getUint32(t)},put(e,t,n){return Mc(e).setUint32(t,n),t+4}},Rc={len:4,get(e,t){return Mc(e).getInt32(t)},put(e,t,n){return Mc(e).setInt32(t,n),t+4}},zc={len:8,get(e,t){return Mc(e).getBigUint64(t,!0)},put(e,t,n){return Mc(e).setBigUint64(t,n,!0),t+8}};var Bc=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return Ec(n,this.encoding)}},Vc=(0,f.createRequire)(`/`);try{Vc(`worker_threads`).Worker}catch{}var Hc=Uint8Array,Uc=Uint16Array,Wc=Int32Array,Gc=new Hc([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Kc=new Hc([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),qc=new Hc([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Jc=function(e,t){for(var n=new Uc(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Wc(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Yc=Jc(Gc,2),Xc=Yc.b,Zc=Yc.r;Xc[28]=258,Zc[258]=28;var Qc=Jc(Kc,0),$c=Qc.b;Qc.r;for(var el=new Uc(32768),tl=0;tl<32768;++tl){var nl=(tl&43690)>>1|(tl&21845)<<1;nl=(nl&52428)>>2|(nl&13107)<<2,nl=(nl&61680)>>4|(nl&3855)<<4,el[tl]=((nl&65280)>>8|(nl&255)<<8)>>1}for(var rl=(function(e,t,n){for(var r=e.length,i=0,a=new Uc(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Uc(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Uc(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[el[d]>>c]=l}else for(s=new Uc(r),i=0;i<r;++i)e[i]&&(s[i]=el[o[e[i]-1]++]>>15-e[i]);return s}),il=new Hc(288),tl=0;tl<144;++tl)il[tl]=8;for(var tl=144;tl<256;++tl)il[tl]=9;for(var tl=256;tl<280;++tl)il[tl]=7;for(var tl=280;tl<288;++tl)il[tl]=8;for(var al=new Hc(32),tl=0;tl<32;++tl)al[tl]=5;var ol=rl(il,9,1),sl=rl(al,5,1),cl=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},ll=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},ul=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},dl=function(e){return(e+7)/8|0},fl=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Hc(e.subarray(t,n))},pl=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],ml=function(e,t,n){var r=Error(t||pl[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,ml),!n)throw r;return r},hl=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new Hc(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new Hc(i*3));var l=function(e){var t=n.length;if(e>t){var r=new Hc(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=ll(e,d,1);var v=ll(e,d+1,3);if(d+=3,v)if(v==1)p=ol,m=sl,h=9,g=5;else if(v==2){var y=ll(e,d,31)+257,b=ll(e,d+10,15)+4,x=y+ll(e,d+5,31)+1;d+=14;for(var S=new Hc(x),C=new Hc(19),w=0;w<b;++w)C[qc[w]]=ll(e,d+w*3,7);d+=b*3;for(var T=cl(C),E=(1<<T)-1,D=rl(C,T,1),w=0;w<x;){var O=D[ll(e,d,E)];d+=O&15;var k=O>>4;if(k<16)S[w++]=k;else{var A=0,j=0;for(k==16?(j=3+ll(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+ll(e,d,7),d+=3):k==18&&(j=11+ll(e,d,127),d+=7);j--;)S[w++]=A}}var M=S.subarray(0,y),N=S.subarray(y);h=cl(M),g=cl(N),p=rl(M,h,1),m=rl(N,g,1)}else ml(1);else{var k=dl(d)+4,P=e[k-4]|e[k-3]<<8,F=k+P;if(F>i){c&&ml(0);break}s&&l(f+P),n.set(e.subarray(k,F),f),t.b=f+=P,t.p=d=F*8,t.f=u;continue}if(d>_){c&&ml(0);break}}s&&l(f+131072);for(var I=(1<<h)-1,ee=(1<<g)-1,L=d;;L=d){var A=p[ul(e,d)&I],R=A>>4;if(d+=A&15,d>_){c&&ml(0);break}if(A||ml(2),R<256)n[f++]=R;else if(R==256){L=d,p=null;break}else{var z=R-254;if(R>264){var w=R-257,B=Gc[w];z=ll(e,d,(1<<B)-1)+Xc[w],d+=B}var V=m[ul(e,d)&ee],H=V>>4;V||ml(3),d+=V&15;var N=$c[H];if(H>3){var B=Kc[H];N+=ul(e,d)&(1<<B)-1,d+=B}if(d>_){c&&ml(0);break}s&&l(f+131072);var U=f+z;if(f<N){var te=a-N,W=Math.min(N,U);for(te+f<0&&ml(3);f<W;++f)n[f]=r[te+f]}for(;f<U;++f)n[f]=n[f-N]}}t.l=p,t.p=L,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?fl(n,0,f):n.subarray(0,f)},gl=new Hc(0),_l=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&ml(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},vl=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},yl=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&ml(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&ml(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function bl(e,t){return hl(e,{i:2},t&&t.out,t&&t.dictionary)}function xl(e,t){var n=_l(e);return n+8>e.length&&ml(6,`invalid gzip data`),hl(e.subarray(n,-8),{i:2},t&&t.out||new Hc(vl(e)),t&&t.dictionary)}function Sl(e,t){return hl(e.subarray(yl(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function Cl(e,t){return e[0]==31&&e[1]==139&&e[2]==8?xl(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?bl(e,t):Sl(e,t)}var wl=typeof TextDecoder<`u`&&new TextDecoder;try{wl.decode(gl,{stream:!0})}catch{}var Tl=Qs({"../../node_modules/ms/index.js":((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})}),El=Qs({"../../node_modules/debug/src/common.js":((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Tl(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})}),Dl=Qs({"../../node_modules/debug/src/browser.js":((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=El()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),Ol=Qs({"../../node_modules/has-flag/index.js":((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})}),kl=Qs({"../../node_modules/supports-color/index.js":((e,t)=>{let n=tc(`os`),r=tc(`tty`),i=Ol(),{env:a}=process,o;i(`no-color`)||i(`no-colors`)||i(`color=false`)||i(`color=never`)?o=0:(i(`color`)||i(`colors`)||i(`color=true`)||i(`color=always`))&&(o=1);function s(){if(`FORCE_COLOR`in a)return a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(a.FORCE_COLOR,10),3)}function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let c=s();c!==void 0&&(o=c);let l=r?o:c;if(l===0)return 0;if(r){if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2}if(e&&!t&&l===void 0)return 0;let u=l||0;if(a.TERM===`dumb`)return u;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in a)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`,`DRONE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:u;if(`TEAMCITY_VERSION`in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in a){let e=Number.parseInt((a.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(a.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||`COLORTERM`in a?1:u}function u(e,t={}){let n=l(e,{streamIsTTY:e&&e.isTTY,...t});return c(n)}t.exports={supportsColor:u,stdout:u({isTTY:r.isatty(1)}),stderr:u({isTTY:r.isatty(2)})}})}),Al=Qs({"../../node_modules/debug/src/node.js":((e,t)=>{let n=tc(`tty`),r=tc(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=kl();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
136
136
|
`).join(`
|
|
137
137
|
`+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=o()+n+` `+e[0]}function o(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function s(...t){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...t)+`
|
|
138
138
|
`)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=El()(e);let{formatters:d}=t.exports;d.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split(`
|
|
@@ -143,11 +143,11 @@ ${Zi}${t.trimStart()}`),n=3+(0,f.stripVTControlCharacters)(t.trimStart()).length
|
|
|
143
143
|
`,t)}reset(){this._core.reset()}loadAddon(e){this._addonManager.loadAddon(this,e)}_verifyIntegers(...e){for(let t of e)if(t===1/0||isNaN(t)||t%1!=0)throw Error(`This API only accepts integers`)}}e.Terminal=u})();var a=e;for(var o in i)a[o]=i[o];i.__esModule&&Object.defineProperty(a,`__esModule`,{value:!0})})()})}),ru=ec(tu(),1),iu=ec(nu(),1),au=class e{static COLUMNS=80;static ROWS=24;static SCROLLBACK=128e3;globalEnv;processes=new Map;spawnListeners=[];nodePty;constructor(e){this.globalEnv=e?.env??{},this.nodePty=e?.nodePty}onSpawn(e){return this.spawnListeners.push(e),{dispose:()=>{this.spawnListeners=this.spawnListeners.filter(t=>t!==e)}}}setEnv(e){this.globalEnv={...this.globalEnv,...e},Object.keys(e).forEach(t=>{e[t]===``&&delete this.globalEnv[t]})}async execute(t,n,r){let i=await ou(t,n,{name:`xterm-256color`,cols:e.COLUMNS,rows:e.ROWS,cwd:r?.cwd,env:{...globalThis.process.env,...this.globalEnv,...r?.env}},this.nodePty),a=new iu.default.Terminal({allowProposedApi:!0,convertEol:!0,scrollback:e.SCROLLBACK,cols:e.COLUMNS,rows:e.ROWS}),o=new ru.SerializeAddon;a.loadAddon(o);let s;i.onData(e=>{s=new Promise(t=>{a.write(e,t)})}),a.onData(e=>{i.write(e)});let c={command:t,args:n,cwd:r?.cwd??``,env:{...r?.env},startTimeMS:Date.now(),exitCode:void 0,exitSignal:void 0,pid:i.pid,pty:i,terminal:a,serializer:o,kill:e=>{i.kill(e)},onExit:e=>i.onExit(({exitCode:t,signal:n})=>{s?s.then(()=>{e(t,n)}):e(t,n)}),onOutput:e=>i.onData(t=>{e(t)}),sendInput:e=>{a.input(e)}};this.processes.set(i.pid,c),i.onExit(({exitCode:e,signal:t})=>{c.exitCode=e,c.exitSignal=t});for(let e of this.spawnListeners)e(c);return c}status(e){let t=this.processes.get(e);if(!t)throw Error(`Process with PID ${e} not found`);let n=this.readPlainOutput(e);return{pid:t.pid,command:t.command,title:t.pty.process,args:t.args,cwd:t.cwd,env:t.env,exit_code:t.exitCode,exit_signal:t.exitSignal,duration_ms:Date.now()-t.startTimeMS,output_total_lines:n.totalLines}}list(e){return Array.from(this.processes.values()).filter(t=>e||t.exitCode===void 0).map(e=>this.status(e.pid))}getProcess(e){return this.processes.get(e)}readANSIOutput(e,t){let n=this.processes.get(e);if(!n)throw Error(`Process with PID ${e} not found`);return n.serializer.serialize({scrollback:t})}readPlainOutput(t,n,r){let i=n?Math.max(0,n-1):0,a=r?Math.max(0,r-1):e.SCROLLBACK+e.ROWS-1,o=this.processes.get(t);if(!o)throw Error(`Process with PID ${t} not found`);let s=[];for(let t=0;t<e.SCROLLBACK+e.ROWS;t++){let e=o.terminal.buffer.normal.getLine(t);e&&s.push(e.translateToString(!0)??``)}for(;s.length>0&&s[s.length-1].trim()===``;)s.pop();return{lines:s.slice(i,a+1),totalLines:s.length}}close(){this.processes.forEach(e=>{e.pty.kill()})}};const ou=async(e,t,n,r)=>{if(!r||globalThis.Bun!==void 0){let r=new nc,i=new nc,a=(0,_.spawn)(e,t,{env:n.env,cwd:n.cwd,stdio:`pipe`});return a.stdout.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.stderr.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.on(`exit`,(e,t)=>{let n=e??-1,i=t?n:void 0;r.emit({exitCode:n,signal:i})}),{pid:await new Promise((e,t)=>{a.on(`spawn`,()=>{e(a.pid??-1)}),a.on(`error`,e=>{t(e)})}),process:``,onExit:e=>r.event(e),kill(e){a.kill(e)},onData:e=>i.event(e),write(e){a.stdin?.write(e)}}}return r.spawn(e,t,n)};var su=Qs({"../../node_modules/events-universal/default.js":((e,t)=>{t.exports=tc(`events`)})}),cu=Qs({"../../node_modules/fast-fifo/fixed-size.js":((e,t)=>{t.exports=class{constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return this.buffer[this.top]===void 0?(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0):!1}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}})}),lu=Qs({"../../node_modules/fast-fifo/index.js":((e,t)=>{let n=cu();t.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){let t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){this.length!==0&&this.length--;let e=this.tail.shift();if(e===void 0&&this.tail.next){let e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){let e=this.tail.peek();return e===void 0&&this.tail.next?this.tail.next.peek():e}isEmpty(){return this.length===0}}})}),uu=Qs({"../../node_modules/b4a/index.js":((e,t)=>{function n(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function r(e){return Buffer.isEncoding(e)}function i(e,t,n){return Buffer.alloc(e,t,n)}function a(e){return Buffer.allocUnsafe(e)}function o(e){return Buffer.allocUnsafeSlow(e)}function s(e,t){return Buffer.byteLength(e,t)}function c(e,t){return Buffer.compare(e,t)}function l(e,t){return Buffer.concat(e,t)}function u(e,t,n,r,i){return b(e).copy(t,n,r,i)}function d(e,t){return b(e).equals(t)}function f(e,t,n,r,i){return b(e).fill(t,n,r,i)}function p(e,t,n){return Buffer.from(e,t,n)}function m(e,t,n,r){return b(e).includes(t,n,r)}function h(e,t,n,r){return b(e).indexOf(t,n,r)}function g(e,t,n,r){return b(e).lastIndexOf(t,n,r)}function _(e){return b(e).swap16()}function v(e){return b(e).swap32()}function y(e){return b(e).swap64()}function b(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function x(e,t,n,r){return b(e).toString(t,n,r)}function S(e,t,n,r,i){return b(e).write(t,n,r,i)}function C(e,t){return b(e).readDoubleBE(t)}function w(e,t){return b(e).readDoubleLE(t)}function T(e,t){return b(e).readFloatBE(t)}function E(e,t){return b(e).readFloatLE(t)}function D(e,t){return b(e).readInt32BE(t)}function O(e,t){return b(e).readInt32LE(t)}function k(e,t){return b(e).readUInt32BE(t)}function A(e,t){return b(e).readUInt32LE(t)}function j(e,t,n){return b(e).writeDoubleBE(t,n)}function M(e,t,n){return b(e).writeDoubleLE(t,n)}function N(e,t,n){return b(e).writeFloatBE(t,n)}function P(e,t,n){return b(e).writeFloatLE(t,n)}function F(e,t,n){return b(e).writeInt32BE(t,n)}function I(e,t,n){return b(e).writeInt32LE(t,n)}function ee(e,t,n){return b(e).writeUInt32BE(t,n)}function L(e,t,n){return b(e).writeUInt32LE(t,n)}t.exports={isBuffer:n,isEncoding:r,alloc:i,allocUnsafe:a,allocUnsafeSlow:o,byteLength:s,compare:c,concat:l,copy:u,equals:d,fill:f,from:p,includes:m,indexOf:h,lastIndexOf:g,swap16:_,swap32:v,swap64:y,toBuffer:b,toString:x,write:S,readDoubleBE:C,readDoubleLE:w,readFloatBE:T,readFloatLE:E,readInt32BE:D,readInt32LE:O,readUInt32BE:k,readUInt32LE:A,writeDoubleBE:j,writeDoubleLE:M,writeFloatBE:N,writeFloatLE:P,writeInt32BE:F,writeInt32LE:I,writeUInt32BE:ee,writeUInt32LE:L}})}),du=Qs({"../../node_modules/text-decoder/lib/pass-through-decoder.js":((e,t)=>{let n=uu();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})}),fu=Qs({"../../node_modules/text-decoder/lib/utf8-decoder.js":((e,t)=>{let n=uu();t.exports=class{constructor(){this.codePoint=0,this.bytesSeen=0,this.bytesNeeded=0,this.lowerBoundary=128,this.upperBoundary=191}get remaining(){return this.bytesSeen}decode(e){if(this.bytesNeeded===0){let t=!0;for(let n=Math.max(0,e.byteLength-4),r=e.byteLength;n<r&&t;n++)t=e[n]<=127;if(t)return n.toString(e,`utf8`)}let t=``;for(let n=0,r=e.byteLength;n<r;n++){let r=e[n];if(this.bytesNeeded===0){r<=127?t+=String.fromCharCode(r):(this.bytesSeen=1,r>=194&&r<=223?(this.bytesNeeded=2,this.codePoint=r&31):r>=224&&r<=239?(r===224?this.lowerBoundary=160:r===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.codePoint=r&15):r>=240&&r<=244?(r===240&&(this.lowerBoundary=144),r===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.codePoint=r&7):t+=`�`);continue}if(r<this.lowerBoundary||r>this.upperBoundary){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,t+=`�`;continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|r&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0)}return t}flush(){let e=this.bytesNeeded>0?`�`:``;return this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,e}}})}),pu=Qs({"../../node_modules/text-decoder/index.js":((e,t)=>{let n=du(),r=fu();t.exports=class{constructor(e=`utf8`){switch(this.encoding=i(e),this.encoding){case`utf8`:this.decoder=new r;break;case`utf16le`:case`base64`:throw Error(`Unsupported encoding: `+this.encoding);default:this.decoder=new n(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return typeof e==`string`?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t=``;return e&&(t=this.push(e)),t+=this.decoder.flush(),t}};function i(e){switch(e=e.toLowerCase(),e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:throw Error(`Unknown encoding: `+e)}}})}),mu=Qs({"../../node_modules/streamx/index.js":((e,t)=>{let{EventEmitter:n}=su(),r=Error(`Stream was destroyed`),i=Error(`Premature close`),a=lu(),o=pu(),s=typeof queueMicrotask>`u`?e=>global.process.nextTick(e):queueMicrotask,c=(1<<29)-1,l=c^1;c^2;let u=1024,d=2048,f=4096,p=8192,m=16384,h=32768,g=65536,_=131072;16|g,f|128;let v=256|_;c^16,c^64,c^(64|g);let y=c^g;c^256,c^(128|p),c^u;let b=c^768,x=c^h;c^32;let S=c^_;c^v;let C=1<<18,w=2<<18,T=4<<18,E=8<<18,D=16<<18,O=32<<18,k=64<<18,A=128<<18,j=256<<18,M=512<<18,N=1024<<18;c^(C|j);let P=c^T;c^(C|M),c^D,c^E;let F=c^A;c^w;let I=c^N,ee=16|C,L=c^ee,R=m|O,z=14|R;P&536870847;let B=A|h;B&L;let V=33587215;u|16399;let H=m|143;u|143,u|16398,h|1,M|8388623,E|D,E|C;let U=270794767;T|C,C|j,O|134217742;let te=Symbol.asyncIterator||Symbol(`asyncIterator`);var W=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:r,byteLength:i,byteLengthWritable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||i||Ae,this.map=r||n,this.afterWrite=oe.bind(this),this.afterUpdateNextTick=le.bind(this)}get ended(){return(this.stream._duplexState&O)!==0}push(e){return this.stream._duplexState&142606350?!1:(this.map!==null&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=E,!0):(this.stream._duplexState|=6291456,!1))}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=534773759),e}end(e){typeof e==`function`?this.stream.once(`finish`,e):e!=null&&this.push(e),this.stream._duplexState=(this.stream._duplexState|M)&P}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&U)===2359296;)n.push(r._writableState.shift());if(r._duplexState&15)return t(null);r._writev(n,t)}update(){let e=this.stream;e._duplexState|=w;do{for(;(e._duplexState&U)===E;){let t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}e._duplexState&1310720||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536346623}updateNonPrimary(){let e=this.stream;if((e._duplexState&144965647)===M){e._duplexState|=C,e._final(ie.bind(this));return}if((e._duplexState&14)==4){(e._duplexState&B)===0&&(e._duplexState|=ee,e._destroy(ae.bind(this)));return}(e._duplexState&V)===1&&(e._duplexState=(e._duplexState|ee)&l,e._open(de.bind(this)))}continueUpdate(){return(this.stream._duplexState&A)===0?!1:(this.stream._duplexState&=F,!0)}updateCallback(){(this.stream._duplexState&35127311)===T?this.update():this.updateNextTick()}updateNextTick(){(this.stream._duplexState&A)===0&&(this.stream._duplexState|=A,(this.stream._duplexState&w)===0&&s(this.afterUpdateNextTick))}},ne=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:r,byteLength:i,byteLengthReadable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||i||Ae,this.map=r||n,this.pipeTo=null,this.afterRead=se.bind(this),this.afterUpdateNextTick=ce.bind(this)}get ended(){return(this.stream._duplexState&m)!==0}pipe(e,t){if(this.pipeTo!==null)throw Error(`Can only pipe to one destination`);if(typeof t!=`function`&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new re(this.stream,e,t),t&&this.stream.on(`error`,je),we(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,je),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,K.bind(this)),this.stream.emit(`piping`,e),e.emit(`pipe`,this.stream)}push(e){let t=this.stream;return e===null?(this.highWaterMark=0,t._duplexState=(t._duplexState|u)&536805311,!1):this.map!==null&&(e=this.map(e),e===null)?(t._duplexState&=y,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|128)&y,this.buffered<this.highWaterMark)}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=536862591),e}unshift(e){let t=[this.map===null?e:this.map(e)];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){let n=t[e];this.buffered+=this.byteLength(n),this.queue.push(n)}this.push(t[t.length-1])}read(){let e=this.stream;if((e._duplexState&H)===128){let t=this.shift();return this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t),t}return this.readAhead===!1&&(e._duplexState|=_,this.updateNextTick()),null}drain(){let e=this.stream;for(;(e._duplexState&H)===128&&e._duplexState&768;){let t=this.shift();this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t)}}update(){let e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(e._duplexState&214047)===_;)e._duplexState|=65552,e._read(this.afterRead),this.drain();(e._duplexState&12431)==4224&&(e._duplexState|=p,e.emit(`readable`)),e._duplexState&80||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536870879}updateNonPrimary(){let e=this.stream;if((e._duplexState&1167)===u&&(e._duplexState=(e._duplexState|m)&536869887,e.emit(`end`),(e._duplexState&z)===R&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){(e._duplexState&B)===0&&(e._duplexState|=ee,e._destroy(ae.bind(this)));return}(e._duplexState&V)===1&&(e._duplexState=(e._duplexState|ee)&l,e._open(de.bind(this)))}continueUpdate(){return(this.stream._duplexState&h)===0?!1:(this.stream._duplexState&=x,!0)}updateCallback(){(this.stream._duplexState&32879)==64?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&32769||(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}updateNextTick(){(this.stream._duplexState&h)===0&&(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}},G=class{constructor(e){this.data=null,this.afterTransform=fe.bind(e),this.afterFinal=null}},re=class{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){if(t&&(this.error=t),e===this.to&&(this.to=null,this.from!==null)){((this.from._duplexState&m)===0||!this.pipeToFinished)&&this.from.destroy(this.error||Error(`Writable stream closed prematurely`));return}if(e===this.from&&(this.from=null,this.to!==null)){(e._duplexState&m)===0&&this.to.destroy(this.error||Error(`Readable stream closed before ending`));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function K(){this.stream._duplexState|=512,this.updateCallback()}function ie(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=O,t.emit(`finish`)),(t._duplexState&z)===R&&(t._duplexState|=4),t._duplexState&=402391039,(t._duplexState&w)===0?this.update():this.updateNextTick()}function ae(e){let t=this.stream;!e&&this.error!==r&&(e=this.error),e&&t.emit(`error`,e),t._duplexState|=8,t.emit(`close`);let n=t._readableState,i=t._writableState;if(n!==null&&n.pipeline!==null&&n.pipeline.done(t,e),i!==null){for(;i.drains!==null&&i.drains.length>0;)i.drains.shift().resolve(!1);i.pipeline!==null&&i.pipeline.done(t,e)}}function oe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&ue(this.drains),(t._duplexState&6553615)===D&&(t._duplexState&=532676607,(t._duplexState&k)===k&&t.emit(`drain`)),this.updateCallback()}function se(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=S),this.updateCallback()}function ce(){this.stream._duplexState&32||(this.stream._duplexState&=x,this.update())}function le(){(this.stream._duplexState&w)===0&&(this.stream._duplexState&=F,this.update())}function ue(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function de(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=T),t.emit(`open`)),t._duplexState&=L,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function fe(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function pe(e){this._readableState!==null&&(e===`data`&&(this._duplexState|=d|v,this._readableState.updateNextTick()),e===`readable`&&(this._duplexState|=f,this._readableState.updateNextTick())),this._writableState!==null&&e===`drain`&&(this._duplexState|=k,this._writableState.updateNextTick())}var me=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,Me.bind(this))),this.on(`newListener`,pe)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return this._readableState===null?void 0:!0}get writable(){return this._writableState===null?void 0:!0}get destroyed(){return(this._duplexState&8)!=0}get destroying(){return(this._duplexState&14)!=0}destroy(e){this._duplexState&14||(e||=r,this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=e),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},he=class e extends me{constructor(e){super(e),this._duplexState|=O|131073,this._readableState=new ne(this,e),e&&(this._readableState.readAhead===!1&&(this._duplexState&=S),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}setEncoding(e){let t=new o(e),n=this._readableState.map||Se;return this._readableState.map=r,this;function r(e){let r=t.push(e);return r===``&&(e.byteLength!==0||t.remaining>0)?null:n(r)}}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=v,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator(t,n){let r,i=new e({...n,read(e){t.next().then(a).then(e.bind(null,null)).catch(e)},predestroy(){r=t.return()},destroy(e){if(!r)return e(null);r.then(e.bind(null,null)).catch(e)}});return i;function a(e){e.done?i.push(null):i.push(e.value)}}static from(t,n){if(De(t))return t;if(t[te])return this._fromAsyncIterator(t[te](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(e){this.push(r===t.length?null:t[r++]),e(null)}})}static isBackpressured(e){return(e._duplexState&17422)!=0||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return(e._duplexState&256)==0}[te](){let e=this,t=null,n=null,i=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,a),this.on(`close`,o),{[te](){return this},next(){return new Promise(function(t,r){n=t,i=r;let a=e.read();a===null?e._duplexState&8&&s(null):s(a)})},return(){return c(null)},throw(e){return c(e)}};function a(){n!==null&&s(e.read())}function o(){n!==null&&s(null)}function s(a){i!==null&&(t?i(t):a===null&&(e._duplexState&m)===0?i(r):n({value:a,done:a===null}),i=n=null)}function c(t){return e.destroy(t),new Promise((n,r)=>{if(e._duplexState&8)return n({value:void 0,done:!0});e.once(`close`,function(){t?r(t):n({value:void 0,done:!0})})})}}},q=class extends me{constructor(e){super(e),this._duplexState|=1|m,this._writableState=new W(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=N}uncork(){this._duplexState&=I,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return(e._duplexState&146800654)!=0}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(Ne(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&j?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},ge=class extends he{constructor(e){super(e),this._duplexState=1|this._duplexState&_,this._writableState=new W(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=N}uncork(){this._duplexState&=I,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},_e=class extends ge{constructor(e){super(e),this._transformState=new G(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(this._transformState.data!==null){let t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(ye.bind(this))}},ve=class extends _e{};function ye(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function be(...e){return new Promise((t,n)=>xe(...e,e=>{if(e)return n(e);t()}))}function xe(e,...t){let n=Array.isArray(e)?[...e,...t]:[e,...t],r=n.length&&typeof n[n.length-1]==`function`?n.pop():null;if(n.length<2)throw Error(`Pipeline requires at least 2 streams`);let a=n[0],o=null,s=null;for(let e=1;e<n.length;e++)o=n[e],we(a)?a.pipe(o,l):(c(a,!0,e>1,l),a.pipe(o)),a=o;if(r){let e=!1,t=we(o)||!!(o._writableState&&o._writableState.autoDestroy);o.on(`error`,e=>{s===null&&(s=e)}),o.on(`finish`,()=>{e=!0,t||r(s)}),t&&o.on(`close`,()=>r(s||(e?null:i)))}return o;function c(e,t,n,r){e.on(`error`,r),e.on(`close`,a);function a(){if(t&&e._readableState&&!e._readableState.ended||n&&e._writableState&&!e._writableState.ended)return r(i)}}function l(e){if(!(!e||s)){s=e;for(let t of n)t.destroy(e)}}}function Se(e){return e}function Ce(e){return!!e._readableState||!!e._writableState}function we(e){return typeof e._duplexState==`number`&&Ce(e)}function Te(e){return!!e._readableState&&e._readableState.ended}function Ee(e){return!!e._writableState&&e._writableState.ended}function J(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===r?null:n}function De(e){return we(e)&&e.readable}function Oe(e){return(e._duplexState&1)!=1||(e._duplexState&B)!==0}function ke(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Ae(e){return ke(e)?e.byteLength:1024}function je(){}function Me(){this.destroy(Error(`Stream aborted.`))}function Ne(e){return e._writev!==q.prototype._writev&&e._writev!==ge.prototype._writev}t.exports={pipeline:xe,pipelinePromise:be,isStream:Ce,isStreamx:we,isEnded:Te,isFinished:Ee,isDisturbed:Oe,getStreamError:J,Stream:me,Writable:q,Readable:he,Duplex:ge,Transform:_e,PassThrough:ve}})}),hu=Qs({"../../node_modules/tar-stream/headers.js":(e=>{let t=uu(),n=t.from([117,115,116,97,114,0]),r=t.from([48,48]),i=t.from([117,115,116,97,114,32]),a=t.from([32,0]);e.decodeLongPath=function(e,t){return v(e,0,e.length,t)},e.encodePax=function(e){let n=``;e.name&&(n+=y(` path=`+e.name+`
|
|
144
144
|
`)),e.linkname&&(n+=y(` linkpath=`+e.linkname+`
|
|
145
145
|
`));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
|
|
146
|
-
`);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})}),gu=Qs({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=mu(),a=lu(),o=uu(),s=hu(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})}),_u=Qs({"../../node_modules/tar-stream/constants.js":((e,t)=>{let n={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=tc(`fs`).constants||n}catch{t.exports=n}})}),vu=Qs({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=mu(),a=uu(),o=_u(),s=hu(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})}),yu=ec(Qs({"../../node_modules/tar-stream/index.js":(e=>{e.extract=gu(),e.pack=vu()})})(),1);const bu=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await w.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=yu.pack(),i=async(e,t=``)=>{let n=await w.readdir(e,{withFileTypes:!0});for(let a of n){let n=`${e}/${a.name}`,o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){r.entry({name:`${o}/`,type:`directory`}),await i(n,o);continue}if(a.isSymbolicLink?.()){let e=await w.readlink(n);r.entry({name:o,type:`symlink`,linkname:e});continue}if(a.isFile()){let e=await w.stat(n);await new Promise((t,i)=>{let a=(0,l.createReadStream)(n),s=r.entry({name:o,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&i(e)});a.on(`error`,i),a.on(`data`,e=>s.write(e)),a.on(`end`,()=>{s.end(),t()})});continue}}};(async()=>{try{await i(e),r.finalize()}catch(e){r.destroy(e)}})();let a=r,o=0,s=!1;return new ReadableStream({start(e){a.on(`data`,t=>{if(!s){if(o+=t.length,o>n){s=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${o} bytes.`));try{a.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),a.once(`error`,t=>{s||(s=!0,e.error(t instanceof Error?t:Error(String(t))))}),a.once(`end`,()=>{s||(s=!0,e.close())})},cancel(){try{a.destroy()}catch{}}})};var xu=Qs({"../../node_modules/dotenv/package.json":((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})}),Su=ec(Qs({"../../node_modules/dotenv/lib/main.js":((e,t)=>{let n=tc(`fs`),r=tc(`path`),i=tc(`os`),a=tc(`crypto`),o=xu().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
146
|
+
`);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})}),gu=Qs({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=mu(),a=lu(),o=uu(),s=hu(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})}),_u=Qs({"../../node_modules/tar-stream/constants.js":((e,t)=>{let n={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=tc(`fs`).constants||n}catch{t.exports=n}})}),vu=Qs({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=mu(),a=uu(),o=_u(),s=hu(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})}),yu=ec(Qs({"../../node_modules/tar-stream/index.js":(e=>{e.extract=gu(),e.pack=vu()})})(),1);const bu=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await w.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=yu.pack(),i=async(e,t=``)=>{let n=await w.readdir(e,{withFileTypes:!0});for(let o of n){let n=`${e}/${o.name}`,s=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){r.entry({name:`${s}/`,type:`directory`}),await i(n,s);continue}if(o.isSymbolicLink?.()){let e=await w.readlink(n);r.entry({name:s,type:`symlink`,linkname:e});continue}if(o.isFile()){let e=await w.stat(n);await new Promise((t,i)=>{let o=(0,a.createReadStream)(n),c=r.entry({name:s,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&i(e)});o.on(`error`,i),o.on(`data`,e=>c.write(e)),o.on(`end`,()=>{c.end(),t()})});continue}}};(async()=>{try{await i(e),r.finalize()}catch(e){r.destroy(e)}})();let o=r,s=0,c=!1;return new ReadableStream({start(e){o.on(`data`,t=>{if(!c){if(s+=t.length,s>n){c=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${s} bytes.`));try{o.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),o.once(`error`,t=>{c||(c=!0,e.error(t instanceof Error?t:Error(String(t))))}),o.once(`end`,()=>{c||(c=!0,e.close())})},cancel(){try{o.destroy()}catch{}}})};var xu=Qs({"../../node_modules/dotenv/package.json":((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})}),Su=ec(Qs({"../../node_modules/dotenv/lib/main.js":((e,t)=>{let n=tc(`fs`),r=tc(`path`),i=tc(`os`),a=tc(`crypto`),o=xu().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
147
147
|
`);let r;for(;(r=f.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
|
|
148
|
-
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})})(),1);const Cu=(e,t)=>e.length<=t?e:e.slice(e.length-t),wu=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var Tu=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;proxyOnly;fetchProxyRequest;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new lc({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new au({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=oc.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case cs.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case cs.PROXY_INIT:{let t=us[cs.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new Ws.default(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped(ls.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(ls.PROXY_WEBSOCKET_MESSAGE,os(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(ls.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case cs.PROXY_WEBSOCKET_MESSAGE:{let e=ss(n,this.decoder);r.send(e);break}case cs.PROXY_WEBSOCKET_CLOSE:{let e=us[cs.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case cs.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r,redirect:`manual`},a;a=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let o={};a.headers.forEach((e,t)=>{o[t]=e});let s={headers:o,status_code:a.status,status_message:a.statusText};e.writeTyped(ls.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,u=oc.getMaxPayloadSize()-1;if(l>=u){if(!a.body){e.close();return}let t=a.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(u,r.length-t),i=r.subarray(t,t+n);e.writeTyped(ls.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(ls.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=ps[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{if(t.payload.env_file){let e=await o.readFile(t.payload.env_file,`utf-8`),n=(0,Su.parse)(e);t.payload.env={...t.payload.env,...n}}let n=await this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=wu(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await bu(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await o.readFile(t.payload.path),r=await Zl(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
|
|
149
|
-
`),a=Math.max(0,(t.payload.line_start??1)-1),
|
|
150
|
-
`),mime_type:`text/plain`,total_lines:i.length,lines_read:
|
|
148
|
+
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})})(),1);const Cu=(e,t)=>e.length<=t?e:e.slice(e.length-t),wu=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var Tu=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;proxyOnly;fetchProxyRequest;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new lc({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new au({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=oc.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case cs.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case cs.PROXY_INIT:{let t=us[cs.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new Ws.default(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped(ls.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(ls.PROXY_WEBSOCKET_MESSAGE,os(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(ls.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case cs.PROXY_WEBSOCKET_MESSAGE:{let e=ss(n,this.decoder);r.send(e);break}case cs.PROXY_WEBSOCKET_CLOSE:{let e=us[cs.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case cs.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r,redirect:`manual`},a;a=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let o={};a.headers.forEach((e,t)=>{o[t]=e});let s={headers:o,status_code:a.status,status_message:a.statusText};e.writeTyped(ls.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,u=oc.getMaxPayloadSize()-1;if(l>=u){if(!a.body){e.close();return}let t=a.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(u,r.length-t),i=r.subarray(t,t+n);e.writeTyped(ls.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(ls.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=ps[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{if(t.payload.env_file){let e=await g.readFile(t.payload.env_file,`utf-8`),n=(0,Su.parse)(e);t.payload.env={...t.payload.env,...n}}let n=await this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=wu(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await bu(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await g.readFile(t.payload.path),r=await Zl(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
|
|
149
|
+
`),a=Math.max(0,(t.payload.line_start??1)-1),o=Math.min(i.length,t.payload.line_end??i.length),s=i.slice(a,o);this.sendResponse(e,{id:t.id,payload:{content:s.join(`
|
|
150
|
+
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await g.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await g.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await g.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await g.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(ls.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([ls.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=Cu(this.processManager.readANSIOutput(i.pid),64e3),f=wu(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};function Eu(e){let t=new TextEncoder,n=new TextDecoder,r=new Tu({...e,send:e=>{i.handleMessage(e)}}),i=new lc({send:e=>{r.handleMessage(e)},isClient:!0}),a=i.createStream(),o=new Ds({send:e=>{a.writeTyped(0,t.encode(e),!0)}});return a.onData(e=>{let t=e.subarray(1);o.handleMessage(n.decode(t))}),i.onStream(e=>{e.onData(e=>{let t=e.subarray(1);o.handleMessage(n.decode(t))})}),{client:o,server:r}}var Du=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},Ou=class extends Du{};new Ou;function ku(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Au(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function ju(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Mu(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Nu(e,t){return ju(e,t,``)}function Pu(e,t){return Mu(e,t,``)}function Fu(e,t){return t.slice(0,Iu(e,t))}function Iu(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Lu(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Ru(e){let t=e.match(/^\s*/);return t?t[0]:``}const zu=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,Bu=RegExp(`[${zu}]+|\\s+|[^${zu}]`,`ug`);var Vu=class extends Du{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match(Bu)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&Hu(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Hu(n,i,r,null),e}};new Vu;function Hu(e,t,n,r){if(t&&n){let i=Ru(t.value),a=Lu(t.value),o=Ru(n.value),s=Lu(n.value);if(e){let r=ku(i,o);e.value=Mu(e.value,o,r),t.value=Nu(t.value,r),n.value=Nu(n.value,r)}if(r){let e=Au(a,s);r.value=ju(r.value,s,e),t.value=Pu(t.value,e),n.value=Pu(n.value,e)}}else if(n){if(e){let e=Ru(n.value);n.value=n.value.substring(e.length)}if(r){let e=Ru(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Ru(r.value),i=Ru(t.value),a=Lu(t.value),o=ku(n,i);t.value=Nu(t.value,o);let s=Au(Nu(n,o),a);t.value=Pu(t.value,s),r.value=ju(r.value,n,s),e.value=Mu(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Ru(r.value),n=Lu(t.value),i=Fu(n,e);t.value=Pu(t.value,i)}else if(e){let n=Lu(e.value),r=Ru(t.value),i=Fu(n,r);t.value=Nu(t.value,i)}}var Uu=class extends Du{tokenize(e){let t=RegExp(`(\\r?\\n)|[${zu}]+|[^\\S\\n\\r]+|[^${zu}]`,`ug`);return e.match(t)||[]}};new Uu;var Wu=class extends Du{constructor(){super(...arguments),this.tokenize=qu}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
151
151
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
152
152
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
153
153
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
@@ -166,7 +166,7 @@ Use the same rules as \`execute_bash\`, but the output is returned synchronously
|
|
|
166
166
|
Output from the process will be returned along with it's exit code, duration, and whether the process is still running.
|
|
167
167
|
|
|
168
168
|
IMPORTANT: ALWAYS use this tool to determine the status of a process. NEVER use "ps".
|
|
169
|
-
`,inputSchema:b.z.object({pid:b.z.number(),timeout_ms:b.z.number().optional().describe(`The timeout in milliseconds to wait to return output. This does *not* kill the process, it simply returns early with current output of the process. Defaults to 25 seconds.`)}),async*execute(t,n){for await(let r of sd({client:await e(),pid:t.pid,abortSignal:n.abortSignal,timeoutMs:t.timeout_ms}))yield r},toModelOutput:ad})),read_file:id(({client:e})=>(0,
|
|
169
|
+
`,inputSchema:b.z.object({pid:b.z.number(),timeout_ms:b.z.number().optional().describe(`The timeout in milliseconds to wait to return output. This does *not* kill the process, it simply returns early with current output of the process. Defaults to 25 seconds.`)}),async*execute(t,n){for await(let r of sd({client:await e(),pid:t.pid,abortSignal:n.abortSignal,timeoutMs:t.timeout_ms}))yield r},toModelOutput:ad})),read_file:id(({client:e})=>(0,h.tool)({description:`Reads a file from the workspace filesystem. You can access any file directly by using this tool.
|
|
170
170
|
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
|
|
171
171
|
|
|
172
172
|
Usage:
|
|
@@ -178,7 +178,7 @@ Usage:
|
|
|
178
178
|
- This tool allows Blink to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Blink is a multimodal LLM
|
|
179
179
|
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
|
|
180
180
|
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/123/abc/T/TemporaryItems/NSIRD_screencaptureui_ZfB1tD/Screenshot.png
|
|
181
|
-
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:b.z.object({file_path:b.z.string(),line_offset:b.z.number(),line_limit:b.z.number()}),execute:async(t,n)=>await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal}),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:id(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:b.z.object({file_path:b.z.string(),content:b.z.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:id(({client:e})=>(0,
|
|
181
|
+
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:b.z.object({file_path:b.z.string(),line_offset:b.z.number(),line_limit:b.z.number()}),execute:async(t,n)=>await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal}),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:id(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:b.z.object({file_path:b.z.string(),content:b.z.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:id(({client:e})=>(0,h.tool)({description:`Reads a directory from the workspace filesystem.`,inputSchema:b.z.object({directory_path:b.z.string()}),execute:async(t,n)=>(await e()).request(`read_directory`,{path:t.directory_path})})),edit_file:id(({client:e})=>({description:`This is a tool for making multiple edits to a single file in one operation. It is built on top of the "workspace_edit_file" tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the "workspace_edit_file" tool when you need to make multiple edits to the same file.
|
|
182
182
|
|
|
183
183
|
Before using this tool:
|
|
184
184
|
|
|
@@ -242,15 +242,15 @@ for await (const chunk of exa.streamAnswer(query)) {
|
|
|
242
242
|
// Handle chunks
|
|
243
243
|
}`,400);let n=t?.outputSchema;n&&gp(n)&&(n=_p(n));let r={query:e,stream:!1,text:t?.text??!1,model:t?.model??`exa`,systemPrompt:t?.systemPrompt,outputSchema:n,userLocation:t?.userLocation};return await this.request(`/answer`,`POST`,r)}async*streamAnswer(e,t){let n=t?.outputSchema;n&&gp(n)&&(n=_p(n));let r={query:e,text:t?.text??!1,stream:!0,model:t?.model??`exa`,systemPrompt:t?.systemPrompt,outputSchema:n},i=await Ap(this.baseURL+`/answer`,{method:`POST`,headers:this.headers,body:JSON.stringify(r)});if(!i.ok){let e=await i.text();throw new hp(e,i.status,new Date().toISOString())}let a=i.body?.getReader();if(!a)throw new hp(`No response body available for streaming.`,500,new Date().toISOString());let o=new TextDecoder,s=``;try{for(;;){let{done:e,value:t}=await a.read();if(e)break;s+=o.decode(t,{stream:!0});let n=s.split(`
|
|
244
244
|
`);s=n.pop()||``;for(let e of n){if(!e.startsWith(`data: `))continue;let t=e.replace(/^data:\s*/,``).trim();if(!t||t===`[DONE]`)continue;let n;try{n=JSON.parse(t)}catch{continue}let r=this.processChunk(n);(r.content||r.citations)&&(yield r)}}if(s.startsWith(`data: `)){let e=s.replace(/^data:\s*/,``).trim();if(e&&e!==`[DONE]`)try{let t=JSON.parse(e),n=this.processChunk(t);(n.content||n.citations)&&(yield n)}catch{}}}finally{a.releaseLock()}}processChunk(e){let t,n;return e.choices&&e.choices[0]&&e.choices[0].delta&&(t=e.choices[0].delta.content),e.citations&&e.citations!==`null`&&(n=e.citations.map(e=>({id:e.id,url:e.url,title:e.title,publishedDate:e.publishedDate,author:e.author,text:e.text}))),{content:t,citations:n}}async parseSSEStream(e){let t=e.body?.getReader();if(!t)throw new hp(`No response body available for streaming.`,500,new Date().toISOString());let n=new TextDecoder,r=``;return new Promise(async(e,i)=>{try{for(;;){let{done:a,value:o}=await t.read();if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
|
|
245
|
-
`);r=s.pop()||``;for(let n of s){if(!n.startsWith(`data: `))continue;let r=n.replace(/^data:\s*/,``).trim();if(!r||r===`[DONE]`)continue;let a;try{a=JSON.parse(r)}catch{continue}switch(a.tag){case`complete`:t.releaseLock(),e(a.data);return;case`error`:{let e=a.error?.message||`Unknown error`;t.releaseLock(),i(new hp(e,500,new Date().toISOString()));return}default:break}}}i(new hp(`Stream ended without a completion event.`,500,new Date().toISOString()))}catch(e){i(e)}finally{try{t.releaseLock()}catch{}}})}};const Np=()=>{let e;if(process.env.EXA_API_KEY)e=new Mp(process.env.EXA_API_KEY);else if(process.env.BLINK_INVOCATION_AUTH_TOKEN)e=new Mp(process.env.BLINK_INVOCATION_AUTH_TOKEN,`https://blink.so/api/tools/exa`);else if(process.env.BLINK_TOKEN)e=new Mp(process.env.BLINK_TOKEN,`https://blink.so/api/tools/exa`);else throw console.warn(`You must set the EXA_API_KEY environment variable or be authenticated with Blink to use the web search SDK.`),Error(`The EXA_API_KEY environment variable or a Blink token must be set to use the web search SDK.`);return e},Pp={web_search:Ad({description:`Perform a search query on the web, and retrieve the most relevant URLs/web data.`,inputSchema:b.z.object({query:b.z.string()}),execute:async({query:e})=>await Np().searchAndContents(e,{numResults:5,type:`auto`,text:{maxCharacters:3e3},livecrawl:`preferred`})})};function Fp(e,
|
|
245
|
+
`);r=s.pop()||``;for(let n of s){if(!n.startsWith(`data: `))continue;let r=n.replace(/^data:\s*/,``).trim();if(!r||r===`[DONE]`)continue;let a;try{a=JSON.parse(r)}catch{continue}switch(a.tag){case`complete`:t.releaseLock(),e(a.data);return;case`error`:{let e=a.error?.message||`Unknown error`;t.releaseLock(),i(new hp(e,500,new Date().toISOString()));return}default:break}}}i(new hp(`Stream ended without a completion event.`,500,new Date().toISOString()))}catch(e){i(e)}finally{try{t.releaseLock()}catch{}}})}};const Np=()=>{let e;if(process.env.EXA_API_KEY)e=new Mp(process.env.EXA_API_KEY);else if(process.env.BLINK_INVOCATION_AUTH_TOKEN)e=new Mp(process.env.BLINK_INVOCATION_AUTH_TOKEN,`https://blink.so/api/tools/exa`);else if(process.env.BLINK_TOKEN)e=new Mp(process.env.BLINK_TOKEN,`https://blink.so/api/tools/exa`);else throw console.warn(`You must set the EXA_API_KEY environment variable or be authenticated with Blink to use the web search SDK.`),Error(`The EXA_API_KEY environment variable or a Blink token must be set to use the web search SDK.`);return e},Pp={web_search:Ad({description:`Perform a search query on the web, and retrieve the most relevant URLs/web data.`,inputSchema:b.z.object({query:b.z.string()}),execute:async({query:e})=>await Np().searchAndContents(e,{numResults:5,type:`auto`,text:{maxCharacters:3e3},livecrawl:`preferred`})})};function Fp(e,n,r){let i,a=u.default.createServer(t.createServerAdapter(async t=>{let o=new URL(t.url,i);if(o.pathname!==`/`)return new Response(`Not found`,{status:404});let s=o.searchParams.get(`code`);if(s)try{let e=await fetch(`https://api.github.com/app-manifests/${s}/conversions`,{method:`POST`,headers:{Accept:`application/vnd.github+json`,"User-Agent":`blink.so`,"X-GitHub-Api-Version":`2022-11-28`}});if(!e.ok){let t=await e.text();throw Error(`GitHub API error: ${e.status} ${e.statusText}${t?` - ${t}`:``}`)}let t=await e.json();return await r?.(null,t),new Response(`GitHub App created successfully! Return to your terminal to continue.`,{headers:{"Content-Type":`text/plain`}})}catch(e){let t=e instanceof Error?e:Error(String(e));try{await r?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let n=t.message;return new Response(`Error: ${n}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{a.close()}let c={...e,redirect_url:i},l=`<!DOCTYPE html>
|
|
246
246
|
<html>
|
|
247
247
|
<body>
|
|
248
|
-
<form id="f" method="POST" action="${
|
|
248
|
+
<form id="f" method="POST" action="${n?`https://github.com/organizations/${n}/settings/apps/new`:`https://github.com/settings/apps/new`}">
|
|
249
249
|
<input type="hidden" name="manifest" value='${JSON.stringify(c).replace(/'/g,`'`)}' />
|
|
250
250
|
</form>
|
|
251
251
|
<script>document.getElementById('f').submit()<\/script>
|
|
252
252
|
</body>
|
|
253
|
-
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{a.on(`error`,t),a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}i=`http://127.0.0.1:${n.port}`,e(i)})})}const Ip=b.z.enum([`read`,`write`]),Lp=b.z.union([b.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),b.z.literal(`check_run`).describe(`Check run created, completed, or requested`),b.z.literal(`check_suite`).describe(`Check suite completed or requested`),b.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),b.z.literal(`commit_comment`).describe(`Commit comment created`),b.z.literal(`create`).describe(`Branch or tag created`),b.z.literal(`delete`).describe(`Branch or tag deleted`),b.z.literal(`deployment`).describe(`Deployment created`),b.z.literal(`deployment_status`).describe(`Deployment status created`),b.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),b.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),b.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),b.z.literal(`fork`).describe(`Repository forked`),b.z.literal(`gollum`).describe(`Wiki page created or updated`),b.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),b.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),b.z.literal(`label`).describe(`Label created, edited, or deleted`),b.z.literal(`member`).describe(`Collaborator added, removed, or edited`),b.z.literal(`membership`).describe(`Team membership added or removed`),b.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),b.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),b.z.literal(`organization`).describe(`Organization member added, removed, or invited`),b.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),b.z.literal(`package`).describe(`Package published or updated`),b.z.literal(`page_build`).describe(`GitHub Pages site built`),b.z.literal(`project`).describe(`Project created, updated, or deleted`),b.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),b.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),b.z.literal(`public`).describe(`Repository visibility changed to public`),b.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),b.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),b.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),b.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),b.z.literal(`push`).describe(`Git push to a repository`),b.z.literal(`registry_package`).describe(`Registry package published or updated`),b.z.literal(`release`).describe(`Release published or edited`),b.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),b.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),b.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),b.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),b.z.literal(`star`).describe(`Repository starred or unstarred`),b.z.literal(`status`).describe(`Commit status created`),b.z.literal(`team`).describe(`Team created, deleted, or edited`),b.z.literal(`team_add`).describe(`Repository added to team`),b.z.literal(`watch`).describe(`User started watching repository`),b.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),b.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),b.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),Rp=b.z.object({name:b.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:b.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:b.z.string().optional().describe(`The description of the GitHub App.`),public:b.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:b.z.object({url:b.z.url(),active:b.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:b.z.array(b.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:b.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:b.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:b.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:b.z.array(Lp).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:b.z.record(b.z.string(),Ip).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function zp(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const Bp=b.z.union([b.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),b.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),b.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),b.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),b.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),b.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),b.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),b.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),b.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),b.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),b.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),b.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),b.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),b.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),b.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),b.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),b.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),b.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),b.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),b.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),b.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),b.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),b.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),b.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),b.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),b.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),b.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),b.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),b.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),b.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),b.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),b.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),b.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),b.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),b.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),b.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),b.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Vp=b.z.union([b.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),b.z.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),b.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),b.z.literal(`channels:join`).describe(`Join public channels`),b.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),b.z.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),b.z.literal(`chat:write`).describe(`Send messages as the bot`),b.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),b.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),b.z.literal(`commands`).describe(`Add and use slash commands`),b.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),b.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),b.z.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),b.z.literal(`files:write`).describe(`Upload, edit, and delete files`),b.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),b.z.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),b.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),b.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),b.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),b.z.literal(`im:write`).describe(`Start and manage direct messages with users`),b.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),b.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),b.z.literal(`metadata.message:read`).describe(`Read message metadata`),b.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),b.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),b.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),b.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),b.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),b.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),b.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),b.z.literal(`reminders:read`).describe(`View reminders created by the bot`),b.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),b.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),b.z.literal(`usergroups:read`).describe(`View user groups and their members`),b.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),b.z.literal(`users.profile:read`).describe(`View profile information about users`),b.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),b.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),b.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),Hp=b.z.union([b.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),b.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),b.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),b.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),b.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),b.z.literal(`files:read`).describe(`View files on behalf of the user`),b.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),b.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),b.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),b.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),b.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),b.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),b.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),b.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),b.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),b.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),b.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),b.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),b.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),b.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),b.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),b.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),b.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),b.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),b.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),b.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),b.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),b.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),b.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),b.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),b.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),b.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),b.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),b.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),b.z.literal(`users:write`).describe(`Set presence for the user`)]),Up=b.z.object({display_information:b.z.object({name:b.z.string().describe(`The name of the Slack app.`),description:b.z.string().optional().describe(`A short description of the app.`),background_color:b.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:b.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:b.z.object({bot_user:b.z.object({display_name:b.z.string().describe(`The display name for the bot user.`),always_online:b.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:b.z.object({home_tab_enabled:b.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:b.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:b.z.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home.`),assistant_view:b.z.object({assistant_description:b.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:b.z.array(b.z.object({command:b.z.string().regex(/^\//).describe(`The command (must start with /).`),description:b.z.string().describe(`Description of the command.`),usage_hint:b.z.string().optional().describe(`Usage hint for the command.`),should_escape:b.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:b.z.array(b.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:b.z.object({redirect_urls:b.z.array(b.z.string().url()).optional().describe(`OAuth redirect URLs.`),scopes:b.z.object({bot:b.z.array(b.z.union([Vp,b.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:b.z.array(b.z.union([Hp,b.z.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).optional().describe(`OAuth configuration for the Slack app.`),settings:b.z.object({event_subscriptions:b.z.object({request_url:b.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:b.z.array(b.z.union([Bp,b.z.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:b.z.object({is_enabled:b.z.boolean().describe(`Enable interactivity.`),request_url:b.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:b.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:b.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:b.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:b.z.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)}),Wp=`This project is a Blink agent.
|
|
253
|
+
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{a.on(`error`,t),a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}i=`http://127.0.0.1:${n.port}`,e(i)})})}const Ip=b.z.enum([`read`,`write`]),Lp=b.z.union([b.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),b.z.literal(`check_run`).describe(`Check run created, completed, or requested`),b.z.literal(`check_suite`).describe(`Check suite completed or requested`),b.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),b.z.literal(`commit_comment`).describe(`Commit comment created`),b.z.literal(`create`).describe(`Branch or tag created`),b.z.literal(`delete`).describe(`Branch or tag deleted`),b.z.literal(`deployment`).describe(`Deployment created`),b.z.literal(`deployment_status`).describe(`Deployment status created`),b.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),b.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),b.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),b.z.literal(`fork`).describe(`Repository forked`),b.z.literal(`gollum`).describe(`Wiki page created or updated`),b.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),b.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),b.z.literal(`label`).describe(`Label created, edited, or deleted`),b.z.literal(`member`).describe(`Collaborator added, removed, or edited`),b.z.literal(`membership`).describe(`Team membership added or removed`),b.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),b.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),b.z.literal(`organization`).describe(`Organization member added, removed, or invited`),b.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),b.z.literal(`package`).describe(`Package published or updated`),b.z.literal(`page_build`).describe(`GitHub Pages site built`),b.z.literal(`project`).describe(`Project created, updated, or deleted`),b.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),b.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),b.z.literal(`public`).describe(`Repository visibility changed to public`),b.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),b.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),b.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),b.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),b.z.literal(`push`).describe(`Git push to a repository`),b.z.literal(`registry_package`).describe(`Registry package published or updated`),b.z.literal(`release`).describe(`Release published or edited`),b.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),b.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),b.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),b.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),b.z.literal(`star`).describe(`Repository starred or unstarred`),b.z.literal(`status`).describe(`Commit status created`),b.z.literal(`team`).describe(`Team created, deleted, or edited`),b.z.literal(`team_add`).describe(`Repository added to team`),b.z.literal(`watch`).describe(`User started watching repository`),b.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),b.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),b.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),Rp=b.z.object({name:b.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:b.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:b.z.string().optional().describe(`The description of the GitHub App.`),public:b.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:b.z.object({url:b.z.url(),active:b.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:b.z.array(b.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:b.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:b.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:b.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:b.z.array(Lp).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:b.z.record(b.z.string(),Ip).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function zp(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const Bp=b.z.union([b.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),b.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),b.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),b.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),b.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),b.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),b.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),b.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),b.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),b.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),b.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),b.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),b.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),b.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),b.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),b.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),b.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),b.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),b.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),b.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),b.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),b.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),b.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),b.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),b.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),b.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),b.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),b.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),b.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),b.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),b.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),b.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),b.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),b.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),b.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),b.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),b.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Vp=b.z.union([b.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),b.z.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),b.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),b.z.literal(`channels:join`).describe(`Join public channels`),b.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),b.z.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),b.z.literal(`chat:write`).describe(`Send messages as the bot`),b.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),b.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),b.z.literal(`commands`).describe(`Add and use slash commands`),b.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),b.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),b.z.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),b.z.literal(`files:write`).describe(`Upload, edit, and delete files`),b.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),b.z.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),b.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),b.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),b.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),b.z.literal(`im:write`).describe(`Start and manage direct messages with users`),b.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),b.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),b.z.literal(`metadata.message:read`).describe(`Read message metadata`),b.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),b.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),b.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),b.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),b.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),b.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),b.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),b.z.literal(`reminders:read`).describe(`View reminders created by the bot`),b.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),b.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),b.z.literal(`usergroups:read`).describe(`View user groups and their members`),b.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),b.z.literal(`users.profile:read`).describe(`View profile information about users`),b.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),b.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),b.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),Hp=b.z.union([b.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),b.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),b.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),b.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),b.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),b.z.literal(`files:read`).describe(`View files on behalf of the user`),b.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),b.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),b.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),b.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),b.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),b.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),b.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),b.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),b.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),b.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),b.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),b.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),b.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),b.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),b.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),b.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),b.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),b.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),b.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),b.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),b.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),b.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),b.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),b.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),b.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),b.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),b.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),b.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),b.z.literal(`users:write`).describe(`Set presence for the user`)]),Up=b.z.object({display_information:b.z.object({name:b.z.string().describe(`The name of the Slack app.`),description:b.z.string().optional().describe(`A short description of the app.`),background_color:b.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:b.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:b.z.object({bot_user:b.z.object({display_name:b.z.string().describe(`The display name for the bot user.`),always_online:b.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:b.z.object({home_tab_enabled:b.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:b.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:b.z.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home. If specified, the "bot" scope is *REQUIRED*.`),assistant_view:b.z.object({assistant_description:b.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:b.z.array(b.z.object({command:b.z.string().regex(/^\//).describe(`The command (must start with /).`),description:b.z.string().describe(`Description of the command.`),usage_hint:b.z.string().optional().describe(`Usage hint for the command.`),should_escape:b.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:b.z.array(b.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:b.z.object({redirect_urls:b.z.array(b.z.url()).optional().describe(`OAuth redirect URLs.`),scopes:b.z.object({bot:b.z.array(b.z.union([Vp,b.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:b.z.array(b.z.union([Hp,b.z.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).describe(`OAuth configuration for the Slack app.`),settings:b.z.object({event_subscriptions:b.z.object({request_url:b.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:b.z.array(b.z.union([Bp,b.z.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:b.z.object({is_enabled:b.z.boolean().describe(`Enable interactivity.`),request_url:b.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:b.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:b.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:b.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:b.z.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)}),Wp=`This project is a Blink agent.
|
|
254
254
|
|
|
255
255
|
You are an expert software engineer, which makes you an expert agent developer. You are highly idiomatic, opinionated, concise, and precise. The user prefers accuracy over speed.
|
|
256
256
|
|
|
@@ -298,6 +298,10 @@ Changes to the agent are hot-reloaded. As you make edits, the user can immediate
|
|
|
298
298
|
5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses \`inputSchema\` instead of \`parameters\` (which was in v4).
|
|
299
299
|
6. Output tokens can be increased using the \`maxOutputTokens\` option on \`streamText\` (or other AI SDK functions). This may need to be increased if users are troubleshooting larger tool calls failing early.
|
|
300
300
|
7. Use the TypeScript language service tools (\`typescript_completions\`, \`typescript_quickinfo\`, \`typescript_definition\`, \`typescript_diagnostics\`) to understand APIs, discover available methods, check types, and debug errors. These tools use tsserver to provide IDE-like intelligence.
|
|
301
|
+
|
|
302
|
+
If the user is asking for a behavioral change, you should update the agent's system prompt.
|
|
303
|
+
This will not ensure the behavior, but it will guide the agent towards the desired behavior.
|
|
304
|
+
If the user needs 100% behavioral certainty, adjust tool behavior instead.
|
|
301
305
|
</agent_development>
|
|
302
306
|
|
|
303
307
|
<agent_web_requests>
|
|
@@ -551,6 +555,49 @@ agent.on("chat", async ({ messages }) => {
|
|
|
551
555
|
})
|
|
552
556
|
\`\`\`
|
|
553
557
|
|
|
558
|
+
Slack SDK Notes:
|
|
559
|
+
- "app_mention" event is triggered in both private channels and public channels.
|
|
560
|
+
- "message" event is triggered regardless of being mentioned or not, and will *also* be fired when "app_mention" is triggered.
|
|
561
|
+
- *NEVER* register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.
|
|
562
|
+
- Think about how you scope chats - for example, in IMs or if the user wants to make a bot for a whole channel, you would not want to add "ts" or "thread_ts" to the chat key.
|
|
563
|
+
- When using "assistant.threads.setStatus", you need to ensure the status of that same "thread_ts" is cleared. You can do this by inserting a message part that directs the agent to clear the status (there is a tool if using @blink-sdk/slack called "reportStatus" that does this). e.g. \`message.parts.push({ type: "text", text: "*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${channel} thread_ts=\${thread_ts}" })\`
|
|
564
|
+
- The Slack SDK has many functions that allow users to completely customize the message format. If the user asks for customization, look at the types for @blink-sdk/slack - specifically: "createPartsFromMessageMetadata", "createMessageFromEvent", and "extractMessagesMetadata".
|
|
565
|
+
|
|
566
|
+
Slack App Manifest:
|
|
567
|
+
- *ALWAYS* include the "assistant:write" scope unless the user explicitly states otherwise - this allows Slack apps to set their status, which makes for a significantly better user experience. You *MUST* provide "assistant_view" if you provide this scope.
|
|
568
|
+
- The user can always edit the manifest after creation, but you'd have to suggest it to them.
|
|
569
|
+
- "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
|
|
570
|
+
- *ALWAYS* default "token_rotation_enabled" to false unless the user explicitly asks for it. It is a *much* simpler user-experience to not rotate tokens.
|
|
571
|
+
- For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
|
|
572
|
+
- "app_mentions:read"
|
|
573
|
+
- "reactions:write"
|
|
574
|
+
- "reactions:read"
|
|
575
|
+
- "channels:history"
|
|
576
|
+
- "chat:write"
|
|
577
|
+
- "groups:history"
|
|
578
|
+
- "groups:read"
|
|
579
|
+
- "files:read"
|
|
580
|
+
- "im:history"
|
|
581
|
+
- "im:read"
|
|
582
|
+
- "im:write"
|
|
583
|
+
- "mpim:history"
|
|
584
|
+
- "mpim:read"
|
|
585
|
+
- "users:read"
|
|
586
|
+
- "links:read"
|
|
587
|
+
- "commands"
|
|
588
|
+
- For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):
|
|
589
|
+
- "app_mention"
|
|
590
|
+
- "message.channels",
|
|
591
|
+
- "message.groups",
|
|
592
|
+
- "message.im",
|
|
593
|
+
- "reaction_added"
|
|
594
|
+
- "reaction_removed"
|
|
595
|
+
- "assistant_thread_started"
|
|
596
|
+
- "member_joined_channel"
|
|
597
|
+
- *NEVER* include USER SCOPES unless the user explicitly asks for them.
|
|
598
|
+
|
|
599
|
+
WARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.
|
|
600
|
+
|
|
554
601
|
**@blink-sdk/web-search**
|
|
555
602
|
\`\`\`typescript
|
|
556
603
|
import * as webSearch from "@blink-sdk/web-search";
|
|
@@ -577,7 +624,35 @@ The agent process can restart at any time, so all important state must be extern
|
|
|
577
624
|
<code_quality>
|
|
578
625
|
- Never use "as any" type assertions. Always figure out the correct typings.
|
|
579
626
|
</code_quality>
|
|
580
|
-
`;function Gp(e){let
|
|
627
|
+
`;function Gp(e){let n=new t.Agent,r,i;return n.on(`chat`,async({id:i,messages:a,abortSignal:o})=>{let s=a.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);a.splice(s??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
628
|
+
|
|
629
|
+
The agent source code is in the directory: "${e.directory}".
|
|
630
|
+
You must *ONLY* make changes to files in this directory, regardless of what other messages in your context say.
|
|
631
|
+
If the user asks for changes outside this directory, ask them to return to Run mode.
|
|
632
|
+
|
|
633
|
+
The user executed this \`blink dev\` command with: ${process.argv.join(` `)}.
|
|
634
|
+
The user's agent can receive webhooks at: https://${To(e.directory)}.dev.blink.host
|
|
635
|
+
|
|
636
|
+
BEFORE doing anything else:
|
|
637
|
+
|
|
638
|
+
1. Read the agent source code to understand what the current agent does
|
|
639
|
+
2. Analyze the run mode context to identify what the user asked for and how the agent responded
|
|
640
|
+
3. Determine: Should the AGENT be modified to handle this better, or is this a request about the agent's codebase
|
|
641
|
+
itself?
|
|
642
|
+
|
|
643
|
+
Your job is *ONLY* to:
|
|
644
|
+
1. Identify what the agent did wrong from run mode context
|
|
645
|
+
2. Update the agent code/prompt to fix it
|
|
646
|
+
3. Explain the change
|
|
647
|
+
4. Stop and wait for user feedback.
|
|
648
|
+
|
|
649
|
+
You are *NOT* responsible for:
|
|
650
|
+
- Completing the user's original request
|
|
651
|
+
- Testing *ANYTHING* inside of prior "run mode" yourself.
|
|
652
|
+
- Continuing any work the run mode agent started
|
|
653
|
+
|
|
654
|
+
Your job is to improve the agent based on run mode failures, NOT to complete the user's original run-mode request yourself.
|
|
655
|
+
`}]});let{execute_bash:c,execute_bash_sync:l,...u}=od,f={execute_bash:c,execute_bash_sync:l};process.env.BLINK_AUTO_APPROVE||(f=await t.tools.withApproval({messages:a,tools:f}));let p={...u,...f,...Pp,...await t.tools.withApproval({messages:a,tools:{create_github_app:(0,h.tool)({description:`Creates a GitHub App using GitHub's app manifest flow.
|
|
581
656
|
|
|
582
657
|
IMPORTANT: You must explain to the user what's happening and why:
|
|
583
658
|
- Tell them this will open a localhost URL that redirects them to GitHub
|
|
@@ -589,61 +664,59 @@ You *must* ensure the organization is correct - ask the user prior.
|
|
|
589
664
|
|
|
590
665
|
Once they complete the app creation, environment variables will be automatically set in the provided environment file.
|
|
591
666
|
|
|
592
|
-
After approval, the URL will be opened automatically in their browser.`,inputSchema:b.z.object({manifest:Rp,envFile:b.z.enum([`local`,`production`]).describe(`The environment file to put credentials in on app creation.`),organization:b.z.string().optional().describe(`An optional GitHub organization the app should be created for. Leave blank to create a personal app.`)}),execute:async(
|
|
667
|
+
After approval, the URL will be opened automatically in their browser.`,inputSchema:b.z.object({manifest:Rp,envFile:b.z.enum([`local`,`production`]).describe(`The environment file to put credentials in on app creation.`),organization:b.z.string().optional().describe(`An optional GitHub organization the app should be created for. Leave blank to create a personal app.`)}),execute:async(t,r)=>{let a=await Fp(t.manifest,t.organization,async(r,a)=>{if(r){await n.chat.sendMessages(i,[{role:`assistant`,parts:[{type:`text`,text:`Failed to create GitHub App: ${r.message}`}]}]);return}if(a){try{let n=t.envFile===`production`?`.env.production`:`.env.local`,r=(0,d.join)(e.directory,n),i=``;try{i=await(0,g.readFile)(r,`utf-8`)}catch{}let o=`
|
|
593
668
|
# GitHub App credentials (created with the blink edit agent)
|
|
594
|
-
GITHUB_APP_ID=${
|
|
595
|
-
GITHUB_CLIENT_ID=${
|
|
596
|
-
GITHUB_CLIENT_SECRET=${
|
|
597
|
-
GITHUB_WEBHOOK_SECRET=${
|
|
598
|
-
GITHUB_PRIVATE_KEY="${btoa(
|
|
599
|
-
`;await(0,
|
|
669
|
+
GITHUB_APP_ID=${a.id}
|
|
670
|
+
GITHUB_CLIENT_ID=${a.client_id}
|
|
671
|
+
GITHUB_CLIENT_SECRET=${a.client_secret}
|
|
672
|
+
GITHUB_WEBHOOK_SECRET=${a.webhook_secret}
|
|
673
|
+
GITHUB_PRIVATE_KEY="${btoa(a.pem)}"
|
|
674
|
+
`;await(0,g.writeFile)(r,i+o,`utf-8`)}catch(e){await n.chat.sendMessages(i,[{role:`assistant`,parts:[{type:`text`,text:`GitHub App created but failed to write credentials to env file: ${e instanceof Error?e.message:String(e)}`}]}]);return}await n.chat.sendMessages(i,[{role:`assistant`,parts:[{type:`text`,text:`GitHub App created successfully. The following environment variables have been set in the ${t.envFile} environment file: GITHUB_APP_ID, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, GITHUB_WEBHOOK_SECRET, GITHUB_PRIVATE_KEY.`}]}])}});return(await za(a)).once(`error`,e=>{console.log(`Could not open the browser. Please visit the URL manually: ${a}`)}),`Opening GitHub App creation URL in browser: ${a}`}}),create_slack_app:(0,h.tool)({description:`Creates a Slack App with the provided manifest.
|
|
600
675
|
|
|
601
676
|
IMPORTANT - when ran, you MUST:
|
|
602
|
-
1. Inform the user that the URL has opened in their browser automatically
|
|
677
|
+
1. Inform the user that the URL has opened in their browser automatically to *Slack*.
|
|
603
678
|
2. Direct the user to add the Slack Signing Secret - found on the general settings page.
|
|
604
679
|
3. Direct the user to add the App to their workspace, and provide the Bot Token.
|
|
605
680
|
|
|
606
681
|
You MUST GUIDE THE USER through these steps - do not provide all the steps at once.
|
|
607
|
-
|
|
608
|
-
*ALWAYS* default "token_rotation_enabled" to false unless the user explicitly asks for it.
|
|
609
|
-
It is a *much* simpler user-experience to not rotate tokens. When "token_rotation_enabled" is false,
|
|
610
|
-
do should *not* provide "oauth_config" in the manifest.
|
|
611
|
-
|
|
612
|
-
For the best user experience, default to the following bot scopes:
|
|
613
|
-
- "app_mentions:read"
|
|
614
|
-
- "reactions:write"
|
|
615
|
-
- "reactions:read"
|
|
616
|
-
- "channels:history"
|
|
617
|
-
- "chat:write"
|
|
618
|
-
- "groups:history"
|
|
619
|
-
- "groups:read"
|
|
620
|
-
- "files:read"
|
|
621
|
-
- "im:history"
|
|
622
|
-
- "im:read"
|
|
623
|
-
- "im:write"
|
|
624
|
-
- "mpim:history"
|
|
625
|
-
- "mpim:read"
|
|
626
|
-
- "users:read"
|
|
627
|
-
- "links:read"
|
|
628
|
-
- "commands"
|
|
629
|
-
|
|
630
|
-
Default to the following events:
|
|
631
|
-
- "app_mention"
|
|
632
|
-
- "message.channels",
|
|
633
|
-
- "message.groups",
|
|
634
|
-
- "message.im",
|
|
635
|
-
- "message.mpim"
|
|
636
|
-
- "reaction_added"
|
|
637
|
-
- "reaction_removed"
|
|
638
|
-
- "assistant_thread_started"
|
|
639
|
-
- "member_joined_channel"
|
|
640
|
-
|
|
641
|
-
*NEVER* include user scopes unless the user explicitly asks for them.
|
|
642
|
-
`,inputSchema:Up,execute:async(e,t)=>{let n=zp(e);return(await za(n)).once(`error`,e=>{console.log(`Could not open the browser. Please visit the URL manually: ${n}`)}),`Opened Slack App creation URL in browser: ${n}`}})}}),message_user_agent:(0,g.tool)({description:`Messages the user agent. There is no conversation history - this will be the only message sent, and only one message responds. Every time you invoke this tool, a new conversation occurs.
|
|
682
|
+
`,inputSchema:Up,execute:async(e,t)=>{let n=zp(e);return(await za(n)).once(`error`,e=>{console.log(`Could not open the browser. Please visit the URL manually: ${n}`)}),`Opened Slack App creation URL in browser: ${n}`}})}}),message_user_agent:(0,h.tool)({description:`Messages the user agent. There is no conversation history - this will be the only message sent, and only one message responds. Every time you invoke this tool, a new conversation occurs.
|
|
643
683
|
|
|
644
|
-
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:b.z.object({message:b.z.string()}),execute:async(e,
|
|
684
|
+
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:b.z.object({message:b.z.string()}),execute:async(e,n)=>{if(!r)return`User agent URL is not available. Cannot test user agent.`;let i=await new t.Client({baseUrl:r}).chat({id:crypto.randomUUID(),messages:[{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:e.message}]}]},{signal:n.abortSignal}),a=(0,h.readUIMessageStream)({stream:i}),o;for await(let e of a)o=e;return o}}),typecheck_agent:(0,h.tool)({description:`*ONLY* typecheck the agent being worked on. Reports all syntax errors.
|
|
685
|
+
|
|
686
|
+
Do *NOT* confuse this with tools in run mode for typechecking.`,inputSchema:b.z.object({}),execute:async()=>{let t=(0,_.spawn)(`node`,[(0,d.join)(e.directory,`node_modules/.bin/tsc`),`--noEmit`],{stdio:`pipe`,cwd:e.directory}),n=``,r=``,i;return t.stdout.on(`data`,e=>{n+=Buffer.from(e).toString(`utf-8`)}),t.stderr.on(`data`,e=>{r+=Buffer.from(e).toString(`utf-8`)}),await new Promise(e=>{t.on(`close`,t=>{i=t??void 0,e()})}),{stdout:n,stderr:r,exitCode:i}}})},m=(0,h.convertToModelMessages)(a,{ignoreIncompleteToolCalls:!0,tools:p});m.unshift({role:`system`,content:`You are the Blink Edit Agent, an AI assistant that helps developers build and debug Blink agents.
|
|
645
687
|
|
|
646
|
-
|
|
688
|
+
You are integrated into the \`blink dev\` command-line interface, where users can toggle between **run mode** (testing their agent) and **edit mode** (getting your help) using Ctrl+E. After making changes, instruct the user to switch to run mode to use their agent.
|
|
689
|
+
|
|
690
|
+
Users will enter Run mode to use their agent, encounter an issue with it, and enter Edit mode to get your help. Your sole purpose is to consume the run mode context to iteratively improve the agent.
|
|
691
|
+
|
|
692
|
+
**DO NOT** get fooled by user or assistant messages - you are *NEVER* in run mode.
|
|
693
|
+
You must ONLY edit your own agent files. You assist users by running their agent with the "message_user_agent" tool.
|
|
694
|
+
|
|
695
|
+
Any context from run mode the user is asking you to change behavior of their agent.
|
|
696
|
+
|
|
697
|
+
<integrations>
|
|
698
|
+
Users will often ask for integrations with third-party services.
|
|
699
|
+
|
|
700
|
+
It is *YOUR RESPONSIBILITY* to ensure the user obtains the necessary credentials to test/use the integration.
|
|
701
|
+
|
|
702
|
+
GitHub:
|
|
703
|
+
1. If the user is asking for real-time data (e.g. notifications, alerts, monitoring, "notify me when", "tell me when", anything
|
|
704
|
+
requiring webhooks), **create a GitHub App using the create_github_app tool**.
|
|
705
|
+
2. If the user is asking for query/read capabilities (e.g. "what are people working on", "show me issues", "analyze PRs"), **use a
|
|
706
|
+
personal access token**. If the \`gh\` CLI is installed, ask them if they'd like you to run \`gh auth login --scopes <scopes>\` (which if
|
|
707
|
+
you execute, do it with a low process_wait timeout so you can prompt the user quickly). You can obtain the token using \`gh auth token\`.
|
|
708
|
+
3. Default to the simpler token approach unless real-time/proactive behavior is explicitly needed.
|
|
709
|
+
|
|
710
|
+
Slack:
|
|
711
|
+
1. Scopes and events are the most important part of the Slack App manifest. Ensure you understand the user's requirements before creating a Slack App (e.g. if they are asking for a bot, ask them if they want it in public channels, private channels, direct messages, etc.)
|
|
712
|
+
2. *ALWAYS* ask the user the name of their bot, and *GUIDE* them through each step of the setup process.
|
|
713
|
+
</integrations>
|
|
714
|
+
|
|
715
|
+
<agent_development>
|
|
716
|
+
1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
|
|
717
|
+
2. Use the \`message_user_agent\` tool to test the agent after you make changes.
|
|
718
|
+
</agent_development>
|
|
719
|
+
`});let v=`This project is a Blink agent.
|
|
647
720
|
|
|
648
721
|
You are an expert software engineer, which makes you an expert agent developer. You are highly idiomatic, opinionated, concise, and precise. The user prefers accuracy over speed.
|
|
649
722
|
|
|
@@ -691,6 +764,10 @@ Changes to the agent are hot-reloaded. As you make edits, the user can immediate
|
|
|
691
764
|
5. Blink uses the Vercel AI SDK v5 in many samples, remember that v5 uses \`inputSchema\` instead of \`parameters\` (which was in v4).
|
|
692
765
|
6. Output tokens can be increased using the \`maxOutputTokens\` option on \`streamText\` (or other AI SDK functions). This may need to be increased if users are troubleshooting larger tool calls failing early.
|
|
693
766
|
7. Use the TypeScript language service tools (\`typescript_completions\`, \`typescript_quickinfo\`, \`typescript_definition\`, \`typescript_diagnostics\`) to understand APIs, discover available methods, check types, and debug errors. These tools use tsserver to provide IDE-like intelligence.
|
|
767
|
+
|
|
768
|
+
If the user is asking for a behavioral change, you should update the agent's system prompt.
|
|
769
|
+
This will not ensure the behavior, but it will guide the agent towards the desired behavior.
|
|
770
|
+
If the user needs 100% behavioral certainty, adjust tool behavior instead.
|
|
694
771
|
</agent_development>
|
|
695
772
|
|
|
696
773
|
<agent_web_requests>
|
|
@@ -944,6 +1021,49 @@ agent.on("chat", async ({ messages }) => {
|
|
|
944
1021
|
})
|
|
945
1022
|
\`\`\`
|
|
946
1023
|
|
|
1024
|
+
Slack SDK Notes:
|
|
1025
|
+
- "app_mention" event is triggered in both private channels and public channels.
|
|
1026
|
+
- "message" event is triggered regardless of being mentioned or not, and will *also* be fired when "app_mention" is triggered.
|
|
1027
|
+
- *NEVER* register app event listeners in the "on" handler of the agent. This will cause the handler to be called multiple times.
|
|
1028
|
+
- Think about how you scope chats - for example, in IMs or if the user wants to make a bot for a whole channel, you would not want to add "ts" or "thread_ts" to the chat key.
|
|
1029
|
+
- When using "assistant.threads.setStatus", you need to ensure the status of that same "thread_ts" is cleared. You can do this by inserting a message part that directs the agent to clear the status (there is a tool if using @blink-sdk/slack called "reportStatus" that does this). e.g. \`message.parts.push({ type: "text", text: "*INTERNAL INSTRUCTION*: Clear the status of this thread after you finish: channel=\${channel} thread_ts=\${thread_ts}" })\`
|
|
1030
|
+
- The Slack SDK has many functions that allow users to completely customize the message format. If the user asks for customization, look at the types for @blink-sdk/slack - specifically: "createPartsFromMessageMetadata", "createMessageFromEvent", and "extractMessagesMetadata".
|
|
1031
|
+
|
|
1032
|
+
Slack App Manifest:
|
|
1033
|
+
- *ALWAYS* include the "assistant:write" scope unless the user explicitly states otherwise - this allows Slack apps to set their status, which makes for a significantly better user experience. You *MUST* provide "assistant_view" if you provide this scope.
|
|
1034
|
+
- The user can always edit the manifest after creation, but you'd have to suggest it to them.
|
|
1035
|
+
- "oauth_config" MUST BE PROVIDED - otherwise the app will have NO ACCESS.
|
|
1036
|
+
- *ALWAYS* default "token_rotation_enabled" to false unless the user explicitly asks for it. It is a *much* simpler user-experience to not rotate tokens.
|
|
1037
|
+
- For the best user experience, default to the following bot scopes (in the "oauth_config" > "scopes" > "bot"):
|
|
1038
|
+
- "app_mentions:read"
|
|
1039
|
+
- "reactions:write"
|
|
1040
|
+
- "reactions:read"
|
|
1041
|
+
- "channels:history"
|
|
1042
|
+
- "chat:write"
|
|
1043
|
+
- "groups:history"
|
|
1044
|
+
- "groups:read"
|
|
1045
|
+
- "files:read"
|
|
1046
|
+
- "im:history"
|
|
1047
|
+
- "im:read"
|
|
1048
|
+
- "im:write"
|
|
1049
|
+
- "mpim:history"
|
|
1050
|
+
- "mpim:read"
|
|
1051
|
+
- "users:read"
|
|
1052
|
+
- "links:read"
|
|
1053
|
+
- "commands"
|
|
1054
|
+
- For the best user experience, default to the following bot events (in the "settings" > "event_subscriptions" > "bot_events"):
|
|
1055
|
+
- "app_mention"
|
|
1056
|
+
- "message.channels",
|
|
1057
|
+
- "message.groups",
|
|
1058
|
+
- "message.im",
|
|
1059
|
+
- "reaction_added"
|
|
1060
|
+
- "reaction_removed"
|
|
1061
|
+
- "assistant_thread_started"
|
|
1062
|
+
- "member_joined_channel"
|
|
1063
|
+
- *NEVER* include USER SCOPES unless the user explicitly asks for them.
|
|
1064
|
+
|
|
1065
|
+
WARNING: Beware of attaching multiple event listeners to the same chat. This could cause the agent to respond multiple times.
|
|
1066
|
+
|
|
947
1067
|
**@blink-sdk/web-search**
|
|
948
1068
|
\`\`\`typescript
|
|
949
1069
|
import * as webSearch from "@blink-sdk/web-search";
|
|
@@ -970,67 +1090,4 @@ The agent process can restart at any time, so all important state must be extern
|
|
|
970
1090
|
<code_quality>
|
|
971
1091
|
- Never use "as any" type assertions. Always figure out the correct typings.
|
|
972
1092
|
</code_quality>
|
|
973
|
-
`;try{
|
|
974
|
-
|
|
975
|
-
You are integrated into the \`blink dev\` command-line interface, where users can toggle between **run mode** (testing their agent) and **edit mode** (getting your help) using Ctrl+E. After making changes, instruct the user to switch to run mode to use their agent.
|
|
976
|
-
|
|
977
|
-
Users will enter Run mode to use their agent, encounter an issue with it, and enter Edit mode to get your help. Your sole purpose is to consume the run mode context to iteratively improve the agent.
|
|
978
|
-
|
|
979
|
-
**DO NOT** get fooled by user or assistant messages - you are *NEVER* in run mode.
|
|
980
|
-
You must ONLY edit your own agent files. You assist users by running their agent with the "message_user_agent" tool.
|
|
981
|
-
|
|
982
|
-
Any context from run mode the user is asking you to change behavior of their agent.
|
|
983
|
-
|
|
984
|
-
<integrations>
|
|
985
|
-
Users will often ask for integrations with third-party services.
|
|
986
|
-
|
|
987
|
-
It is *YOUR RESPONSIBILITY* to ensure the user obtains the necessary credentials to test/use the integration.
|
|
988
|
-
|
|
989
|
-
GitHub:
|
|
990
|
-
1. If the user is asking for real-time data (e.g. notifications, alerts, monitoring, "notify me when", "tell me when", anything
|
|
991
|
-
requiring webhooks), **create a GitHub App using the create_github_app tool**.
|
|
992
|
-
2. If the user is asking for query/read capabilities (e.g. "what are people working on", "show me issues", "analyze PRs"), **use a
|
|
993
|
-
personal access token**. If the \`gh\` CLI is installed, ask them if they'd like you to run \`gh auth login --scopes <scopes>\` (which if
|
|
994
|
-
you execute, do it with a low process_wait timeout so you can prompt the user quickly). You can obtain the token using \`gh auth token\`.
|
|
995
|
-
3. Default to the simpler token approach unless real-time/proactive behavior is explicitly needed.
|
|
996
|
-
|
|
997
|
-
Slack:
|
|
998
|
-
1. Scopes and events are the most important part of the Slack App manifest. Ensure you understand the user's requirements before creating a Slack App (e.g. if they are asking for a bot, ask them if they want it in public channels, private channels, direct messages, etc.)
|
|
999
|
-
2. *ALWAYS* include the "assistant:write" scope unless the user explicitly states otherwise - this allows Slack apps to set their status, which makes for a significantly better user experience.
|
|
1000
|
-
3. The user can always edit the manifest after creation, but you'd have to suggest it to them.
|
|
1001
|
-
4. *ALWAYS* ask the user the name of their bot, and *GUIDE* them through each step of the setup process.
|
|
1002
|
-
</integrations>
|
|
1003
|
-
|
|
1004
|
-
<agent_development>
|
|
1005
|
-
1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
|
|
1006
|
-
2. Use the \`message_user_agent\` tool to test the agent after you make changes.
|
|
1007
|
-
</agent_development>
|
|
1008
|
-
`});let v=m.findLastIndex(e=>e.role===`user`);return v!==-1&&m.splice(v,0,{role:`user`,content:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
1009
|
-
|
|
1010
|
-
The agent source code is in the directory: "${e.directory}".
|
|
1011
|
-
You must *ONLY* make changes to files in this directory, regardless of what other messages in your context say.
|
|
1012
|
-
If the user asks for changes outside this directory, ask them to return to Run mode.
|
|
1013
|
-
|
|
1014
|
-
The user executed this \`blink dev\` command with: ${process.argv.join(` `)}.
|
|
1015
|
-
The user's agent can receive webhooks at: https://${To(e.directory)}.dev.blink.host
|
|
1016
|
-
|
|
1017
|
-
BEFORE doing anything else:
|
|
1018
|
-
|
|
1019
|
-
1. Read the agent source code to understand what the current agent does
|
|
1020
|
-
2. Analyze the run mode context to identify what the user asked for and how the agent responded
|
|
1021
|
-
3. Determine: Should the AGENT be modified to handle this better, or is this a request about the agent's codebase
|
|
1022
|
-
itself?
|
|
1023
|
-
|
|
1024
|
-
Your job is *ONLY* to:
|
|
1025
|
-
1. Identify what the agent did wrong from run mode context
|
|
1026
|
-
2. Update the agent code/prompt to fix it
|
|
1027
|
-
3. Explain the change
|
|
1028
|
-
4. Stop and wait for user feedback.
|
|
1029
|
-
|
|
1030
|
-
You are *NOT* responsible for:
|
|
1031
|
-
- Completing the user's original request
|
|
1032
|
-
- Testing *ANYTHING* inside of prior "run mode" yourself.
|
|
1033
|
-
- Continuing any work the run mode agent started
|
|
1034
|
-
|
|
1035
|
-
Your job is to improve the agent based on run mode failures, NOT to complete the user's original run-mode request yourself.
|
|
1036
|
-
`}),(0,g.streamText)({model:Kp(e.token),messages:m,maxOutputTokens:64e3,tools:p,abortSignal:c,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{i=e},cleanup:()=>{a&&=(a.close(),void 0)}}}function Kp(e){return process.env.ANTHROPIC_API_KEY?n.createAnthropic({apiKey:process.env.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`):process.env.OPENAI_API_KEY?n.createOpenAI({apiKey:process.env.OPENAI_API_KEY}).responses(`gpt-5`):n.model(`anthropic/claude-sonnet-4.5`,{token:e})}function qp(e){let[t,r]=(0,v.useState)(void 0),[i,a]=(0,v.useState)(void 0),o=(0,v.useRef)(void 0);return(0,v.useEffect)(()=>{let t=new AbortController,i=!1;return a(void 0),r(void 0),(async()=>{o.current=Gp({directory:e.directory,token:e.token});let i=await Jp(),a=o.current.agent.serve({port:i,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{a.close()}catch{}o.current?.cleanup()});let s=new n.Client({baseUrl:`http://127.0.0.1:${i}`});for(;!t.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;r(s)})().catch(e=>{i||a(e instanceof Error?e:Error(String(e)))}),()=>{i=!0,t.abort()}},[e.directory,e.apiServerUrl,e.token]),(0,v.useMemo)(()=>({client:t,error:i,setUserAgentUrl:e=>{o.current?.setUserAgentUrl(e)}}),[t,i])}async function Jp(){let e=(0,m.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function Yp(e){let{directory:t}=e,[i,a]=(0,v.useState)(),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(`run`),u=(0,v.useRef)(`run`);(0,v.useEffect)(()=>{u.current=c},[c]);let d=(0,v.useCallback)(t=>{l(t),e.onModeChange?.(t),a(void 0)},[e.onModeChange]),f=(0,v.useCallback)(()=>{d(c===`run`?`edit`:`run`)},[c,d]),{error:p,status:m,result:h,entry:_}=Ga({directory:t,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),y=Wa({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),b=rs(t),x=(0,v.useMemo)(()=>{let e=y.token;return e?{...b,BLINK_TOKEN:e}:b},[b,y.token]),S=(0,v.useRef)(void 0);(0,v.useEffect)(()=>{let t=Object.keys(x);if(t.length===S.current||S.current===void 0){S.current=t.length;return}S.current=t.length,e.onEnvLoaded?.(t)},[x,e.onEnvLoaded]);let C=(0,v.useRef)(void 0),w=(0,v.useMemo)(()=>Xo({port:0,dataDirectory:(0,r.join)(t,`data`),getAgent:()=>C.current}),[t]),{agent:T,logs:D,error:O,capabilities:k}=E({buildResult:h,env:x,apiServerUrl:w.url}),{client:A,error:j,setUserAgentUrl:M}=qp({directory:t,apiServerUrl:w.url,token:y.token}),[N,P]=(0,v.useState)(`00000000-0000-0000-0000-000000000000`);(0,v.useEffect)(()=>{T&&M(T.baseUrl),c===`run`?T?C.current=T:(C.current=void 0,w.getChatManager(N)?.stopStreaming()):c===`edit`&&(A?C.current=A:(C.current=void 0,w.getChatManager(N)?.stopStreaming()))},[T,A,c,N,w]);let F=(0,v.useRef)(void 0),I=wo({chatId:N,agent:c===`run`?T:A,chatsDirectory:w.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&F.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:F.current}:e.metadata;return{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:u.current,metadata:t}},filterMessages:e=>u.current===`edit`?!0:!(So(e.metadata)||e.mode===`edit`)}),ee=(0,v.useRef)(0);(0,v.useEffect)(()=>{if(D.length===ee.current)return;let t=ee.current;for(let n of D.slice(t))e.onAgentLog?.(n);ee.current=D.length},[D,e.onAgentLog,I.upsertMessage]);let[L,R]=(0,v.useState)([]);(0,v.useEffect)(()=>{w.listChats().then(e=>{R(e.map(e=>e.key))})},[w]),(0,v.useEffect)(()=>{N&&!L.includes(N)&&R(e=>[...e,N])},[N,L]);let z=(0,v.useMemo)(()=>To(t),[t]),B=Qo({id:z,disabled:!k?.request,onRequest:async t=>{if(!T)throw Error(`No agent`);let n=new URL(t.url),r=new URL(T.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});(0,v.useEffect)(()=>{B.status===`connected`&&e.onDevhookConnected?.(`https://${B.id}.dev.blink.host`)},[B.status,B.id]);let{schema:V,options:H,error:U,setOption:te}=Zo({agent:c===`run`?T:A,capabilities:k,messages:I.messages});(0,v.useEffect)(()=>{F.current=H},[H]);let W=(0,v.useMemo)(()=>{let e=new Map;return O&&c===`run`&&e.set(`agent`,O.message),j&&c===`edit`&&e.set(`editAgent`,`Edit agent error: ${j.message}`),I.error&&m!==`building`&&e.set(`chat`,`Chat error: ${I.error}`),U&&e.set(`options`,`Options error: ${U.message}`),e},[O,j,I.error,U,c,m]),ne=(0,v.useRef)(new Map);(0,v.useEffect)(()=>{let t=ne.current,n=W;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ne.current=new Map(n)},[W,e.onError]);let G=(0,v.useMemo)(()=>{let e=[...I.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||i===e.id)return;let t=e.parts.filter(g.isToolOrDynamicToolUIPart);if(t.length!==0&&t.some(e=>n.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[I.messages,i]),re=(0,v.useCallback)(async(e,t)=>{if(!G)return;t&&e&&s(!0),a(G.id);let r=I.messages;if(r.length===0)return;let i=r[r.length-1];if(!i||i.role!==`assistant`||!Array.isArray(i.parts))return;let o=i.parts.map(t=>t.output&&n.isToolApprovalOutput(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await I.upsertMessage({...i,parts:o}),await I.start()},[G,I]);(0,v.useEffect)(()=>{o&&G&&re(!0)},[o,G,re]);let K=(0,v.useCallback)(()=>{let e=crypto.randomUUID();P(e),R(t=>[...t,e]),a(void 0)},[]),ie=(0,v.useCallback)(e=>{P(e),a(void 0)},[]),ae=(0,v.useMemo)(()=>{if(G)return{message:G,approve:e=>re(!0,e),reject:()=>re(!1),autoApproveEnabled:o}},[G,re,o]),oe=(0,v.useMemo)(()=>{let e=I.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[I.messages]),se=(0,v.useMemo)(()=>{if(I.status!==`streaming`)return!1;if(!I.streamingMessage)return!0;let e=I.streamingMessage.parts.filter(g.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[I.status,I.streamingMessage]);return{mode:c,setMode:d,toggleMode:f,chat:I,chats:L,switchChat:ie,newChat:K,build:{status:m,error:p,entrypoint:_},devhook:{connected:B.status===`connected`,url:B.status===`connected`?`https://${B.id}.dev.blink.host`:void 0},capabilities:k,options:{schema:V,selected:H,error:U,setOption:te},approval:ae,tokenUsage:oe,auth:y,server:w,showWaitingPlaceholder:se}}exports.useAgent=E,exports.useAuth=Wa,exports.useBundler=Ga,exports.useChat=wo,exports.useDevMode=Yp,exports.useDevhook=Qo,exports.useDotenv=rs,exports.useEditAgent=qp,exports.useOptions=Zo;
|
|
1093
|
+
`;try{v=await(0,g.readFile)((0,d.join)(e.directory,`AGENTS.md`),`utf-8`)}catch{}return m.unshift({role:`system`,content:v}),(0,h.streamText)({model:Kp(e.token),messages:m,maxOutputTokens:64e3,tools:p,abortSignal:o,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:n,setUserAgentUrl:e=>{r=e},cleanup:()=>{i&&=(i.close(),void 0)}}}function Kp(e){return process.env.ANTHROPIC_API_KEY?t.createAnthropic({apiKey:process.env.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`):process.env.OPENAI_API_KEY?t.createOpenAI({apiKey:process.env.OPENAI_API_KEY}).responses(`gpt-5`):t.model(`anthropic/claude-sonnet-4.5`,{token:e})}function qp(e){let[n,r]=(0,v.useState)(void 0),[i,a]=(0,v.useState)(void 0),o=(0,v.useRef)(void 0);return(0,v.useEffect)(()=>{let n=new AbortController,i=!1;return a(void 0),r(void 0),(async()=>{o.current=Gp({directory:e.directory,token:e.token});let i=await Jp(),a=o.current.agent.serve({port:i,host:`127.0.0.1`,apiUrl:e.apiServerUrl});n.signal.addEventListener(`abort`,()=>{try{a.close()}catch{}o.current?.cleanup()});let s=new t.Client({baseUrl:`http://127.0.0.1:${i}`});for(;!n.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(n.signal.aborted)throw n.signal.reason;r(s)})().catch(e=>{i||a(e instanceof Error?e:Error(String(e)))}),()=>{i=!0,n.abort()}},[e.directory,e.apiServerUrl,e.token]),(0,v.useMemo)(()=>({client:n,error:i,setUserAgentUrl:e=>{o.current?.setUserAgentUrl(e)}}),[n,i])}async function Jp(){let e=(0,u.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function Yp(e){let{directory:n}=e,[r,i]=(0,v.useState)(),[a,o]=(0,v.useState)(!1),[s,c]=(0,v.useState)(`run`),l=(0,v.useRef)(`run`);(0,v.useEffect)(()=>{l.current=s},[s]);let u=(0,v.useCallback)(t=>{c(t),e.onModeChange?.(t),i(void 0)},[e.onModeChange]),f=(0,v.useCallback)(()=>{u(s===`run`?`edit`:`run`)},[s,u]),{error:p,status:m,result:g,entry:_}=Ga({directory:n,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),y=Wa({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),b=rs(n),x=(0,v.useMemo)(()=>{let e=y.token;return e?{...b,BLINK_TOKEN:e}:b},[b,y.token]),S=(0,v.useRef)(void 0);(0,v.useEffect)(()=>{let t=Object.keys(x);if(t.length===S.current||S.current===void 0){S.current=t.length;return}S.current=t.length,e.onEnvLoaded?.(t)},[x,e.onEnvLoaded]);let C=(0,v.useRef)(void 0),w=(0,v.useMemo)(()=>Xo({port:0,dataDirectory:(0,d.join)(n,`data`),getAgent:()=>C.current}),[n]),{agent:T,logs:D,error:O,capabilities:k}=E({buildResult:g,env:x,apiServerUrl:w.url}),{client:A,error:j,setUserAgentUrl:M}=qp({directory:n,apiServerUrl:w.url,token:y.token}),[N,P]=(0,v.useState)(`00000000-0000-0000-0000-000000000000`);(0,v.useEffect)(()=>{T&&M(T.baseUrl),s===`run`?T?C.current=T:(C.current=void 0,w.getChatManager(N)?.stopStreaming()):s===`edit`&&(A?C.current=A:(C.current=void 0,w.getChatManager(N)?.stopStreaming()))},[T,A,s,N,w]);let F=(0,v.useRef)(void 0),I=wo({chatId:N,agent:s===`run`?T:A,chatsDirectory:w.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&F.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:F.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=l.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:l.current,metadata:t}},filterMessages:e=>l.current===`edit`?!0:!(So(e.metadata)||e.mode===`edit`)}),ee=(0,v.useRef)(0);(0,v.useEffect)(()=>{if(D.length===ee.current)return;let t=ee.current;for(let n of D.slice(t))e.onAgentLog?.(n);ee.current=D.length},[D,e.onAgentLog,I.upsertMessage]);let[L,R]=(0,v.useState)([]);(0,v.useEffect)(()=>{w.listChats().then(e=>{R(e.map(e=>e.key))})},[w]),(0,v.useEffect)(()=>{N&&!L.includes(N)&&R(e=>[...e,N])},[N,L]);let z=(0,v.useMemo)(()=>To(n),[n]),B=Qo({id:z,disabled:!k?.request,onRequest:async t=>{if(!T)throw Error(`No agent`);let n=new URL(t.url),r=new URL(T.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});(0,v.useEffect)(()=>{B.status===`connected`&&e.onDevhookConnected?.(`https://${B.id}.dev.blink.host`)},[B.status,B.id]);let{schema:V,options:H,error:U,setOption:te}=Zo({agent:s===`run`?T:A,capabilities:k,messages:I.messages});(0,v.useEffect)(()=>{F.current=H},[H]);let W=(0,v.useMemo)(()=>{let e=new Map;return O&&s===`run`&&e.set(`agent`,O.message),j&&s===`edit`&&e.set(`editAgent`,`Edit agent error: ${j.message}`),I.error&&m!==`building`&&e.set(`chat`,`Chat error: ${I.error}`),U&&e.set(`options`,`Options error: ${U.message}`),e},[O,j,I.error,U,s,m]),ne=(0,v.useRef)(new Map);(0,v.useEffect)(()=>{let t=ne.current,n=W;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ne.current=new Map(n)},[W,e.onError]);let G=(0,v.useMemo)(()=>{let e=[...I.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||r===e.id)return;let n=e.parts.filter(h.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[I.messages,r]),re=(0,v.useCallback)(async(e,n)=>{if(!G)return;n&&e&&o(!0),i(G.id);let r=I.messages;if(r.length===0)return;let a=r[r.length-1];if(!a||a.role!==`assistant`||!Array.isArray(a.parts))return;let s=a.parts.map(n=>n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n);await I.upsertMessage({...a,parts:s}),await I.start()},[G,I]);(0,v.useEffect)(()=>{a&&G&&re(!0)},[a,G,re]);let K=(0,v.useCallback)(()=>{let e=crypto.randomUUID();P(e),R(t=>[...t,e]),i(void 0)},[]),ie=(0,v.useCallback)(e=>{P(e),i(void 0)},[]),ae=(0,v.useMemo)(()=>{if(G)return{message:G,approve:e=>re(!0,e),reject:()=>re(!1),autoApproveEnabled:a}},[G,re,a]),oe=(0,v.useMemo)(()=>{let e=I.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[I.messages]),se=(0,v.useMemo)(()=>{if(I.status!==`streaming`)return!1;if(!I.streamingMessage)return!0;let e=I.streamingMessage.parts.filter(h.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[I.status,I.streamingMessage]);return{mode:s,setMode:u,toggleMode:f,chat:I,chats:L,switchChat:ie,newChat:K,build:{status:m,error:p,entrypoint:_},devhook:{connected:B.status===`connected`,url:B.status===`connected`?`https://${B.id}.dev.blink.host`:void 0},capabilities:k,options:{schema:V,selected:H,error:U,setOption:te},approval:ae,tokenUsage:oe,auth:y,server:w,showWaitingPlaceholder:se}}exports.useAgent=E,exports.useAuth=Wa,exports.useBundler=Ga,exports.useChat=wo,exports.useDevMode=Yp,exports.useDevhook=Qo,exports.useDotenv=rs,exports.useEditAgent=qp,exports.useOptions=Zo;
|