blink 0.1.111 → 0.1.112

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.
@@ -36,7 +36,7 @@ ${Or}`),t.includes(`
36
36
  `)&&(n=3+w(t.slice(t.lastIndexOf(`
37
37
  `))).length);let e=w(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
38
38
  ${Or}${t.trimStart()}`),n=3+w(t.trimStart()).length)}process.stdout.write(`
39
- `)},info:e=>kr.message(e,{symbol:_r.default.blue(Cr)}),success:e=>kr.message(e,{symbol:_r.default.green(wr)}),step:e=>kr.message(e,{symbol:_r.default.green(xr)}),warn:e=>kr.message(e,{symbol:_r.default.yellow(Tr)}),warning:e=>kr.warn(e),error:e=>kr.message(e,{symbol:_r.default.red(Er)})};let Ar;function jr(){try{return y.statSync(`/.dockerenv`),!0}catch{return!1}}function Mr(){try{return y.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Nr(){return Ar===void 0&&(Ar=jr()||Mr()),Ar}let Pr;const Fr=()=>{try{return y.statSync(`/run/.containerenv`),!0}catch{return!1}};function Ir(){return Pr===void 0&&(Pr=Fr()||Nr()),Pr}const Lr=()=>{if(F.platform!==`linux`)return!1;if(ve.release().toLowerCase().includes(`microsoft`))return!Ir();try{return y.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Ir():!1}catch{return!1}};var Rr=F.env.__IS_WSL_TEST__?Lr:Lr();const zr=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await ge.access(n,_e.F_OK),r=!0}catch{}if(!r)return e;let i=await ge.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}})(),Br=async()=>`${await zr()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Vr=async()=>Rr?Br():`${F.env.SYSTEMROOT||F.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Hr(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 Ur=C(me);async function Wr(){if(F.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Ur(`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 Gr=C(me);async function Kr(e,{humanReadableOutput:t=!0,signal:n}={}){if(F.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Gr(`osascript`,[`-e`,e,r],i);return a.trim()}async function qr(e){return Kr(`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 Jr=C(me),Yr={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 Xr=class extends Error{};async function Zr(e=Jr){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 Xr(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Yr[r];if(!i)throw new Xr(`Unknown browser ID: ${r}`);return i}const Qr=C(me),$r=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function ei(){if(F.platform===`darwin`){let e=await Wr();return{name:await qr(e),id:e}}if(F.platform===`linux`){let{stdout:e}=await Qr(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:$r(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(F.platform===`win32`)return Zr();throw Error(`Only macOS, Linux, and Windows are supported`)}const ti=C(pe.execFile),ni=de.dirname(x(import.meta.url)),ri=de.join(ni,`xdg-open`),{platform:ii,arch:ai}=F;async function oi(){let e=await Vr(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=_.from(t,`utf16le`).toString(`base64`),{stdout:r}=await ti(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 si=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},ci=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return si(e.app,t=>ci({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return si(t,t=>ci({...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=Rr?await oi():await ei();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),ci({...e,app:{name:fi[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(ii===`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(ii===`win32`||Rr&&!Ir()&&!t){r=await Vr(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Rr||(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=_.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!ni||ni===`/`,t=!1;try{await ge.access(ri,_e.X_OK),t=!0}catch{}r=F.versions.electron??(ii===`android`||e||!t)?`xdg-open`:ri}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}ii===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=pe.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)},li=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return ci({...t,target:e})};function ui(e){if(typeof e==`string`||Array.isArray(e))return e;let{[ai]:t}=e;if(!t)throw Error(`${ai} is not supported`);return t}function di({[ii]:e},{wsl:t}){if(t&&Rr)return ui(t);if(!e)throw Error(`${ii} is not supported`);return ui(e)}const fi={};Hr(fi,`chrome`,()=>di({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`]}})),Hr(fi,`brave`,()=>di({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`]}})),Hr(fi,`firefox`,()=>di({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Hr(fi,`edge`,()=>di({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Hr(fi,`browser`,()=>`browser`),Hr(fi,`browserPrivate`,()=>`browserPrivate`);var pi=li;function mi(e){let t=e||_i();if(A(t)){let e=M(t,`utf8`);return JSON.parse(e).token}}function hi(e,t){let n=t||_i();A(D(n))||j(D(n),{recursive:!0}),ee(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function gi(e){let t=e||_i();A(t)&&N(t)}function _i(){let e=Kn(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return O(e[0],`auth.json`)}function vi(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=K(),[s,c]=K(()=>mi(i)),[l,u]=K(),d=G(n),f=G(r);W(()=>{d.current=n,f.current=r},[n,r]);let p=U(async()=>{u(void 0);try{let e=mi(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new Ln({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=U(async()=>{u(void 0);try{let e=new Ln,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();hi(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=U(()=>{gi(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return W(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function yi(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=oe(()=>h(t),[t]),[o,s]=K(void 0),[c,l]=K(void 0),[u,d]=K(`building`),f=G(n),p=G(r),m=G(i);return W(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),W(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),oe(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function bi(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function xi(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Si=/^\.+(\\|\/)|^\.+$/,Ci=/[. ]+$/,wi=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Ti=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ei=e=>e===`‍`,Di=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Oi=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let ki;function Ai(){return ki??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),ki}function ji(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(bi().test(n)||[...n].some(e=>Ti.test(e)&&!Ei(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Oi,` `),n.length>0&&(e=e.replaceAll(Di,`$1`)),e=e.replace(Ci,``),e=e.replace(Si,n),e=e.replace(bi(),n),e=e.replaceAll(wi,e=>Ei(e)?e:n),e.length===0&&(e=n),e=xi().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=Mi(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Mi(n,a)+i}}return e}function Mi(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Ai().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Ni(e){return`${e}.lock`}function Pi(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Fi(e,t={}){let n=Ni(e),r=process.pid.toString();try{return v.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(v.readFileSync(n,`utf8`),10)}catch{return v.unlinkSync(n),Fi(e,{...t,stale:0})}if(!Pi(i))try{return v.unlinkSync(n),Fi(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Fi(e,{...t,stale:0});throw n}return!1}}async function Ii(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=ue.resolve(e),i=0;for(;i<=n.retries;){if(Fi(r,n))return()=>Li(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 Li(e){let t=ue.resolve(e),n=Ni(t);try{if(parseInt(v.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}v.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Ri(e){let t=ue.resolve(e),n=Ni(t);try{if(!v.existsSync(n))return{locked:!1};let e=v.readFileSync(n,`utf8`),t=parseInt(e,10);return Pi(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const zi=e=>{v.mkdirSync(e,{recursive:!0})},Bi=e=>{try{v.fdatasyncSync(e)}catch{}try{v.closeSync(e)}catch{}},Vi=e=>{try{let t=v.openSync(e,`r`);try{v.fsyncSync(t)}finally{v.closeSync(t)}}catch{}},Hi=(e,t)=>{let n=ue.dirname(e);zi(n);let r=ue.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=v.openSync(r,`w`),v.writeFileSync(i,t,`utf-8`),Bi(i),i=void 0,v.renameSync(r,e),Vi(e),Vi(n)}catch(e){if(i!==void 0)try{v.closeSync(i)}catch{}try{v.rmSync(r,{force:!0})}catch{}throw e}},Ui=(e,t)=>{let n=new Map,r,i=e=>{if(v.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(v.readFileSync(e,`utf-8`))},a=(e,t)=>{Hi(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=ue.join(e,`index.json`);zi(e),v.existsSync(t)||v.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Ii(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=ue.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=ue.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return ue.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=ue.join(e,n);if(v.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(v.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=ji(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=ue.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!v.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=ue.join(e,i),a=v.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Ri(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 l(r);if(!a){let t=ji(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=ue.join(e,t);zi(e),v.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Ri(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 f=await Ii(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...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=ue.join(e,n);try{v.rmSync(i,{force:!0}),Vi(e)}catch{}}}finally{await t()}},async release(){f(),n.delete(r)}}},dispose(){n.clear()}}},Wi=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=ue.join(e,`index.json`),u=()=>{try{if(!v.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=v.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(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)}},f=(t,n,r=!1)=>{let i=ue.join(e,n);try{let e=v.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(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=Ri(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(v.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{v.mkdirSync(e,{recursive:!0})}catch{}a=v.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),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 Gi({chatKey:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Ki}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,chat:{key:e}},{signal:r}),l=R({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 Ki=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(ne);return n.length===0||n.some(e=>l(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},qi=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Ji(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Yi=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,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=Ui(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Wi(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}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,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).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,messages:(this.chat?.messages??[]).filter(e=>!Ji(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 upsertMessage(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=e;if(this.serializeMessage){let t=this.serializeMessage(e);if(t===void 0)return;n=t}let i=n.id||crypto.randomUUID(),a=n.mode||`run`,o=qi(n,a,i),s=t.messages.find(e=>e.id===o.id)?t.messages.map(e=>e.id===o.id?o:e):[...t.messages,o];this.chat={...t,updated_at:new Date().toISOString(),messages:s},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessage(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>t.id!==e),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessage(e){if(this.chat.error=void 0,this.status===`streaming`){this.queue.push(e),this.notifyListeners();return}this.queue=[e],await this.processQueueOrRun()}async start(){await this.processQueueOrRun()}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.shift();this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r&&await this.upsertMessage(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!ne(e)||e.input!==``?e:{...e,input:{}})}));let a=await Gi({agent:this.agent,chatKey:this.chatId,signal:n.signal,messages:i}),o=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)},s=a.getReader();n.signal.addEventListener(`abort`,()=>{s.cancel().catch(()=>{})},{once:!0});try{for(;;){let{done:e,value:t}=await s.read();if(e||n.signal.aborted)break;this.streamingMessage&&t.id!==this.streamingMessage.id&&await o(this.streamingMessage),this.streamingMessage=this.serializeMessage?this.serializeMessage(t):t,this.notifyListeners()}}finally{n.signal.removeEventListener(`abort`,abortHandler),s.releaseLock()}this.streamingMessage&&await o(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 Xi(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=G(null),[s,c]=K({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});W(()=>{o.current&&o.current.dispose();let e=new Yi({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]),W(()=>{o.current&&o.current.setAgent(n)},[n]);let l=U(async e=>{o.current&&await o.current.sendMessage(e)},[]),u=U(async e=>{o.current&&await o.current.upsertMessage(e)},[]),d=U(()=>{o.current&&o.current.stopStreaming()},[]),f=U(async()=>{o.current&&await o.current.resetChat()},[]),p=U(()=>{o.current&&o.current.clearQueue()},[]),m=U(async e=>{o.current&&await o.current.deleteMessage(e)},[]),h=U(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function Zi(e){let t=O(e,`data`,`devhook.txt`);if(j(D(t),{recursive:!0}),A(t))return M(t,`utf-8`);let n=crypto.randomUUID();return ee(t,n),n}const Qi=(e,t)=>e.json({error:t},400),$i=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}},ea=()=>new o,ta=ea().get(`/:key`,async e=>{let{key:t,err:n}=$i(e);if(n)return Qi(e,n);let r=await e.env.context.store.get(t);return e.json({value:r},200)}).post(`/:key`,m(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Qi(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Qi(t,`Value must be a string`):Qi(t,`Value is required`)}),async e=>{let{key:t,err:n}=$i(e);if(n)return Qi(e,n);let{value:r}=e.req.valid(`json`);return await e.env.context.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=$i(e);return n?Qi(e,n):(await e.env.context.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.context.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),na=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`}},ra=ea().basePath(`/:key`).post(`/`,async e=>{let{key:t,err:n}=na(e);return n?Qi(e,n):e.json(await e.env.context.chat.ensure(t),200)}).post(`/sendMessages`,m(`json`,(e,t)=>({message:e.message,options:e.options})),async e=>{let{key:t,err:n}=na(e);if(n)return Qi(e,n);let{message:r,options:i}=e.req.valid(`json`);try{await e.env.context.chat.message(t,r,i)}catch(t){return Qi(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),ia=ea().post(`/v1/traces`,async e=>e.env.context.otlp?e.env.context.otlp.traces(e.req.raw):e.body(null,204)),aa=new o().route(`/kv`,ta).route(`/chat`,ra).route(`/otlp`,ia);function oa(e){let t=fe(e.dataDirectory,`chats`),n={},r=fe(e.dataDirectory,`storage.json`);v.existsSync(r)&&(n=JSON.parse(v.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new Yi({chatId:n,chatsDirectory:t}),r.setAgent(e.getAgent()),i.set(n,r)),r},o={chat:{async ensure(e){let t=a(e).getState(),n=t.messages.length===0&&!t.created_at;return{key:e,created:n}},async message(e,t,n){let r=a(e),i=qi(t,`run`);if(n?.behavior===`append`){await r.upsertMessage(i);return}if(n?.behavior===`interrupt`){await r.sendMessage(i);return}await r.sendMessage(i)}},store:{get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,v.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],v.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).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+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}}},s=E(c(e=>aa.fetch(e,{context:o})));s.listen(e.port??0);let l=Ui(t,`id`);return{url:`http://127.0.0.1:${s.address().port}`,runtime:o,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),lockChat:e=>l.lock(e),startChat:async e=>{await a(e).start()},stopChat:e=>{i.get(e)?.stopStreaming()},dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),s.close()}}}function sa({agent:e,capabilities:t,messages:n}){let[r,i]=K(void 0),[a,o]=K(!0),[s,c]=K(void 0),l=G(s);W(()=>{l.current=s},[s]);let[d,f]=K(()=>u(n));W(()=>{f(e=>{let t=u(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[p,m]=K(void 0),h=U((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=U(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(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);W(()=>{if(!d&&!s){m(void 0);return}g()},[d,s,g]);let _=G(void 0),v=G(void 0);W(()=>{e!==v.current&&(v.current=e,c(void 0),m(void 0),i(void 0),o(!0),_.current=void 0)},[e]),W(()=>{if(t&&!t.ui||!e){c(void 0),m(void 0),i(void 0),_.current=void 0;return}let n=p?JSON.stringify(p):``;if(_.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),_.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,p]);let y=U((e,t)=>{g({[e]:t})},[g]);return{schema:s,options:p,setOption:y,loading:a,error:r}}function ca(e){let t=G(e.onRequest);W(()=>{t.current=e.onRequest},[e.onRequest]);let n=G(e.id??crypto.randomUUID()),[r,i]=K(`disconnected`);return W(()=>{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 Ln({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 la=e(((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}}})),ua=r(e(((e,t)=>{let r=n(`fs`),i=n(`path`),a=n(`os`),o=n(`crypto`),s=la().version,c=[`🔐 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 l(){return c[Math.floor(Math.random()*c.length)]}function u(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function d(){return process.stdout.isTTY}function f(e){return d()?`\x1b[2m${e}\x1b[0m`:e}let p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function m(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
39
+ `)},info:e=>kr.message(e,{symbol:_r.default.blue(Cr)}),success:e=>kr.message(e,{symbol:_r.default.green(wr)}),step:e=>kr.message(e,{symbol:_r.default.green(xr)}),warn:e=>kr.message(e,{symbol:_r.default.yellow(Tr)}),warning:e=>kr.warn(e),error:e=>kr.message(e,{symbol:_r.default.red(Er)})};let Ar;function jr(){try{return y.statSync(`/.dockerenv`),!0}catch{return!1}}function Mr(){try{return y.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Nr(){return Ar===void 0&&(Ar=jr()||Mr()),Ar}let Pr;const Fr=()=>{try{return y.statSync(`/run/.containerenv`),!0}catch{return!1}};function Ir(){return Pr===void 0&&(Pr=Fr()||Nr()),Pr}const Lr=()=>{if(F.platform!==`linux`)return!1;if(ve.release().toLowerCase().includes(`microsoft`))return!Ir();try{return y.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Ir():!1}catch{return!1}};var Rr=F.env.__IS_WSL_TEST__?Lr:Lr();const zr=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await ge.access(n,_e.F_OK),r=!0}catch{}if(!r)return e;let i=await ge.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}})(),Br=async()=>`${await zr()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Vr=async()=>Rr?Br():`${F.env.SYSTEMROOT||F.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Hr(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 Ur=C(me);async function Wr(){if(F.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Ur(`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 Gr=C(me);async function Kr(e,{humanReadableOutput:t=!0,signal:n}={}){if(F.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Gr(`osascript`,[`-e`,e,r],i);return a.trim()}async function qr(e){return Kr(`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 Jr=C(me),Yr={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 Xr=class extends Error{};async function Zr(e=Jr){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 Xr(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Yr[r];if(!i)throw new Xr(`Unknown browser ID: ${r}`);return i}const Qr=C(me),$r=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function ei(){if(F.platform===`darwin`){let e=await Wr();return{name:await qr(e),id:e}}if(F.platform===`linux`){let{stdout:e}=await Qr(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:$r(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(F.platform===`win32`)return Zr();throw Error(`Only macOS, Linux, and Windows are supported`)}const ti=C(pe.execFile),ni=de.dirname(x(import.meta.url)),ri=de.join(ni,`xdg-open`),{platform:ii,arch:ai}=F;async function oi(){let e=await Vr(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=_.from(t,`utf16le`).toString(`base64`),{stdout:r}=await ti(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 si=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},ci=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return si(e.app,t=>ci({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return si(t,t=>ci({...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=Rr?await oi():await ei();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),ci({...e,app:{name:fi[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(ii===`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(ii===`win32`||Rr&&!Ir()&&!t){r=await Vr(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Rr||(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=_.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!ni||ni===`/`,t=!1;try{await ge.access(ri,_e.X_OK),t=!0}catch{}r=F.versions.electron??(ii===`android`||e||!t)?`xdg-open`:ri}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}ii===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=pe.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)},li=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return ci({...t,target:e})};function ui(e){if(typeof e==`string`||Array.isArray(e))return e;let{[ai]:t}=e;if(!t)throw Error(`${ai} is not supported`);return t}function di({[ii]:e},{wsl:t}){if(t&&Rr)return ui(t);if(!e)throw Error(`${ii} is not supported`);return ui(e)}const fi={};Hr(fi,`chrome`,()=>di({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`]}})),Hr(fi,`brave`,()=>di({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`]}})),Hr(fi,`firefox`,()=>di({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Hr(fi,`edge`,()=>di({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Hr(fi,`browser`,()=>`browser`),Hr(fi,`browserPrivate`,()=>`browserPrivate`);var pi=li;function mi(e){let t=e||_i();if(A(t)){let e=M(t,`utf8`);return JSON.parse(e).token}}function hi(e,t){let n=t||_i();A(D(n))||j(D(n),{recursive:!0}),ee(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function gi(e){let t=e||_i();A(t)&&N(t)}function _i(){let e=Kn(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return O(e[0],`auth.json`)}function vi(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=K(),[s,c]=K(()=>mi(i)),[l,u]=K(),d=G(n),f=G(r);W(()=>{d.current=n,f.current=r},[n,r]);let p=U(async()=>{u(void 0);try{let e=mi(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new Ln({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=U(async()=>{u(void 0);try{let e=new Ln,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();hi(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=U(()=>{gi(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return W(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function yi(e){let{directory:t,onBuildStart:n,onBuildSuccess:r,onBuildError:i}=typeof e==`string`?{directory:e}:e,a=oe(()=>h(t),[t]),[o,s]=K(void 0),[c,l]=K(void 0),[u,d]=K(`building`),f=G(n),p=G(r),m=G(i);return W(()=>{f.current=n,p.current=r,m.current=i},[n,r,i]),W(()=>{let e=new AbortController;return a.build({cwd:t,entry:a.entry,outdir:a.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{d(`building`),s(void 0),l(void 0),f.current?.()},onResult:e=>{`error`in e?(s(e.error),d(`error`),m.current?.(e.error)):(l(e),d(`success`),p.current?.(e))}}).catch(e=>{console.log(`error`,e),d(`error`),s(e),m.current?.(e)}),()=>{e.abort()}},[t]),oe(()=>({error:o,status:u,result:c,entry:a.entry,outdir:a.outdir}),[o,u,c,a.entry,a.outdir])}function bi(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function xi(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Si=/^\.+(\\|\/)|^\.+$/,Ci=/[. ]+$/,wi=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Ti=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ei=e=>e===`‍`,Di=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Oi=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let ki;function Ai(){return ki??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),ki}function ji(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(bi().test(n)||[...n].some(e=>Ti.test(e)&&!Ei(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Oi,` `),n.length>0&&(e=e.replaceAll(Di,`$1`)),e=e.replace(Ci,``),e=e.replace(Si,n),e=e.replace(bi(),n),e=e.replaceAll(wi,e=>Ei(e)?e:n),e.length===0&&(e=n),e=xi().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=Mi(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Mi(n,a)+i}}return e}function Mi(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Ai().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Ni(e){return`${e}.lock`}function Pi(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Fi(e,t={}){let n=Ni(e),r=process.pid.toString();try{return v.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(v.readFileSync(n,`utf8`),10)}catch{return v.unlinkSync(n),Fi(e,{...t,stale:0})}if(!Pi(i))try{return v.unlinkSync(n),Fi(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Fi(e,{...t,stale:0});throw n}return!1}}async function Ii(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=ue.resolve(e),i=0;for(;i<=n.retries;){if(Fi(r,n))return()=>Li(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 Li(e){let t=ue.resolve(e),n=Ni(t);try{if(parseInt(v.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}v.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Ri(e){let t=ue.resolve(e),n=Ni(t);try{if(!v.existsSync(n))return{locked:!1};let e=v.readFileSync(n,`utf8`),t=parseInt(e,10);return Pi(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const zi=e=>{v.mkdirSync(e,{recursive:!0})},Bi=e=>{try{v.fdatasyncSync(e)}catch{}try{v.closeSync(e)}catch{}},Vi=e=>{try{let t=v.openSync(e,`r`);try{v.fsyncSync(t)}finally{v.closeSync(t)}}catch{}},Hi=(e,t)=>{let n=ue.dirname(e);zi(n);let r=ue.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=v.openSync(r,`w`),v.writeFileSync(i,t,`utf-8`),Bi(i),i=void 0,v.renameSync(r,e),Vi(e),Vi(n)}catch(e){if(i!==void 0)try{v.closeSync(i)}catch{}try{v.rmSync(r,{force:!0})}catch{}throw e}},Ui=(e,t)=>{let n=new Map,r,i=e=>{if(v.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(v.readFileSync(e,`utf-8`))},a=(e,t)=>{Hi(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=ue.join(e,`index.json`);zi(e),v.existsSync(t)||v.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Ii(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=ue.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=ue.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return ue.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=ue.join(e,n);if(v.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(v.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=ji(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=ue.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!v.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=ue.join(e,i),a=v.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Ri(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 l(r);if(!a){let t=ji(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=ue.join(e,t);zi(e),v.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Ri(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 f=await Ii(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...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=ue.join(e,n);try{v.rmSync(i,{force:!0}),Vi(e)}catch{}}}finally{await t()}},async release(){f(),n.delete(r)}}},dispose(){n.clear()}}},Wi=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=ue.join(e,`index.json`),u=()=>{try{if(!v.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=v.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(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)}},f=(t,n,r=!1)=>{let i=ue.join(e,n);try{let e=v.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(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=Ri(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(v.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{v.mkdirSync(e,{recursive:!0})}catch{}a=v.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),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 Gi({chatKey:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Ki}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,chat:{key:e}},{signal:r}),l=R({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 Ki=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(ne);return n.length===0||n.some(e=>l(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},qi=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Ji(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Yi=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,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=Ui(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=Wi(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}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,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).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,messages:(this.chat?.messages??[]).filter(e=>!Ji(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 upsertMessage(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=e;if(this.serializeMessage){let t=this.serializeMessage(e);if(t===void 0)return;n=t}let i=n.id||crypto.randomUUID(),a=n.mode||`run`,o=qi(n,a,i),s=t.messages.find(e=>e.id===o.id)?t.messages.map(e=>e.id===o.id?o:e):[...t.messages,o];this.chat={...t,updated_at:new Date().toISOString(),messages:s},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessage(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>t.id!==e),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessage(e){if(this.chat.error=void 0,this.status===`streaming`){this.queue.push(e),this.notifyListeners();return}this.queue=[e],await this.processQueueOrRun()}async start(){await this.processQueueOrRun()}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.shift();this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r&&await this.upsertMessage(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!ne(e)||e.input!==``?e:{...e,input:{}})}));let a=await Gi({agent:this.agent,chatKey:this.chatId,signal:n.signal,messages:i}),o=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)},s=a.getReader();n.signal.addEventListener(`abort`,()=>{s.cancel().catch(()=>{})},{once:!0});try{for(;;){let{done:e,value:t}=await s.read();if(e||n.signal.aborted)break;this.streamingMessage&&t.id!==this.streamingMessage.id&&await o(this.streamingMessage),this.streamingMessage=this.serializeMessage?this.serializeMessage(t):t,this.notifyListeners()}}finally{s.releaseLock()}this.streamingMessage&&await o(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 Xi(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=G(null),[s,c]=K({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});W(()=>{o.current&&o.current.dispose();let e=new Yi({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]),W(()=>{o.current&&o.current.setAgent(n)},[n]);let l=U(async e=>{o.current&&await o.current.sendMessage(e)},[]),u=U(async e=>{o.current&&await o.current.upsertMessage(e)},[]),d=U(()=>{o.current&&o.current.stopStreaming()},[]),f=U(async()=>{o.current&&await o.current.resetChat()},[]),p=U(()=>{o.current&&o.current.clearQueue()},[]),m=U(async e=>{o.current&&await o.current.deleteMessage(e)},[]),h=U(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function Zi(e){let t=O(e,`data`,`devhook.txt`);if(j(D(t),{recursive:!0}),A(t))return M(t,`utf-8`);let n=crypto.randomUUID();return ee(t,n),n}const Qi=(e,t)=>e.json({error:t},400),$i=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}},ea=()=>new o,ta=ea().get(`/:key`,async e=>{let{key:t,err:n}=$i(e);if(n)return Qi(e,n);let r=await e.env.context.store.get(t);return e.json({value:r},200)}).post(`/:key`,m(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Qi(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Qi(t,`Value must be a string`):Qi(t,`Value is required`)}),async e=>{let{key:t,err:n}=$i(e);if(n)return Qi(e,n);let{value:r}=e.req.valid(`json`);return await e.env.context.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=$i(e);return n?Qi(e,n):(await e.env.context.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.context.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),na=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`}},ra=ea().basePath(`/:key`).post(`/`,async e=>{let{key:t,err:n}=na(e);return n?Qi(e,n):e.json(await e.env.context.chat.ensure(t),200)}).post(`/sendMessages`,m(`json`,(e,t)=>({message:e.message,options:e.options})),async e=>{let{key:t,err:n}=na(e);if(n)return Qi(e,n);let{message:r,options:i}=e.req.valid(`json`);try{await e.env.context.chat.message(t,r,i)}catch(t){return Qi(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),ia=ea().post(`/v1/traces`,async e=>e.env.context.otlp?e.env.context.otlp.traces(e.req.raw):e.body(null,204)),aa=new o().route(`/kv`,ta).route(`/chat`,ra).route(`/otlp`,ia);function oa(e){let t=fe(e.dataDirectory,`chats`),n={},r=fe(e.dataDirectory,`storage.json`);v.existsSync(r)&&(n=JSON.parse(v.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new Yi({chatId:n,chatsDirectory:t}),r.setAgent(e.getAgent()),i.set(n,r)),r},o={chat:{async ensure(e){let t=a(e).getState(),n=t.messages.length===0&&!t.created_at;return{key:e,created:n}},async message(e,t,n){let r=a(e),i=qi(t,`run`);if(n?.behavior===`append`){await r.upsertMessage(i);return}if(n?.behavior===`interrupt`){await r.sendMessage(i);return}await r.sendMessage(i)}},store:{get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,v.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],v.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).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+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}}},s=E(c(e=>aa.fetch(e,{context:o})));s.listen(e.port??0);let l=Ui(t,`id`);return{url:`http://127.0.0.1:${s.address().port}`,runtime:o,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),lockChat:e=>l.lock(e),startChat:async e=>{await a(e).start()},stopChat:e=>{i.get(e)?.stopStreaming()},dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),s.close()}}}function sa({agent:e,capabilities:t,messages:n}){let[r,i]=K(void 0),[a,o]=K(!0),[s,c]=K(void 0),l=G(s);W(()=>{l.current=s},[s]);let[d,f]=K(()=>u(n));W(()=>{f(e=>{let t=u(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[p,m]=K(void 0),h=U((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=U(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(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);W(()=>{if(!d&&!s){m(void 0);return}g()},[d,s,g]);let _=G(void 0),v=G(void 0);W(()=>{e!==v.current&&(v.current=e,c(void 0),m(void 0),i(void 0),o(!0),_.current=void 0)},[e]),W(()=>{if(t&&!t.ui||!e){c(void 0),m(void 0),i(void 0),_.current=void 0;return}let n=p?JSON.stringify(p):``;if(_.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),_.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,p]);let y=U((e,t)=>{g({[e]:t})},[g]);return{schema:s,options:p,setOption:y,loading:a,error:r}}function ca(e){let t=G(e.onRequest);W(()=>{t.current=e.onRequest},[e.onRequest]);let n=G(e.id??crypto.randomUUID()),[r,i]=K(`disconnected`);return W(()=>{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 Ln({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 la=e(((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}}})),ua=r(e(((e,t)=>{let r=n(`fs`),i=n(`path`),a=n(`os`),o=n(`crypto`),s=la().version,c=[`🔐 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 l(){return c[Math.floor(Math.random()*c.length)]}function u(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function d(){return process.stdout.isTTY}function f(e){return d()?`\x1b[2m${e}\x1b[0m`:e}let p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function m(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
40
40
  `);let r;for(;(r=p.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,`
41
41
  `),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function h(e){e||={};let t=x(e);e.path=t;let n=O.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=y(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=b(n,t);a=O.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return O.parse(a)}function g(e){console.error(`[dotenv@${s}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function v(e){console.log(`[dotenv@${s}] ${e}`)}function y(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 b(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 x(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let n of e.path)r.existsSync(n)&&(t=n.endsWith(`.vault`)?n:`${n}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=i.resolve(process.cwd(),`.env.vault`);return r.existsSync(t)?t:null}function S(e){return e[0]===`~`?i.join(a.homedir(),e.slice(1)):e}function C(e){let t=u(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=u(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&v(`Loading env from encrypted .env.vault`);let r=O._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),O.populate(i,r,e),{parsed:r}}function w(e){let t=i.resolve(process.cwd(),`.env`),n=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=u(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=u(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?n=e.encoding:o&&_(`No encoding is specified. UTF-8 is used by default`);let c=[t];if(e&&e.path)if(!Array.isArray(e.path))c=[S(e.path)];else{c=[];for(let t of e.path)c.push(S(t))}let d,p={};for(let t of c)try{let i=O.parse(r.readFileSync(t,{encoding:n}));O.populate(p,i,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=O.populate(a,p,e);if(o=u(a.DOTENV_CONFIG_DEBUG||o),s=u(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of c)try{let n=i.relative(process.cwd(),e);t.push(n)}catch(t){o&&_(`Failed to load ${e} ${t.message}`),d=t}v(`injecting env (${e}) from ${t.join(`,`)} ${f(`-- tip: ${l()}`)}`)}return d?{parsed:p,error:d}:{parsed:p}}function T(e){if(y(e).length===0)return O.configDotenv(e);let t=x(e);return t?O._configVault(e):(g(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),O.configDotenv(e))}function E(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${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 D(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&&_(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 O={configDotenv:w,_configVault:C,_parseVault:h,config:T,decrypt:E,parse:m,populate:D};t.exports.configDotenv=O.configDotenv,t.exports._configVault=O._configVault,t.exports._parseVault=O._parseVault,t.exports.config=O.config,t.exports.decrypt=O.decrypt,t.exports.parse=O.parse,t.exports.populate=O.populate,t.exports=O}))(),1);async function da(e,t){let n=e;for(;n!==D(n);){let e=O(n,t);try{return await H(e),e}catch{}n=D(n)}}function fa(e,t=`.env.local`){let[n,r]=K({});return W(()=>{let n,i=e=>{try{let t=M(e,`utf-8`),n=(0,ua.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return da(e,t).then(e=>{if(!e){r({});return}i(e),n=P(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}const pa=(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},ma=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1));let ha=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}({}),ga=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 _a={[ha.REQUEST]:Y.string(),[ha.PROXY_INIT]:Y.object({method:Y.string(),headers:Y.record(Y.string(),Y.string()),url:Y.string()}),[ha.PROXY_BODY]:Y.instanceof(Uint8Array),[ha.PROXY_WEBSOCKET_MESSAGE]:Y.object({type:Y.enum([`text`,`binary`]),data:Y.instanceof(Uint8Array)}),[ha.PROXY_WEBSOCKET_CLOSE]:Y.object({code:Y.number().optional(),reason:Y.string().optional()})};ga.RESPONSE,Y.string(),ga.NOTIFICATION,Y.string(),ga.PROXY_INIT,Y.object({status_code:Y.number(),status_message:Y.string(),headers:Y.record(Y.string(),Y.string())}),ga.PROXY_DATA,Y.instanceof(Uint8Array),ga.PROXY_WEBSOCKET_MESSAGE,Y.instanceof(Uint8Array),ga.PROXY_WEBSOCKET_CLOSE,Y.object({code:Y.number(),reason:Y.string()}),ha.PROXY_INIT,Y.string(),Y.record(Y.string(),Y.string()),Y.string();const va={process_execute:Y.object({command:Y.string(),args:Y.array(Y.string()),env_file:Y.string().optional(),env:Y.record(Y.string(),Y.string()).optional(),cwd:Y.string().optional()}),process_send_input:Y.object({pid:Y.number(),data:Y.string()}),process_wait:Y.object({pid:Y.number(),output_idle_timeout_ms:Y.number().optional(),timeout_ms:Y.number().optional()}),process_list:Y.object({include_dead:Y.boolean().optional()}),process_read_plain_output:Y.object({pid:Y.number(),start_line:Y.number().optional(),end_line:Y.number().optional()}),process_kill:Y.object({pid:Y.number(),signal:Y.string().optional()}),set_env:Y.object({env:Y.record(Y.string(),Y.string())}),read_file:Y.object({path:Y.string(),line_start:Y.number().optional(),line_end:Y.number().optional()}),write_file:Y.object({path:Y.string(),content:Y.string(),base64:Y.boolean().optional(),mode:Y.number().optional()}),read_directory:Y.object({path:Y.string()}),watch_directory:Y.object({path:Y.string()}),deploy_static_files:Y.object({path:Y.string()})},ya=Y.object({pid:Y.number(),command:Y.string(),args:Y.array(Y.string()),title:Y.string().optional(),cwd:Y.string(),env:Y.record(Y.string(),Y.string()),exit_code:Y.number().optional(),exit_signal:Y.number().optional(),duration_ms:Y.number().optional(),output_total_lines:Y.number()});ya.extend({ansi_output:Y.string(),plain_output:Y.object({lines:Y.array(Y.string()),total_lines:Y.number()})}),Y.object({pid:Y.number()}),Y.object({}),Y.object({processes:Y.array(ya)}),Y.object({lines:Y.array(Y.string()),total_lines:Y.number(),duration_ms:Y.number(),exit_code:Y.number().optional(),exit_signal:Y.number().optional()}),Y.object({}),Y.object({}),Y.object({total_lines:Y.number(),lines_read:Y.number(),start_line:Y.number(),content:Y.string(),mime_type:Y.string()}),Y.object({}),Y.object({entries:Y.array(Y.object({name:Y.string(),type:Y.enum([`file`,`directory`,`symlink`])}))}),Y.object({}),Y.object({deployment_id:Y.string()});const ba=Y.object({type:Y.enum([`create`,`update`,`delete`]),path:Y.string()}),xa=Y.object({type:Y.enum([`context`,`added`,`deleted`]),content:Y.string(),oldLineNumber:Y.number().optional(),newLineNumber:Y.number().optional()}),Sa=Y.object({oldStart:Y.number(),oldLines:Y.number(),newStart:Y.number(),newLines:Y.number(),lines:Y.array(xa)}),Ca=Y.object({path:Y.string(),status:Y.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:Y.string().optional(),insertions:Y.number(),deletions:Y.number(),chunks:Y.array(Sa)}),wa=Y.object({totalFiles:Y.number(),totalInsertions:Y.number(),totalDeletions:Y.number(),netChange:Y.number(),startHash:Y.string().optional(),currentHash:Y.string().optional(),timespan:Y.number(),files:Y.array(Ca)}),Ta=Y.object({path:Y.string(),status:Y.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:Y.boolean()}),Ea=Y.object({hash:Y.string(),shortHash:Y.string(),message:Y.string(),author:Y.string(),email:Y.string(),date:Y.date(),timestamp:Y.date(),filesChanged:Y.number(),insertions:Y.number(),deletions:Y.number(),commitDiff:Y.array(Ca).optional()});Y.object({files:Y.array(Ta),branch:Y.string(),ahead:Y.number(),behind:Y.number(),timestamp:Y.date(),sessionDiff:wa.optional(),workingDirectoryDiff:wa.optional(),newCommits:Y.array(Ea),currentCommit:Y.object({hash:Y.string(),shortHash:Y.string(),message:Y.string(),author:Y.string(),date:Y.date()}).optional(),diffSkipped:Y.boolean().optional(),payloadTruncated:Y.boolean().optional(),estimatedSizeKB:Y.number().optional()}),Y.object({debounceDelay:Y.number().optional(),gitStatusInterval:Y.number().optional(),ignoreDotfiles:Y.boolean().optional(),ignored:Y.array(Y.string()).optional(),watchGit:Y.boolean().optional(),includeDiffs:Y.boolean().optional(),maxDiffFiles:Y.number().optional(),maxPayloadSizeKB:Y.number().optional(),truncateLargeDiffs:Y.boolean().optional()}),Y.object({status:ya}),Y.object({pid:Y.number(),output:Y.string()}),Y.object({changes:Y.array(ba)});var Da=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)}}}},Oa=e(((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:()=>{}}})),ka=e(((e,t)=>{let{EMPTY_BUFFER:r}=Oa(),i=Buffer[Symbol.species];function a(e,t){if(e.length===0)return r;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let r=e[t];n.set(r,a),a+=r.length}return a<t?new i(n.buffer,n.byteOffset,a):n}function o(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function s(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function c(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function l(e){if(l.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new i(e):ArrayBuffer.isView(e)?t=new i(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),l.readOnly=!1),t}if(t.exports={concat:a,mask:o,toArrayBuffer:c,toBuffer:l,unmask:s},!process.env.WS_NO_BUFFER_UTIL)try{let e=n(`bufferutil`);t.exports.mask=function(t,n,r,i,a){a<48?o(t,n,r,i,a):e.mask(t,n,r,i,a)},t.exports.unmask=function(t,n){t.length<32?s(t,n):e.unmask(t,n)}}catch{}})),Aa=e(((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])}}}})),ja=e(((e,t)=>{let r=n(`zlib`),i=ka(),a=Aa(),{kStatusCode:o}=Oa(),s=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol(`permessage-deflate`),u=Symbol(`total-length`),d=Symbol(`callback`),f=Symbol(`buffers`),p=Symbol(`error`),m;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,!m){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;m=new a(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[d];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){m.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){m.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,n){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[f]=[],this._inflate.on(`error`,_),this._inflate.on(`data`,g)}this._inflate[d]=n,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{let e=this._inflate[p];if(e){this._inflate.close(),this._inflate=null,n(e);return}let r=i.concat(this._inflate[f],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),n(null,r)})}_compress(e,t,n){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[f]=[],this._deflate.on(`data`,h)}this._deflate[d]=n,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[f],this._deflate[u]);t&&(e=new s(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[f]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),n(null,e)})}};function h(e){this[f].push(e),this[u]+=e.length}function g(e){if(this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload){this[f].push(e);return}this[p]=RangeError(`Max payload size exceeded`),this[p].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[p][o]=1009,this.removeListener(`data`,g),this.reset()}function _(e){if(this[l]._inflate=null,this[p]){this[d](this[p]);return}e[o]=1007,this[d](e)}})),Ma=e(((e,t)=>{let{isUtf8:r}=n(`buffer`),{hasBlob:i}=Oa(),a=[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 o(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function s(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 c(e){return i&&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:c,isValidStatusCode:o,isValidUTF8:s,tokenChars:a},r)t.exports.isValidUTF8=function(e){return e.length<24?s(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=n(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?s(t):e(t)}}catch{}})),Na=e(((e,t)=>{let{Writable:r}=n(`stream`),i=ja(),{BINARY_TYPES:a,EMPTY_BUFFER:o,kStatusCode:s,kWebSocket:c}=Oa(),{concat:l,toArrayBuffer:u,unmask:d}=ka(),{isValidStatusCode:f,isValidUTF8:p}=Ma(),m=Buffer[Symbol.species];t.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||a[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=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 m(t.buffer,t.byteOffset+e,t.length-e),new m(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 m(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[i.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=o;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&&d(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[i.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`?l(n,t):this._binaryType===`arraybuffer`?u(l(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=l(n,t);if(!this._skipUTF8Validation&&!p(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,o),this.end();else{let n=e.readUInt16BE(0);if(!f(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new m(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(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[s]=r,a}}})),Pa=e(((e,t)=>{let{Duplex:r}=n(`stream`),{randomFillSync:i}=n(`crypto`),a=ja(),{EMPTY_BUFFER:o,kWebSocket:s,NOOP:c}=Oa(),{isBlob:l,isValidStatusCode:u}=Ma(),{mask:d,toBuffer:f}=ka(),p=Symbol(`kByteLength`),m=Buffer.alloc(4),h=8*1024,g,_=h;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=c,this[s]=void 0}static frame(e,t){let n,r=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||m,t.generateMask?t.generateMask(n):(_===h&&(g===void 0&&(g=Buffer.alloc(h)),i(g,0,h),_=0),n[0]=g[_++],n[1]=g[_++],n[2]=g[_++],n[3]=g[_++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[p]!==void 0?s=t[p]:(e=Buffer.from(e),s=e.length):(s=e.length,r=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(r?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]:r?(d(e,n,l,a,s),[l]):(d(e,n,e,0,s),[l,e])}close(t,n,r,i){let a;if(t===void 0)a=o;else if(typeof t!=`number`||!u(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);a=Buffer.allocUnsafe(2+e),a.writeUInt16BE(t,0),typeof n==`string`?a.write(n,2):a.set(n,2)}let s={[p]:a.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(a,s),i):this.enqueue([this.dispatch,a,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};l(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):l(t)?(i=t.size,a=!1):(t=f(t),i=t.length,a=f.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[p]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};l(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[a.extensionName],i=t.binary?2:1,o=t.compress,s,c;typeof e==`string`?(s=Buffer.byteLength(e),c=!1):l(e)?(s=e.size,c=!1):(e=f(e),s=e.length,c=f.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,i=0),t.fin&&(this._firstFragment=!0);let u={[p]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};l(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[p],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(v,this,e,i);return}this._bufferedBytes-=r[p];let a=f(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(y,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let o=this._extensions[a.extensionName];this._bufferedBytes+=r[p],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){v(this,Error(`The socket was closed while data was being compressed`),i);return}this._bufferedBytes-=r[p],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][p],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][p],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 v(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 y(e,t,n){v(e,t,n),e.onerror(t)}})),Fa=e(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Oa(),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)}})),Ia=e(((e,t)=>{let{tokenChars:n}=Ma();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}})),La=e(((e,t)=>{let r=n(`events`),i=n(`https`),a=n(`http`),o=n(`net`),s=n(`tls`),{randomBytes:c,createHash:l}=n(`crypto`),{Duplex:u,Readable:d}=n(`stream`),{URL:f}=n(`url`),p=ja(),m=Na(),h=Pa(),{isBlob:g}=Ma(),{BINARY_TYPES:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=Oa(),{EventTarget:{addEventListener:T,removeEventListener:E}}=Fa(),{format:D,parse:O}=Ia(),{toBuffer:k}=ka(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=class e extends r{constructor(t,n,r){super(),this._binaryType=_[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,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]),ee(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){_.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 m({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new h(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,R),i.on(`drain`,z),i.on(`error`,B),i.on(`message`,V),i.on(`ping`,H),i.on(`pong`,ie),a.onerror=U,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,oe),t.on(`data`,G),t.on(`end`,K),t.on(`error`,q),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[p.extensionName]&&this._extensions[p.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())}),W(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){ne(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,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){ne(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,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){ne(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[p.extensionName]||(i.compress=!1),this._sender.send(t||v,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(P,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),P.prototype.addEventListener=T,P.prototype.removeEventListener=E,t.exports=P;function ee(e,t,n,r){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,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,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let s;if(t instanceof f)s=t;else try{s=new f(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}s.protocol===`http:`?s.protocol=`ws:`:s.protocol===`https:`&&(s.protocol=`wss:`),e._url=s.href;let u=s.protocol===`wss:`,d=s.protocol===`ws+unix:`,m;if(s.protocol!==`ws:`&&!u&&!d?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:d&&!s.pathname?m=`The URL's pathname is empty`:s.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=c(16).toString(`base64`),_=u?i.request:a.request,v=new Set,b;if(o.createConnection=o.createConnection||(u?I:te),o.defaultPort=o.defaultPort||h,o.port=s.port||h,o.host=s.hostname.startsWith(`[`)?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new p(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[p.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!N.test(e)||v.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);v.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),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),d){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?o.socketPath:s.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=d?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.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&&!r.headers.authorization&&(r.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[A]||(x=e._req=null,F(e,t))}),x.on(`response`,i=>{let a=i.headers.location,s=i.statusCode;if(a&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){L(e,x,`Maximum redirects exceeded`);return}x.abort();let i;try{i=new f(a,t)}catch{let t=SyntaxError(`Invalid URL: ${a}`);F(e,t);return}ee(e,i,n,r)}else e.emit(`unexpected-response`,x,i)||L(e,x,`Unexpected server response: ${i.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==P.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=l(`sha1`).update(g+y).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`],c;if(s===void 0?v.size&&(c=`Server sent no subprotocol`):v.size?v.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){L(e,n,c);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=O(u)}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==p.extensionName){L(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[p.extensionName])}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[p.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=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function te(e){return e.path=e.socketPath,o.connect(e)}function I(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=o.isIP(e.host)?``:e.host),s.connect(e)}function L(e,t,n){e._readyState=P.CLOSING;let r=Error(n);Error.captureStackTrace(r,L),t.setHeader?(t[A]=!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 ne(e,t,n){if(t){let n=g(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function R(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,G),process.nextTick(ae,n._socket),e===1005?n.close():n.close(e,t))}function z(){let e=this[C];e.isPaused||e._socket.resume()}function B(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,G),process.nextTick(ae,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function re(){this[C].emitClose()}function V(e,t){this[C].emit(`message`,e,t)}function H(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function ie(e){this[C].emit(`pong`,e)}function ae(e){e.resume()}function U(e){let t=this[C];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,W(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function W(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function oe(){let e=this[C];this.removeListener(`close`,oe),this.removeListener(`data`,G),this.removeListener(`end`,K),e._readyState=P.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[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,re),e._receiver.on(`finish`,re))}function G(e){this[C]._receiver.write(e)||this.pause()}function K(){let e=this[C];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function q(){let e=this[C];this.removeListener(`error`,q),this.on(`error`,w),e&&(e._readyState=P.CLOSING,this.destroy())}})),Ra=e(((e,t)=>{La();let{Duplex:r}=n(`stream`);function i(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let n=!0,s=new r({...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||(n=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,s);return}let a=!1;e.once(`error`,function(e){a=!0,r(e)}),e.once(`close`,function(){a||r(t),process.nextTick(i,s)}),n&&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`,a),s.on(`error`,o),s}t.exports=s})),za=e(((e,t)=>{let{tokenChars:n}=Ma();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}})),Ba=e(((e,t)=>{let r=n(`events`),i=n(`http`),{Duplex:a}=n(`stream`),{createHash:o}=n(`crypto`),s=Ia(),c=ja(),l=za(),u=La(),{GUID:d,kWebSocket:f}=Oa(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends r{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:u,...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=i.createServer((e,t)=>{let n=i.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=m(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(h,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(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(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`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=l.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new c(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=s.parse(f);e[c.extensionName]&&(n.accept(e[c.extensionName]),m[c.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===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 _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${o(`sha1`).update(t+d).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&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[c.extensionName]){let t=e[c.extensionName].params,n=s.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
42
42
  `).join(`\r
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blink",
3
- "version": "0.1.111",
3
+ "version": "0.1.112",
4
4
  "description": "Blink is a JavaScript runtime for building and deploying AI agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +0,0 @@
1
- import{login as e}from"./auth-CDmvBLTI.js";import"./dist-wyfWuz5A.js";import"./open-S_jcQ0nw.js";async function t(){await e()}export{t as default};
File without changes
File without changes