blink 1.1.23 → 1.1.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/agent/client/index.cjs +1 -1
- package/dist/browser/agent/client/index.d.cts +1 -1
- package/dist/browser/agent/client/index.d.ts +1 -1
- package/dist/browser/agent/client/index.js +1 -1
- package/dist/browser/{index-C-Slllhb.d.ts → index-BXZCP58f.d.ts} +51 -0
- package/dist/browser/{index-DSU-sZKL.d.cts → index-orp-VO8g.d.cts} +51 -0
- package/dist/browser/react/index.browser.cjs +1 -1
- package/dist/browser/react/index.browser.d.cts +16 -2
- package/dist/browser/react/index.browser.d.ts +16 -2
- package/dist/browser/react/index.browser.js +1 -1
- package/dist/cli/{chat-CAtArOPl.js → chat-CYrdzv1d.js} +1 -1
- package/dist/cli/chat-manager-B3eOpIG8.js +21 -0
- package/dist/cli/connect-Bpv7PF3y.js +1 -0
- package/dist/cli/{dev-DwwSnzeH.js → dev-UYlIxku7.js} +23 -29
- package/dist/cli/{getMachineId-bsd-0cOO_RKK.js → getMachineId-bsd-BECgXpZb.js} +1 -1
- package/dist/cli/{getMachineId-bsd-BDrKPt3B.js → getMachineId-bsd-BgAyii4H.js} +1 -1
- package/dist/cli/{getMachineId-bsd-BJ3yH7j4.js → getMachineId-bsd-Cc73dhdJ.js} +1 -1
- package/dist/cli/{getMachineId-bsd-BpxYEV3F.js → getMachineId-bsd-DJn61I3m.js} +1 -1
- package/dist/cli/{getMachineId-bsd-CHVQhSq2.js → getMachineId-bsd-Doah6QJP.js} +1 -1
- package/dist/cli/getMachineId-bsd-aoAkh_W6.js +1 -0
- package/dist/cli/getMachineId-bsd-iPOb0TqF.js +1 -0
- package/dist/cli/getMachineId-bsd-io5tPlFg.js +1 -0
- package/dist/cli/{getMachineId-darwin-0AdOS_kz.js → getMachineId-darwin-BMnMBte0.js} +1 -1
- package/dist/cli/{getMachineId-darwin-CJ2gOzlU.js → getMachineId-darwin-BP9BSYcd.js} +1 -1
- package/dist/cli/{getMachineId-darwin-BeAdNwpL.js → getMachineId-darwin-Bs3mlKrs.js} +1 -1
- package/dist/cli/{getMachineId-darwin-C8-xkmnZ.js → getMachineId-darwin-D-l4_nyT.js} +1 -1
- package/dist/cli/{getMachineId-darwin-BaA8JJgE.js → getMachineId-darwin-DFronuaU.js} +1 -1
- package/dist/cli/getMachineId-darwin-DJO6fOdc.js +2 -0
- package/dist/cli/getMachineId-darwin-DlRRGl6M.js +2 -0
- package/dist/cli/getMachineId-darwin-Wp0usMIp.js +2 -0
- package/dist/cli/{getMachineId-linux-BQISLgy5.js → getMachineId-linux-B2r_HEgX.js} +1 -1
- package/dist/cli/{getMachineId-linux-Bg5YnekM.js → getMachineId-linux-Bj52Hdvy.js} +1 -1
- package/dist/cli/{getMachineId-linux-Boq-GGfA.js → getMachineId-linux-C9o1dYwI.js} +1 -1
- package/dist/cli/{getMachineId-linux-C9BHlxRm.js → getMachineId-linux-CGcBOg7J.js} +1 -1
- package/dist/cli/getMachineId-linux-CV2HmJXY.js +1 -0
- package/dist/cli/getMachineId-linux-Cv44Y8ZY.js +1 -0
- package/dist/cli/getMachineId-linux-CzNEh3DJ.js +1 -0
- package/dist/cli/getMachineId-linux-_RiwpX2J.js +1 -0
- package/dist/cli/{getMachineId-unsupported-4qhSqb7w.js → getMachineId-unsupported-BtmyS2eg.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-BsEK_LG9.js → getMachineId-unsupported-C8az6JKm.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-C6cVb167.js → getMachineId-unsupported-CBS2qXAs.js} +1 -1
- package/dist/cli/{getMachineId-unsupported-CqJy0sqq.js → getMachineId-unsupported-Cu0DvxaU.js} +1 -1
- package/dist/cli/getMachineId-unsupported-Dni2ujA-.js +1 -0
- package/dist/cli/getMachineId-unsupported-MPNVP8rP.js +1 -0
- package/dist/cli/getMachineId-unsupported-mBJd3oBN.js +1 -0
- package/dist/cli/getMachineId-unsupported-rdNf8ej6.js +1 -0
- package/dist/cli/{getMachineId-win-4Psd7Tlr.js → getMachineId-win-BCAO7ld1.js} +1 -1
- package/dist/cli/{getMachineId-win-BzRwVWue.js → getMachineId-win-BDQszRKi.js} +1 -1
- package/dist/cli/{getMachineId-win-BA0Li8oF.js → getMachineId-win-BOnF6rL7.js} +1 -1
- package/dist/cli/{getMachineId-win-BvGLfEpq.js → getMachineId-win-BOuIHcz_.js} +1 -1
- package/dist/cli/getMachineId-win-BQ_C7kS3.js +1 -0
- package/dist/cli/getMachineId-win-Bw0-Mlkn.js +1 -0
- package/dist/cli/getMachineId-win-DrJTv2qi.js +1 -0
- package/dist/cli/{getMachineId-win-C4wjvjxC.js → getMachineId-win-pnMl0wak.js} +1 -1
- package/dist/cli/index.js +3 -3
- package/dist/cli/{init-em410TZP.js → init-CAbtPm4f.js} +1 -1
- package/dist/cli/run-DYgfawiE.js +1 -0
- package/dist/cli/setup-slack-app-C9L0iIDZ.js +1 -0
- package/dist/cli/{token-BdYp2nw_.js → token-Bk68OrJt.js} +1 -1
- package/dist/cli/{token-util-KdD-UX1l.js → token-util-BKLboTb2.js} +1 -1
- package/dist/cli/token-util-Dui5nOLw.js +1 -0
- package/dist/cli/undici-mM2IfLwA.js +1 -0
- package/dist/cli/usingCtx-B1FpoePI.js +1 -0
- package/dist/node/react/index.node.cjs +85 -85
- package/dist/node/react/index.node.d.cts +83 -3
- package/dist/node/react/index.node.d.ts +83 -3
- package/dist/node/react/index.node.js +40 -40
- package/package.json +4 -2
- package/dist/cli/chat-manager-GWR_v50X.js +0 -21
- package/dist/cli/connect-DWScpJzS.js +0 -1
- package/dist/cli/getMachineId-bsd-BrJwIGYU.js +0 -1
- package/dist/cli/getMachineId-bsd-C6osJ6-S.js +0 -1
- package/dist/cli/getMachineId-bsd-DeIJ5F9l.js +0 -1
- package/dist/cli/getMachineId-darwin-CYvRIQbp.js +0 -2
- package/dist/cli/getMachineId-darwin-DWSKszGZ.js +0 -2
- package/dist/cli/getMachineId-darwin-wYLDmdQt.js +0 -2
- package/dist/cli/getMachineId-linux-D0cDy6Ik.js +0 -1
- package/dist/cli/getMachineId-linux-DgyKUIyK.js +0 -1
- package/dist/cli/getMachineId-linux-DnzutOBC.js +0 -1
- package/dist/cli/getMachineId-linux-nBO1QX9q.js +0 -1
- package/dist/cli/getMachineId-unsupported-DQBLgw4s.js +0 -1
- package/dist/cli/getMachineId-unsupported-DTFeADdG.js +0 -1
- package/dist/cli/getMachineId-unsupported-DgVzHx1H.js +0 -1
- package/dist/cli/getMachineId-unsupported-TE5qi9PD.js +0 -1
- package/dist/cli/getMachineId-win-DXCyELQJ.js +0 -1
- package/dist/cli/getMachineId-win-hHwtD9GX.js +0 -1
- package/dist/cli/getMachineId-win-lhgCxX3y.js +0 -1
- package/dist/cli/run-CZZ6WAdr.js +0 -1
- package/dist/cli/setup-slack-app-DagQxNol.js +0 -1
- package/dist/cli/token-util-C9doIH9w.js +0 -1
- package/dist/cli/undici-Bm_EanIy.js +0 -1
- /package/dist/cli/{connect-BCK40kvG.js → connect-DIUub9Pr.js} +0 -0
- /package/dist/cli/{devtools-DsAYEmyP.js → devtools-DqYysfX1.js} +0 -0
- /package/dist/cli/{esm-C_RXU0lI.js → esm-CYkSi8_o.js} +0 -0
- /package/dist/cli/{execAsync-BOPj9Mml.js → execAsync-9jtK4I3l.js} +0 -0
- /package/dist/cli/{execAsync-Bv4jTnD3.js → execAsync-B4_pEoEJ.js} +0 -0
- /package/dist/cli/{execAsync-CyP3Ojec.js → execAsync-BdK7RB6d.js} +0 -0
- /package/dist/cli/{execAsync-DHh3DKKp.js → execAsync-Bjxs-bO2.js} +0 -0
- /package/dist/cli/{execAsync-DdLzES9n.js → execAsync-CM_C8SBr.js} +0 -0
- /package/dist/cli/{execAsync-Dv6XOE2I.js → execAsync-CNFaXJjR.js} +0 -0
- /package/dist/cli/{execAsync-Dwktgsum.js → execAsync-Dl3hbWiU.js} +0 -0
- /package/dist/cli/{execAsync-qNF4iDpO.js → execAsync-qGIZ8XA8.js} +0 -0
- /package/dist/cli/{init-templates-By3gx42M.js → init-templates-BgcZAdJh.js} +0 -0
- /package/dist/cli/{login-BDP8JC4X.js → login-Bu2acoVp.js} +0 -0
- /package/dist/cli/{token-error-COQY18OP.js → token-error-CGIVaIg6.js} +0 -0
- /package/dist/cli/{undici-CRntNDHY.js → undici-BiTrd9-R.js} +0 -0
|
@@ -12,18 +12,18 @@ ${e}
|
|
|
12
12
|
|
|
13
13
|
`;break}case`tool`:throw new t.UnsupportedFunctionalityError({functionality:`tool messages`});default:{let e=a;throw Error(`Unsupported role: ${e}`)}}return i+=`${r}:
|
|
14
14
|
`,{prompt:i,stopSequences:[`
|
|
15
|
-
${n}:`]}}function ai({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function oi(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var si=r.z.object({echo:r.z.boolean().optional(),logitBias:r.z.record(r.z.string(),r.z.number()).optional(),suffix:r.z.string().optional(),user:r.z.string().optional(),logprobs:r.z.union([r.z.boolean(),r.z.number()]).optional()}),ci=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await Sr({provider:`openai`,providerOptions:f,schema:si}),...await Sr({provider:this.providerOptionsName,providerOptions:f,schema:si})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=ii({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await wr({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),body:t,failedResponseHandler:Ur,successfulResponseHandler:Mr(ui),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s={openai:{}};return o.logprobs!=null&&(s.openai.logprobs=o.logprobs),{content:[{type:`text`,text:o.text}],usage:{inputTokens:i.usage?.prompt_tokens,outputTokens:i.usage?.completion_tokens,totalTokens:i.usage?.total_tokens},finishReason:oi(o.finish_reason),request:{body:t},response:{...ai(i),headers:r,body:a},providerMetadata:s,warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await wr({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),body:r,failedResponseHandler:Ur,successfulResponseHandler:jr(di),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...ai(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=oi(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},li=r.z.object({prompt_tokens:r.z.number(),completion_tokens:r.z.number(),total_tokens:r.z.number()}),ui=r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({text:r.z.string(),finish_reason:r.z.string(),logprobs:r.z.object({tokens:r.z.array(r.z.string()),token_logprobs:r.z.array(r.z.number()),top_logprobs:r.z.array(r.z.record(r.z.string(),r.z.number())).nullish()}).nullish()})),usage:li.nullish()}),di=r.z.union([r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({text:r.z.string(),finish_reason:r.z.string().nullish(),index:r.z.number(),logprobs:r.z.object({tokens:r.z.array(r.z.string()),token_logprobs:r.z.array(r.z.number()),top_logprobs:r.z.array(r.z.record(r.z.string(),r.z.number())).nullish()}).nullish()})),usage:li.nullish()}),Hr]),fi=r.z.object({dimensions:r.z.number().optional(),user:r.z.string().optional()}),pi=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=await Sr({provider:`openai`,providerOptions:i,schema:fi})??{},{responseHeaders:o,value:s,rawValue:c}=await wr({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:Kn(this.config.headers(),n),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:a.dimensions,user:a.user},failedResponseHandler:Ur,successfulResponseHandler:Mr(mi),abortSignal:r,fetch:this.config.fetch});return{embeddings:s.data.map(e=>e.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:o,body:c}}}},mi=r.z.object({data:r.z.array(r.z.object({embedding:r.z.array(r.z.number())})),usage:r.z.object({prompt_tokens:r.z.number()}).nullish()}),hi={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},gi=new Set([`gpt-image-1`]),_i=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return hi[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await wr({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Kn(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...gi.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:Ur,successfulResponseHandler:Mr(vi),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:d.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},vi=r.z.object({data:r.z.array(r.z.object({b64_json:r.z.string(),revised_prompt:r.z.string().optional()}))}),yi=r.z.object({code:r.z.string().nullish(),containerId:r.z.string()}),bi=r.z.object({outputs:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`logs`),logs:r.z.string()}),r.z.object({type:r.z.literal(`image`),url:r.z.string()})])).nullish()}),xi=r.z.object({container:r.z.union([r.z.string(),r.z.object({fileIds:r.z.array(r.z.string()).optional()})]).optional()}),Si=kr({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:yi,outputSchema:bi}),Ci=(e={})=>Si(e),wi=r.z.object({key:r.z.string(),type:r.z.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:r.z.union([r.z.string(),r.z.number(),r.z.boolean()])}),Ti=r.z.object({type:r.z.enum([`and`,`or`]),filters:r.z.array(r.z.union([wi,r.z.lazy(()=>Ti)]))}),Ei=r.z.object({vectorStoreIds:r.z.array(r.z.string()),maxNumResults:r.z.number().optional(),ranking:r.z.object({ranker:r.z.string().optional(),scoreThreshold:r.z.number().optional()}).optional(),filters:r.z.union([wi,Ti]).optional()}),Di=r.z.object({queries:r.z.array(r.z.string()),results:r.z.array(r.z.object({attributes:r.z.record(r.z.string(),r.z.unknown()),fileId:r.z.string(),filename:r.z.string(),score:r.z.number(),text:r.z.string()})).nullable()}),Oi=kr({id:`openai.file_search`,name:`file_search`,inputSchema:r.z.object({}),outputSchema:Di}),ki=r.z.object({background:r.z.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:r.z.enum([`low`,`high`]).optional(),inputImageMask:r.z.object({fileId:r.z.string().optional(),imageUrl:r.z.string().optional()}).optional(),model:r.z.string().optional(),moderation:r.z.enum([`auto`]).optional(),outputCompression:r.z.number().int().min(0).max(100).optional(),outputFormat:r.z.enum([`png`,`jpeg`,`webp`]).optional(),quality:r.z.enum([`auto`,`low`,`medium`,`high`]).optional(),size:r.z.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),Ai=r.z.object({result:r.z.string()}),ji=kr({id:`openai.image_generation`,name:`image_generation`,inputSchema:r.z.object({}),outputSchema:Ai}),Mi=(e={})=>ji(e),Ni=r.z.object({action:r.z.object({type:r.z.literal(`exec`),command:r.z.array(r.z.string()),timeoutMs:r.z.number().optional(),user:r.z.string().optional(),workingDirectory:r.z.string().optional(),env:r.z.record(r.z.string(),r.z.string()).optional()})}),Pi=r.z.object({output:r.z.string()}),Fi=kr({id:`openai.local_shell`,name:`local_shell`,inputSchema:Ni,outputSchema:Pi}),Ii=r.z.object({filters:r.z.object({allowedDomains:r.z.array(r.z.string()).optional()}).optional(),searchContextSize:r.z.enum([`low`,`medium`,`high`]).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),country:r.z.string().optional(),city:r.z.string().optional(),region:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),Li=Or({id:`openai.web_search`,name:`web_search`,inputSchema:r.z.object({action:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`search`),query:r.z.string().nullish()}),r.z.object({type:r.z.literal(`open_page`),url:r.z.string()}),r.z.object({type:r.z.literal(`find`),url:r.z.string(),pattern:r.z.string()})]).nullish()})}),Ri=(e={})=>Li(e),zi=r.z.object({searchContextSize:r.z.enum([`low`,`medium`,`high`]).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),country:r.z.string().optional(),city:r.z.string().optional(),region:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),Bi=Or({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:r.z.object({action:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`search`),query:r.z.string().nullish()}),r.z.object({type:r.z.literal(`open_page`),url:r.z.string()}),r.z.object({type:r.z.literal(`find`),url:r.z.string(),pattern:r.z.string()})]).nullish()})}),Vi={codeInterpreter:Ci,fileSearch:Oi,imageGeneration:Mi,localShell:Fi,webSearchPreview:Bi,webSearch:Ri};function Hi(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Ui({prompt:e,systemMessageMode:n,fileIdPrefixes:r,store:i,hasLocalShellTool:a=!1}){let o=[],s=[];for(let{role:c,content:l}of e)switch(c){case`system`:switch(n){case`system`:o.push({role:`system`,content:l});break;case`developer`:o.push({role:`developer`,content:l});break;case`remove`:s.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=n;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:o.push({role:`user`,content:l.map((e,n)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&Hi(e.data,r)?{file_id:e.data}:{image_url:`data:${t};base64,${Br(e.data)}`},detail:e.providerOptions?.openai?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&Hi(e.data,r)?{file_id:e.data}:{filename:e.filename??`part-${n}.pdf`,file_data:`data:application/pdf;base64,${Br(e.data)}`}};else throw new t.UnsupportedFunctionalityError({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of l)switch(n.type){case`text`:o.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-call`:if(t[n.toolCallId]=n,n.providerExecuted)break;if(a&&n.toolName===`local_shell`){let e=Ni.parse(n.input);o.push({type:`local_shell_call`,call_id:n.toolCallId,id:n.providerOptions?.openai?.itemId??void 0,action:{type:`exec`,command:e.action.command,timeout_ms:e.action.timeoutMs,user:e.action.user,working_directory:e.action.workingDirectory,env:e.action.env}});break}o.push({type:`function_call`,call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-result`:i?o.push({type:`item_reference`,id:n.toolCallId}):s.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let t=await Sr({provider:`openai`,providerOptions:n.providerOptions,schema:Wi}),r=t?.itemId;if(r!=null){let a=e[r];if(i)a===void 0&&(o.push({type:`item_reference`,id:r}),e[r]={type:`reasoning`,id:r,summary:[]});else{let i=[];n.text.length>0?i.push({type:`summary_text`,text:n.text}):a!==void 0&&s.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),a===void 0?(e[r]={type:`reasoning`,id:r,encrypted_content:t?.reasoningEncryptedContent,summary:i},o.push(e[r])):a.summary.push(...i)}}else s.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case`tool`:for(let e of l){let t=e.output;if(a&&e.toolName===`local_shell`&&t.type===`json`){o.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:Pi.parse(t.value).output});break}let n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}o.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=c;throw Error(`Unsupported role: ${e}`)}}return{input:o,warnings:s}}var Wi=r.z.object({itemId:r.z.string().nullish(),reasoningEncryptedContent:r.z.string().nullish()});function Gi({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function Ki({tools:e,toolChoice:n,strictJsonSchema:r}){e=e?.length?e:void 0;let i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};let a=[];for(let t of e)switch(t.type){case`function`:a.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:r});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=Ei.parse(t.args);a.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:a.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=zi.parse(t.args);a.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Ii.parse(t.args);a.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=xi.parse(t.args);a.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=ki.parse(t.args);a.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=n.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:n.toolName===`code_interpreter`||n.toolName===`file_search`||n.toolName===`image_generation`||n.toolName===`web_search_preview`||n.toolName===`web_search`?{type:n.toolName}:{type:`function`,name:n.toolName},toolWarnings:i};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${o}`})}}var qi=r.z.object({type:r.z.literal(`web_search_call`),id:r.z.string(),status:r.z.string(),action:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`search`),query:r.z.string().nullish()}),r.z.object({type:r.z.literal(`open_page`),url:r.z.string()}),r.z.object({type:r.z.literal(`find`),url:r.z.string(),pattern:r.z.string()})]).nullish()}),Ji=r.z.object({type:r.z.literal(`file_search_call`),id:r.z.string(),queries:r.z.array(r.z.string()),results:r.z.array(r.z.object({attributes:r.z.record(r.z.string(),r.z.unknown()),file_id:r.z.string(),filename:r.z.string(),score:r.z.number(),text:r.z.string()})).nullish()}),Yi=r.z.object({type:r.z.literal(`code_interpreter_call`),id:r.z.string(),code:r.z.string().nullable(),container_id:r.z.string(),outputs:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`logs`),logs:r.z.string()}),r.z.object({type:r.z.literal(`image`),url:r.z.string()})])).nullable()}),Xi=r.z.object({type:r.z.literal(`local_shell_call`),id:r.z.string(),call_id:r.z.string(),action:r.z.object({type:r.z.literal(`exec`),command:r.z.array(r.z.string()),timeout_ms:r.z.number().optional(),user:r.z.string().optional(),working_directory:r.z.string().optional(),env:r.z.record(r.z.string(),r.z.string()).optional()})}),Zi=r.z.object({type:r.z.literal(`image_generation_call`),id:r.z.string(),result:r.z.string()}),Qi=20,$i=r.z.array(r.z.object({token:r.z.string(),logprob:r.z.number(),top_logprobs:r.z.array(r.z.object({token:r.z.string(),logprob:r.z.number()}))})),ea=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){let p=[],m=ka(this.modelId);i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`});let h=await Sr({provider:`openai`,providerOptions:l,schema:Aa}),{input:g,warnings:_}=await Ui({prompt:c,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:h?.store??!0,hasLocalShellTool:x(`openai.local_shell`)});p.push(..._);let v=h?.strictJsonSchema??!1,y=h?.include;function b(e){y=y==null?[e]:[...y,e]}function x(e){return u?.find(t=>t.type===`provider-defined`&&t.id===e)!=null}let S=typeof h?.logprobs==`number`?h?.logprobs:h?.logprobs===!0?Qi:void 0;S&&b(`message.output_text.logprobs`);let C=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;C&&b(`web_search_call.action.sources`),x(`openai.code_interpreter`)&&b(`code_interpreter_call.outputs`);let w={model:this.modelId,input:g,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||h?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:v,name:f.name??`response`,description:f.description,schema:f.schema}},...h?.textVerbosity&&{verbosity:h.textVerbosity}}},max_tool_calls:h?.maxToolCalls,metadata:h?.metadata,parallel_tool_calls:h?.parallelToolCalls,previous_response_id:h?.previousResponseId,store:h?.store,user:h?.user,instructions:h?.instructions,service_tier:h?.serviceTier,include:y,prompt_cache_key:h?.promptCacheKey,safety_identifier:h?.safetyIdentifier,top_logprobs:S,...m.isReasoningModel&&(h?.reasoningEffort!=null||h?.reasoningSummary!=null)&&{reasoning:{...h?.reasoningEffort!=null&&{effort:h.reasoningEffort},...h?.reasoningSummary!=null&&{summary:h.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:`auto`}};m.isReasoningModel?(w.temperature!=null&&(w.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),w.top_p!=null&&(w.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(h?.reasoningEffort!=null&&p.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),h?.reasoningSummary!=null&&p.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),h?.serviceTier===`flex`&&!m.supportsFlexProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete w.service_tier),h?.serviceTier===`priority`&&!m.supportsPriorityProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete w.service_tier);let{tools:T,toolChoice:E,toolWarnings:D}=Ki({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:T,tool_choice:E},warnings:[...p,...D]}}async doGenerate(e){var n,i;let{args:a,warnings:o,webSearchToolName:s}=await this.getArgs(e),c=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:l,value:u,rawValue:d}=await wr({url:c,headers:Kn(this.config.headers(),e.headers),body:a,failedResponseHandler:Ur,successfulResponseHandler:Mr(r.z.object({id:r.z.string(),created_at:r.z.number(),error:r.z.object({code:r.z.string(),message:r.z.string()}).nullish(),model:r.z.string(),output:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message`),role:r.z.literal(`assistant`),id:r.z.string(),content:r.z.array(r.z.object({type:r.z.literal(`output_text`),text:r.z.string(),logprobs:$i.nullish(),annotations:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`url_citation`),start_index:r.z.number(),end_index:r.z.number(),url:r.z.string(),title:r.z.string()}),r.z.object({type:r.z.literal(`file_citation`),file_id:r.z.string(),filename:r.z.string().nullish(),index:r.z.number().nullish(),start_index:r.z.number().nullish(),end_index:r.z.number().nullish(),quote:r.z.string().nullish()}),r.z.object({type:r.z.literal(`container_file_citation`)})]))}))}),qi,Ji,Yi,Zi,Xi,r.z.object({type:r.z.literal(`function_call`),call_id:r.z.string(),name:r.z.string(),arguments:r.z.string(),id:r.z.string()}),r.z.object({type:r.z.literal(`computer_call`),id:r.z.string(),status:r.z.string().optional()}),r.z.object({type:r.z.literal(`reasoning`),id:r.z.string(),encrypted_content:r.z.string().nullish(),summary:r.z.array(r.z.object({type:r.z.literal(`summary_text`),text:r.z.string()}))})])),service_tier:r.z.string().nullish(),incomplete_details:r.z.object({reason:r.z.string()}).nullish(),usage:ta})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(u.error)throw new t.APICallError({message:u.error.message,url:c,requestBodyValues:a,statusCode:400,responseHeaders:l,responseBody:d,isRetryable:!1});let f=[],p=[],m=!1;for(let t of u.output)switch(t.type){case`reasoning`:t.summary.length===0&&t.summary.push({type:`summary_text`,text:``});for(let e of t.summary)f.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:t.id,reasoningEncryptedContent:t.encrypted_content??null}}});break;case`image_generation_call`:f.push({type:`tool-call`,toolCallId:t.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:t.id,toolName:`image_generation`,result:{result:t.result},providerExecuted:!0});break;case`local_shell_call`:f.push({type:`tool-call`,toolCallId:t.call_id,toolName:`local_shell`,input:JSON.stringify({action:t.action}),providerMetadata:{openai:{itemId:t.id}}});break;case`message`:for(let r of t.content){e.providerOptions?.openai?.logprobs&&r.logprobs&&p.push(r.logprobs),f.push({type:`text`,text:r.text,providerMetadata:{openai:{itemId:t.id}}});for(let e of r.annotations)e.type===`url_citation`?f.push({type:`source`,sourceType:`url`,id:(n=this.config).generateId?.call(n)??Qn(),url:e.url,title:e.title}):e.type===`file_citation`&&f.push({type:`source`,sourceType:`document`,id:(i=this.config).generateId?.call(i)??Qn(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:m=!0,f.push({type:`tool-call`,toolCallId:t.call_id,toolName:t.name,input:t.arguments,providerMetadata:{openai:{itemId:t.id}}});break;case`web_search_call`:f.push({type:`tool-call`,toolCallId:t.id,toolName:s??`web_search`,input:JSON.stringify({action:t.action}),providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:t.id,toolName:s??`web_search`,result:{status:t.status},providerExecuted:!0});break;case`computer_call`:f.push({type:`tool-call`,toolCallId:t.id,toolName:`computer_use`,input:``,providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:t.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:t.status||`completed`},providerExecuted:!0});break;case`file_search_call`:f.push({type:`tool-call`,toolCallId:t.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:t.id,toolName:`file_search`,result:{queries:t.queries,results:t.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});break;case`code_interpreter_call`:f.push({type:`tool-call`,toolCallId:t.id,toolName:`code_interpreter`,input:JSON.stringify({code:t.code,containerId:t.container_id}),providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:t.id,toolName:`code_interpreter`,result:{outputs:t.outputs},providerExecuted:!0});break}let h={openai:{responseId:u.id}};return p.length>0&&(h.openai.logprobs=p),typeof u.service_tier==`string`&&(h.openai.serviceTier=u.service_tier),{content:f,finishReason:Gi({finishReason:u.incomplete_details?.reason,hasFunctionCall:m}),usage:{inputTokens:u.usage.input_tokens,outputTokens:u.usage.output_tokens,totalTokens:u.usage.input_tokens+u.usage.output_tokens,reasoningTokens:u.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:u.usage.input_tokens_details?.cached_tokens??void 0},request:{body:a},response:{id:u.id,timestamp:new Date(u.created_at*1e3),modelId:u.model,headers:l,body:d},providerMetadata:h,warnings:o}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await wr({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Ur,successfulResponseHandler:jr(ma),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let g=t.value;if(Ca(g))g.item.type===`function_call`?(d[g.output_index]={toolName:g.item.name,toolCallId:g.item.call_id},n.enqueue({type:`tool-input-start`,id:g.item.call_id,toolName:g.item.name})):g.item.type===`web_search_call`?(d[g.output_index]={toolName:r??`web_search`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:r??`web_search`})):g.item.type===`computer_call`?(d[g.output_index]={toolName:`computer_use`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`computer_use`})):g.item.type===`code_interpreter_call`?(d[g.output_index]={toolName:`code_interpreter`,toolCallId:g.item.id,codeInterpreter:{containerId:g.item.container_id}},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`code_interpreter`}),n.enqueue({type:`tool-input-delta`,id:g.item.id,delta:`{"containerId":"${g.item.container_id}","code":"`})):g.item.type===`file_search_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}):g.item.type===`image_generation_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}):g.item.type===`message`?n.enqueue({type:`text-start`,id:g.item.id,providerMetadata:{openai:{itemId:g.item.id}}}):wa(g)&&(p[g.item.id]={encryptedContent:g.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${g.item.id}:0`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}}));else if(ga(g)){if(g.item.type===`function_call`)d[g.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:g.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:g.item.name,input:g.item.arguments,providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`web_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`web_search`,input:JSON.stringify({action:g.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`web_search`,result:{status:g.item.status},providerExecuted:!0});else if(g.item.type===`computer_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:g.item.status||`completed`},providerExecuted:!0});else if(g.item.type===`file_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`file_search`,result:{queries:g.item.queries,results:g.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});else if(g.item.type===`code_interpreter_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`code_interpreter`,result:{outputs:g.item.outputs},providerExecuted:!0});else if(g.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`image_generation`,result:{result:g.item.result},providerExecuted:!0});else if(g.item.type===`local_shell_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:`local_shell`,input:JSON.stringify({action:{type:`exec`,command:g.item.action.command,timeoutMs:g.item.action.timeout_ms,user:g.item.action.user,workingDirectory:g.item.action.working_directory,env:g.item.action.env}}),providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`message`)n.enqueue({type:`text-end`,id:g.item.id});else if(_a(g)){let e=p[g.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${g.item.id}:${t}`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}});delete p[g.item.id]}}else if(ba(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(xa(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(g.delta).slice(1,-1)})}else if(Sa(g)){let e=d[g.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:`code_interpreter`,input:JSON.stringify({code:g.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else ya(g)?(u=g.response.id,n.enqueue({type:`response-metadata`,id:g.response.id,timestamp:new Date(g.response.created_at*1e3),modelId:g.response.model})):ha(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):Ea(g)?g.summary_index>0&&((i=p[g.item_id])==null||i.summaryParts.push(g.summary_index),n.enqueue({type:`reasoning-start`,id:`${g.item_id}:${g.summary_index}`,providerMetadata:{openai:{itemId:g.item_id,reasoningEncryptedContent:p[g.item_id]?.encryptedContent??null}}})):Da(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):va(g)?(s=Gi({finishReason:g.response.incomplete_details?.reason,hasFunctionCall:f}),c.inputTokens=g.response.usage.input_tokens,c.outputTokens=g.response.usage.output_tokens,c.totalTokens=g.response.usage.input_tokens+g.response.usage.output_tokens,c.reasoningTokens=g.response.usage.output_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=g.response.usage.input_tokens_details?.cached_tokens??void 0,typeof g.response.service_tier==`string`&&(m=g.response.service_tier)):Ta(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??Qn(),url:g.annotation.url,title:g.annotation.title}):g.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(h=o.config).generateId?.call(h)??Qn(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):Oa(g)&&n.enqueue({type:`error`,error:g})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},ta=r.z.object({input_tokens:r.z.number(),input_tokens_details:r.z.object({cached_tokens:r.z.number().nullish()}).nullish(),output_tokens:r.z.number(),output_tokens_details:r.z.object({reasoning_tokens:r.z.number().nullish()}).nullish()}),na=r.z.object({type:r.z.literal(`response.output_text.delta`),item_id:r.z.string(),delta:r.z.string(),logprobs:$i.nullish()}),ra=r.z.object({type:r.z.literal(`error`),code:r.z.string(),message:r.z.string(),param:r.z.string().nullish(),sequence_number:r.z.number()}),ia=r.z.object({type:r.z.enum([`response.completed`,`response.incomplete`]),response:r.z.object({incomplete_details:r.z.object({reason:r.z.string()}).nullish(),usage:ta,service_tier:r.z.string().nullish()})}),aa=r.z.object({type:r.z.literal(`response.created`),response:r.z.object({id:r.z.string(),created_at:r.z.number(),model:r.z.string(),service_tier:r.z.string().nullish()})}),oa=r.z.object({type:r.z.literal(`response.output_item.added`),output_index:r.z.number(),item:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message`),id:r.z.string()}),r.z.object({type:r.z.literal(`reasoning`),id:r.z.string(),encrypted_content:r.z.string().nullish()}),r.z.object({type:r.z.literal(`function_call`),id:r.z.string(),call_id:r.z.string(),name:r.z.string(),arguments:r.z.string()}),r.z.object({type:r.z.literal(`web_search_call`),id:r.z.string(),status:r.z.string(),action:r.z.object({type:r.z.literal(`search`),query:r.z.string().optional()}).nullish()}),r.z.object({type:r.z.literal(`computer_call`),id:r.z.string(),status:r.z.string()}),r.z.object({type:r.z.literal(`file_search_call`),id:r.z.string()}),r.z.object({type:r.z.literal(`image_generation_call`),id:r.z.string()}),r.z.object({type:r.z.literal(`code_interpreter_call`),id:r.z.string(),container_id:r.z.string(),code:r.z.string().nullable(),outputs:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`logs`),logs:r.z.string()}),r.z.object({type:r.z.literal(`image`),url:r.z.string()})])).nullable(),status:r.z.string()})])}),sa=r.z.object({type:r.z.literal(`response.output_item.done`),output_index:r.z.number(),item:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message`),id:r.z.string()}),r.z.object({type:r.z.literal(`reasoning`),id:r.z.string(),encrypted_content:r.z.string().nullish()}),r.z.object({type:r.z.literal(`function_call`),id:r.z.string(),call_id:r.z.string(),name:r.z.string(),arguments:r.z.string(),status:r.z.literal(`completed`)}),Yi,Zi,qi,Ji,Xi,r.z.object({type:r.z.literal(`computer_call`),id:r.z.string(),status:r.z.literal(`completed`)})])}),ca=r.z.object({type:r.z.literal(`response.function_call_arguments.delta`),item_id:r.z.string(),output_index:r.z.number(),delta:r.z.string()}),la=r.z.object({type:r.z.literal(`response.code_interpreter_call_code.delta`),item_id:r.z.string(),output_index:r.z.number(),delta:r.z.string()}),ua=r.z.object({type:r.z.literal(`response.code_interpreter_call_code.done`),item_id:r.z.string(),output_index:r.z.number(),code:r.z.string()}),da=r.z.object({type:r.z.literal(`response.output_text.annotation.added`),annotation:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`url_citation`),url:r.z.string(),title:r.z.string()}),r.z.object({type:r.z.literal(`file_citation`),file_id:r.z.string(),filename:r.z.string().nullish(),index:r.z.number().nullish(),start_index:r.z.number().nullish(),end_index:r.z.number().nullish(),quote:r.z.string().nullish()})])}),fa=r.z.object({type:r.z.literal(`response.reasoning_summary_part.added`),item_id:r.z.string(),summary_index:r.z.number()}),pa=r.z.object({type:r.z.literal(`response.reasoning_summary_text.delta`),item_id:r.z.string(),summary_index:r.z.number(),delta:r.z.string()}),ma=r.z.union([na,ia,aa,oa,sa,ca,la,ua,da,fa,pa,ra,r.z.object({type:r.z.string()}).loose()]);function ha(e){return e.type===`response.output_text.delta`}function ga(e){return e.type===`response.output_item.done`}function _a(e){return ga(e)&&e.item.type===`reasoning`}function va(e){return e.type===`response.completed`||e.type===`response.incomplete`}function ya(e){return e.type===`response.created`}function ba(e){return e.type===`response.function_call_arguments.delta`}function xa(e){return e.type===`response.code_interpreter_call_code.delta`}function Sa(e){return e.type===`response.code_interpreter_call_code.done`}function Ca(e){return e.type===`response.output_item.added`}function wa(e){return Ca(e)&&e.item.type===`reasoning`}function Ta(e){return e.type===`response.output_text.annotation.added`}function Ea(e){return e.type===`response.reasoning_summary_part.added`}function Da(e){return e.type===`response.reasoning_summary_text.delta`}function Oa(e){return e.type===`error`}function ka(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var Aa=r.z.object({include:r.z.array(r.z.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:r.z.string().nullish(),logprobs:r.z.union([r.z.boolean(),r.z.number().min(1).max(Qi)]).optional(),maxToolCalls:r.z.number().nullish(),metadata:r.z.any().nullish(),parallelToolCalls:r.z.boolean().nullish(),previousResponseId:r.z.string().nullish(),promptCacheKey:r.z.string().nullish(),reasoningEffort:r.z.string().nullish(),reasoningSummary:r.z.string().nullish(),safetyIdentifier:r.z.string().nullish(),serviceTier:r.z.enum([`auto`,`flex`,`priority`]).nullish(),store:r.z.boolean().nullish(),strictJsonSchema:r.z.boolean().nullish(),textVerbosity:r.z.enum([`low`,`medium`,`high`]).nullish(),user:r.z.string().nullish()}),ja=r.z.object({instructions:r.z.string().nullish(),speed:r.z.number().min(.25).max(4).default(1).nullish()}),Ma=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await Sr({provider:`openai`,providerOptions:o,schema:ja}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await wr({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),body:r,failedResponseHandler:Ur,successfulResponseHandler:Nr(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Na=r.z.object({include:r.z.array(r.z.string()).optional(),language:r.z.string().optional(),prompt:r.z.string().optional(),temperature:r.z.number().min(0).max(1).default(0).optional(),timestampGranularities:r.z.array(r.z.enum([`word`,`segment`])).default([`segment`]).optional()}),Pa={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},Fa=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await Sr({provider:`openai`,providerOptions:n,schema:Na}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([Rr(e)]);a.append(`model`,this.modelId);let s=ar(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await Tr({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),formData:r,failedResponseHandler:Ur,successfulResponseHandler:Mr(Ia),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in Pa?Pa[a.language]:void 0;return{text:a.text,segments:a.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??a.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:c,durationInSeconds:a.duration??void 0,warnings:i,response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Ia=r.z.object({text:r.z.string(),language:r.z.string().nullish(),duration:r.z.number().nullish(),words:r.z.array(r.z.object({word:r.z.string(),start:r.z.number(),end:r.z.number()})).nullish(),segments:r.z.array(r.z.object({id:r.z.number(),seek:r.z.number(),start:r.z.number(),end:r.z.number(),text:r.z.string(),tokens:r.z.array(r.z.number()),temperature:r.z.number(),avg_logprob:r.z.number(),compression_ratio:r.z.number(),no_speech_prob:r.z.number()})).nullish()}),La=`2.0.42`;function Ra(e={}){let t=Vr(ir({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>Xn({Authorization:`Bearer ${rr({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${La}`),i=i=>new Yr(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new ci(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new pi(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new _i(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new Fa(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new Ma(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),u=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return d(e)},d=i=>new ea(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),f=function(e){return u(e)};return f.languageModel=u,f.chat=i,f.completion=a,f.responses=d,f.embedding=o,f.textEmbedding=o,f.textEmbeddingModel=o,f.image=s,f.imageModel=s,f.transcription=c,f.transcriptionModel=c,f.speech=l,f.speechModel=l,f.tools=Vi,f}var za=Ra();function Ba(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function Va(e){return Object.fromEntries([...e.headers])}function Ha(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function Ua(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Wa(e,...t){let n=Ua(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ga=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},Ka=Ga();function qa(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Ja=[`fetch failed`,`failed to fetch`];function Ya({error:e,url:n,requestBodyValues:r}){if(qa(e))return e;if(e instanceof TypeError&&Ja.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var Xa=`3.0.10`,Za=/"__proto__"\s*:/,Qa=/"constructor"\s*:/;function $a(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Za.test(e)===!1&&Qa.test(e)===!1?t:eo(t)}function eo(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function to(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return $a(e)}finally{Error.stackTraceLimit=t}}var no=Symbol.for(`vercel.ai.validator`);function ro(e){return{[no]:!0,validate:e}}function io(e){return typeof e==`object`&&!!e&&no in e&&e[no]===!0&&`validate`in e}function ao(e){return io(e)?e:oo(e)}function oo(e){return ro(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function so({value:e,schema:n}){let r=await co({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function co({value:e,schema:n}){let r=ao(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function lo({text:e,schema:n}){try{let t=to(e);return n==null?t:so({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function uo({text:e,schema:n}){try{let t=to(e);return n==null?{success:!0,value:t,rawValue:t}:await co({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}var fo=()=>globalThis.fetch,po=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>mo({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),mo=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=fo()})=>{try{let c=await s(e,{method:`POST`,headers:Wa(n,`ai-sdk/provider-utils/${Xa}`,Ha()),body:r.content,signal:o}),l=Va(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw qa(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(qa(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw Ya({error:t,url:e,requestBodyValues:r.values})}},ho=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=Va(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await lo({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},go=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await uo({text:a,schema:e}),s=Va(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},_o=Symbol(`Let zodToJsonSchema decide on which parser to use`),vo=Symbol.for(`vercel.ai.schema`),{btoa:yo,atob:bo}=globalThis,xo=r.z.object({user:r.z.string().optional(),reasoningEffort:r.z.string().optional()}),So={errorSchema:r.z.object({error:r.z.object({message:r.z.string(),type:r.z.string().nullish(),param:r.z.any().nullish(),code:r.z.union([r.z.string(),r.z.number()]).nullish()})}),errorToMessage:e=>e.error.message},Co=r.z.object({prompt_tokens:r.z.number().nullish(),completion_tokens:r.z.number().nullish(),total_tokens:r.z.number().nullish(),prompt_tokens_details:r.z.object({cached_tokens:r.z.number().nullish()}).nullish(),completion_tokens_details:r.z.object({reasoning_tokens:r.z.number().nullish(),accepted_prediction_tokens:r.z.number().nullish(),rejected_prediction_tokens:r.z.number().nullish()}).nullish()}).nullish(),wo=r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({message:r.z.object({role:r.z.literal(`assistant`).nullish(),content:r.z.string().nullish(),reasoning_content:r.z.string().nullish(),reasoning:r.z.string().nullish(),tool_calls:r.z.array(r.z.object({id:r.z.string().nullish(),function:r.z.object({name:r.z.string(),arguments:r.z.string()})})).nullish()}),finish_reason:r.z.string().nullish()})),usage:Co}),To=r.z.object({echo:r.z.boolean().optional(),logitBias:r.z.record(r.z.string(),r.z.number()).optional(),suffix:r.z.string().optional(),user:r.z.string().optional()}),Eo=r.z.object({prompt_tokens:r.z.number(),completion_tokens:r.z.number(),total_tokens:r.z.number()}),Do=r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({text:r.z.string(),finish_reason:r.z.string()})),usage:Eo.nullish()}),Oo=r.z.object({dimensions:r.z.number().optional(),user:r.z.string().optional()}),ko=r.z.object({data:r.z.array(r.z.object({embedding:r.z.array(r.z.number())})),usage:r.z.object({prompt_tokens:r.z.number()}).nullish(),providerMetadata:r.z.record(r.z.string(),r.z.record(r.z.string(),r.z.any())).optional()}),Ao=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await po({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Ba(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:ho(this.config.errorStructure??So),successfulResponseHandler:go(jo),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f}}}},jo=r.z.object({data:r.z.array(r.z.object({b64_json:r.z.string()}))});function Mo(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function No(e){return Object.fromEntries([...e.headers])}function Po(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function Fo(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Io(e,...t){let n=Fo(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Lo=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},Ro=Lo();function zo(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Bo=[`fetch failed`,`failed to fetch`];function Vo({error:e,url:n,requestBodyValues:r}){if(zo(e))return e;if(e instanceof TypeError&&Bo.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var Ho=`3.0.10`;function Uo({apiKey:e,environmentVariableName:n,apiKeyParameterName:r=`apiKey`,description:i}){if(typeof e==`string`)return e;if(e!=null)throw new t.LoadAPIKeyError({message:`${i} API key must be a string.`});if(typeof process>`u`)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[n],e==null)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter or the ${n} environment variable.`});if(typeof e!=`string`)throw new t.LoadAPIKeyError({message:`${i} API key must be a string. The value of the ${n} environment variable is not a string.`});return e}var Wo=/"__proto__"\s*:/,Go=/"constructor"\s*:/;function Ko(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Wo.test(e)===!1&&Go.test(e)===!1?t:qo(t)}function qo(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Jo(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Ko(e)}finally{Error.stackTraceLimit=t}}var Yo=Symbol.for(`vercel.ai.validator`);function Xo(e){return{[Yo]:!0,validate:e}}function Zo(e){return typeof e==`object`&&!!e&&Yo in e&&e[Yo]===!0&&`validate`in e}function Qo(e){return Zo(e)?e:$o(e)}function $o(e){return Xo(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function es({value:e,schema:n}){let r=await ts({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function ts({value:e,schema:n}){let r=Qo(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function ns({text:e,schema:n}){try{let t=Jo(e);return n==null?t:es({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function rs({text:e,schema:n}){try{let t=Jo(e);return n==null?{success:!0,value:t,rawValue:t}:await ts({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}function os({stream:e,schema:n}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:e},t){e!==`[DONE]`&&t.enqueue(await rs({text:e,schema:n}))}}))}async function ss({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await ts({value:n[e],schema:r});if(!i.success)throw new t.InvalidArgumentError({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var cs=()=>globalThis.fetch,ls=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>us({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),us=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=cs()})=>{try{let c=await s(e,{method:`POST`,headers:Io(n,`ai-sdk/provider-utils/${Ho}`,Po()),body:r.content,signal:o}),l=No(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw zo(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(zo(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw Vo({error:t,url:e,requestBodyValues:r.values})}},ds=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=No(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await ns({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},fs=e=>async({response:n})=>{let r=No(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:os({stream:n.body,schema:e})}},ps=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await rs({text:a,schema:e}),s=No(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},ms=Symbol(`Let zodToJsonSchema decide on which parser to use`),hs=Symbol.for(`vercel.ai.schema`),{btoa:gs,atob:_s}=globalThis;function vs(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return gs(t)}function ys(e){return e instanceof Uint8Array?vs(e):e}function bs(e){return e?.replace(/\/$/,``)}function xs(e){let n=[],r=[];for(let{role:r,content:i}of e)switch(r){case`system`:n.push({role:`system`,content:i});break;case`user`:if(i.length===1&&i[0].type===`text`){n.push({role:`user`,content:i[0].text});break}n.push({role:`user`,content:i.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${ys(e.data)}`}}}else throw new t.UnsupportedFunctionalityError({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of i)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:JSON.stringify(n.input)}});break}n.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of i){let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function Ss({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Cs(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var ws=r.z.object({type:r.z.literal(`web`),country:r.z.string().length(2).optional(),excludedWebsites:r.z.array(r.z.string()).max(5).optional(),allowedWebsites:r.z.array(r.z.string()).max(5).optional(),safeSearch:r.z.boolean().optional()}),Ts=r.z.object({type:r.z.literal(`x`),excludedXHandles:r.z.array(r.z.string()).optional(),includedXHandles:r.z.array(r.z.string()).optional(),postFavoriteCount:r.z.number().int().optional(),postViewCount:r.z.number().int().optional(),xHandles:r.z.array(r.z.string()).optional()}),Es=r.z.object({type:r.z.literal(`news`),country:r.z.string().length(2).optional(),excludedWebsites:r.z.array(r.z.string()).max(5).optional(),safeSearch:r.z.boolean().optional()}),Ds=r.z.object({type:r.z.literal(`rss`),links:r.z.array(r.z.string().url()).max(1)}),Os=r.z.discriminatedUnion(`type`,[ws,Ts,Es,Ds]),ks=r.z.object({reasoningEffort:r.z.enum([`low`,`high`]).optional(),searchParameters:r.z.object({mode:r.z.enum([`off`,`auto`,`on`]),returnCitations:r.z.boolean().optional(),fromDate:r.z.string().optional(),toDate:r.z.string().optional(),maxSearchResults:r.z.number().min(1).max(50).optional(),sources:r.z.array(Os).optional()}).optional()}),As=r.z.object({error:r.z.object({message:r.z.string(),type:r.z.string().nullish(),param:r.z.any().nullish(),code:r.z.union([r.z.string(),r.z.number()]).nullish()})}),js=ds({errorSchema:As,errorToMessage:e=>e.error.message});function Ms({tools:e,toolChoice:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)t.type===`provider-defined`?r.push({type:`unsupported-tool`,tool:t}):i.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(n==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=n.type;switch(a){case`auto`:case`none`:return{tools:i,toolChoice:a,toolWarnings:r};case`required`:return{tools:i,toolChoice:`required`,toolWarnings:r};case`tool`:return{tools:i,toolChoice:{type:`function`,function:{name:n.toolName}},toolWarnings:r};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${a}`})}}var Ns=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){let p=[],m=await ss({provider:`xai`,providerOptions:u,schema:ks})??{};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:h,warnings:g}=xs(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=Ms({tools:d,toolChoice:f});return p.push(...y),{args:{model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:m.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:l.name??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:m.searchParameters?{mode:m.searchParameters.mode,return_citations:m.searchParameters.returnCitations,from_date:m.searchParameters.fromDate,to_date:m.searchParameters.toDate,max_search_results:m.searchParameters.maxSearchResults,sources:m.searchParameters.sources?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{excluded_x_handles:e.excludedXHandles,included_x_handles:e.includedXHandles??e.xHandles,post_favorite_count:e.postFavoriteCount,post_view_count:e.postViewCount},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:h,tools:_,tool_choice:v},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await ls({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:Mo(this.config.headers(),e.headers),body:t,failedResponseHandler:js,successfulResponseHandler:ps(Fs),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[];if(o.message.content!=null&&o.message.content.length>0){let e=o.message.content,n=t.messages[t.messages.length-1];n?.role===`assistant`&&e===n.content&&(e=``),e.length>0&&s.push({type:`text`,text:e})}if(o.message.reasoning_content!=null&&o.message.reasoning_content.length>0&&s.push({type:`reasoning`,text:o.message.reasoning_content}),o.message.tool_calls!=null)for(let e of o.message.tool_calls)s.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(i.citations!=null)for(let e of i.citations)s.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:s,finishReason:Cs(o.finish_reason),usage:{inputTokens:i.usage.prompt_tokens,outputTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens,reasoningTokens:i.usage.completion_tokens_details?.reasoning_tokens??void 0},request:{body:t},response:{...Ss(i),headers:r,body:a},warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await ls({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:Mo(this.config.headers(),e.headers),body:r,failedResponseHandler:js,successfulResponseHandler:fs(Is),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},c=!0,l={},u={},d=this;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let i=t.value;if(c&&=(n.enqueue({type:`response-metadata`,...Ss(i)}),!1),i.citations!=null)for(let e of i.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});i.usage!=null&&(s.inputTokens=i.usage.prompt_tokens,s.outputTokens=i.usage.completion_tokens,s.totalTokens=i.usage.total_tokens,s.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0);let a=i.choices[0];if(a?.finish_reason!=null&&(o=Cs(a.finish_reason)),a?.delta==null)return;let f=a.delta,p=a.index;if(f.content!=null&&f.content.length>0){let e=f.content,t=r.messages[r.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let a=`text-${i.id||p}`;l[a]??(l[a]={type:`text`},n.enqueue({type:`text-start`,id:a})),n.enqueue({type:`text-delta`,id:a,delta:e})}if(f.reasoning_content!=null&&f.reasoning_content.length>0){let e=`reasoning-${i.id||p}`;if(u[e]===f.reasoning_content)return;u[e]=f.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:f.reasoning_content})}if(f.tool_calls!=null)for(let e of f.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:o,usage:s})}})),request:{body:r},response:{headers:i}}}},Ps=r.z.object({prompt_tokens:r.z.number(),completion_tokens:r.z.number(),total_tokens:r.z.number(),completion_tokens_details:r.z.object({reasoning_tokens:r.z.number().nullish()}).nullish()}),Fs=r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({message:r.z.object({role:r.z.literal(`assistant`),content:r.z.string().nullish(),reasoning_content:r.z.string().nullish(),tool_calls:r.z.array(r.z.object({id:r.z.string(),type:r.z.literal(`function`),function:r.z.object({name:r.z.string(),arguments:r.z.string()})})).nullish()}),index:r.z.number(),finish_reason:r.z.string().nullish()})),object:r.z.literal(`chat.completion`),usage:Ps,citations:r.z.array(r.z.string().url()).nullish()}),Is=r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({delta:r.z.object({role:r.z.enum([`assistant`]).optional(),content:r.z.string().nullish(),reasoning_content:r.z.string().nullish(),tool_calls:r.z.array(r.z.object({id:r.z.string(),type:r.z.literal(`function`),function:r.z.object({name:r.z.string(),arguments:r.z.string()})})).nullish()}),finish_reason:r.z.string().nullish(),index:r.z.number()})),usage:Ps.nullish(),citations:r.z.array(r.z.string().url()).nullish()}),Ls=`2.0.23`,Rs={errorSchema:As,errorToMessage:e=>e.error.message};function zs(e={}){let n=bs(e.baseURL??`https://api.x.ai/v1`),r=()=>Io({Authorization:`Bearer ${Uo({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${Ls}`),i=t=>new Ns(t,{provider:`xai.chat`,baseURL:n,headers:r,generateId:Ro,fetch:e.fetch}),a=t=>new Ao(t,{provider:`xai.image`,url:({path:e})=>`${n}${e}`,headers:r,fetch:e.fetch,errorStructure:Rs}),o=e=>i(e);return o.languageModel=i,o.chat=i,o.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},o.imageModel=a,o.image=a,o}var Bs=zs();function Vs(e){if(!e.body)throw Error(`Response body is required`);let n=e.headers.get(t.StreamResponseFormatHeader);if(!n||n===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let r=e=>(0,m.streamText)({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(n){case`openai-chat`:return r(Ra({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return r(Ra({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return r(gt({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return r(Wn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return r(zs({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${n}`)}}var Hs=class{baseUrl;client;constructor(e){this.client=t.hc(e.baseUrl),this.baseUrl=e.baseUrl}async chat(e,t){let n=await this.client._agent.chat.$post({json:e},{headers:t?.headers,init:{signal:t?.signal}});return n.ok||await this.handleError(n),Vs(n)}async capabilities(){let e=await this.client._agent.capabilities.$get();return e.ok||await this.handleError(e),e.json()}async ui(e,t){let n=await this.client._agent.ui.$get({query:e.selectedOptions?{selected_options:JSON.stringify(e.selectedOptions)}:{}},{init:{signal:t?.signal}});if(!n.ok||n.status!==200){if(n.status===404)return;await this.handleError(n)}return n.json()}async health(){let e=await this.client._agent.health.$get();e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed (${e.status}): ${t}`)}throw Error(`Failed (${e.status}): ${e.statusText}`)}};function Us(e){let[n,r]=(0,_.useState)(void 0),[i,a]=(0,_.useState)([]),[o,s]=(0,_.useState)(void 0),[c,l]=(0,_.useState)(e.buildResult),[u,d]=(0,_.useState)(e.env),[f,p]=(0,_.useState)(e.apiServerUrl),[m,h]=(0,_.useState)(void 0);return(0,_.useEffect)(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),(0,_.useEffect)(()=>{if(!c||`error`in c){r(void 0),a([]),s(void 0),h(void 0);return}let e=new AbortController,n=!1;return s(void 0),r(void 0),h(void 0),(async()=>{let n=await Ws(),i=(0,g.spawn)(`node`,[`--no-deprecation`,c.entry],{stdio:`pipe`,env:{...process.env,...u,[t.APIServerURLEnvironmentVariable]:f,PORT:n.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{i.kill()}catch{}});let o=!1;i.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!o&&t.startsWith(`Agent server listening on`)||(o||console.log(`stdout: ${t}`),t.length&&a(e=>[...e,{level:`log`,message:t}]))}),i.stderr.on(`data`,e=>{o||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&a(e=>[...e,{level:`error`,message:t}])}),i.on(`error`,t=>{e.abort(t)}),i.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let s=new Hs({baseUrl:`http://127.0.0.1:${n}`});for(;!e.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;o=!0;let l=await s.capabilities();h(l),r(s)})().catch(e=>{n||s(e instanceof Error?e:Error(String(e)))}),()=>{n=!0,e.abort()}},[c,u,f]),(0,_.useMemo)(()=>({agent:n,logs:i,error:o,capabilities:m}),[n,i,o,m])}async function Ws(){let e=(0,d.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var Gs=Object.getOwnPropertyNames,W=(e,t)=>function(){return t||(0,e[Gs(e)[0]])((t={exports:{}}).exports,t),t.exports},G=(0,v.createRequire)(require(`url`).pathToFileURL(__filename).href);y.z.object({email:y.z.string().email(),password:y.z.string().min(8)}),y.z.object({email:y.z.string().email(),code:y.z.string()}),y.z.object({email:y.z.string().email(),password:y.z.string().min(8)});var Ks=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},qs=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Js(e){}function Ys(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Js,onError:n=Js,onRetry:r=Js,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Xs(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
16
|
-
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new
|
|
17
|
-
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function
|
|
15
|
+
${n}:`]}}function ai({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function oi(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var si=r.z.object({echo:r.z.boolean().optional(),logitBias:r.z.record(r.z.string(),r.z.number()).optional(),suffix:r.z.string().optional(),user:r.z.string().optional(),logprobs:r.z.union([r.z.boolean(),r.z.number()]).optional()}),ci=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await Sr({provider:`openai`,providerOptions:f,schema:si}),...await Sr({provider:this.providerOptionsName,providerOptions:f,schema:si})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=ii({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await wr({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),body:t,failedResponseHandler:Ur,successfulResponseHandler:Mr(ui),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s={openai:{}};return o.logprobs!=null&&(s.openai.logprobs=o.logprobs),{content:[{type:`text`,text:o.text}],usage:{inputTokens:i.usage?.prompt_tokens,outputTokens:i.usage?.completion_tokens,totalTokens:i.usage?.total_tokens},finishReason:oi(o.finish_reason),request:{body:t},response:{...ai(i),headers:r,body:a},providerMetadata:s,warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await wr({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),body:r,failedResponseHandler:Ur,successfulResponseHandler:jr(di),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...ai(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=oi(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},li=r.z.object({prompt_tokens:r.z.number(),completion_tokens:r.z.number(),total_tokens:r.z.number()}),ui=r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({text:r.z.string(),finish_reason:r.z.string(),logprobs:r.z.object({tokens:r.z.array(r.z.string()),token_logprobs:r.z.array(r.z.number()),top_logprobs:r.z.array(r.z.record(r.z.string(),r.z.number())).nullish()}).nullish()})),usage:li.nullish()}),di=r.z.union([r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({text:r.z.string(),finish_reason:r.z.string().nullish(),index:r.z.number(),logprobs:r.z.object({tokens:r.z.array(r.z.string()),token_logprobs:r.z.array(r.z.number()),top_logprobs:r.z.array(r.z.record(r.z.string(),r.z.number())).nullish()}).nullish()})),usage:li.nullish()}),Hr]),fi=r.z.object({dimensions:r.z.number().optional(),user:r.z.string().optional()}),pi=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=await Sr({provider:`openai`,providerOptions:i,schema:fi})??{},{responseHeaders:o,value:s,rawValue:c}=await wr({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:Kn(this.config.headers(),n),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:a.dimensions,user:a.user},failedResponseHandler:Ur,successfulResponseHandler:Mr(mi),abortSignal:r,fetch:this.config.fetch});return{embeddings:s.data.map(e=>e.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:o,body:c}}}},mi=r.z.object({data:r.z.array(r.z.object({embedding:r.z.array(r.z.number())})),usage:r.z.object({prompt_tokens:r.z.number()}).nullish()}),hi={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},gi=new Set([`gpt-image-1`]),_i=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return hi[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await wr({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Kn(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...gi.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:Ur,successfulResponseHandler:Mr(vi),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f},providerMetadata:{openai:{images:d.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},vi=r.z.object({data:r.z.array(r.z.object({b64_json:r.z.string(),revised_prompt:r.z.string().optional()}))}),yi=r.z.object({code:r.z.string().nullish(),containerId:r.z.string()}),bi=r.z.object({outputs:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`logs`),logs:r.z.string()}),r.z.object({type:r.z.literal(`image`),url:r.z.string()})])).nullish()}),xi=r.z.object({container:r.z.union([r.z.string(),r.z.object({fileIds:r.z.array(r.z.string()).optional()})]).optional()}),Si=kr({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:yi,outputSchema:bi}),Ci=(e={})=>Si(e),wi=r.z.object({key:r.z.string(),type:r.z.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:r.z.union([r.z.string(),r.z.number(),r.z.boolean()])}),Ti=r.z.object({type:r.z.enum([`and`,`or`]),filters:r.z.array(r.z.union([wi,r.z.lazy(()=>Ti)]))}),Ei=r.z.object({vectorStoreIds:r.z.array(r.z.string()),maxNumResults:r.z.number().optional(),ranking:r.z.object({ranker:r.z.string().optional(),scoreThreshold:r.z.number().optional()}).optional(),filters:r.z.union([wi,Ti]).optional()}),Di=r.z.object({queries:r.z.array(r.z.string()),results:r.z.array(r.z.object({attributes:r.z.record(r.z.string(),r.z.unknown()),fileId:r.z.string(),filename:r.z.string(),score:r.z.number(),text:r.z.string()})).nullable()}),Oi=kr({id:`openai.file_search`,name:`file_search`,inputSchema:r.z.object({}),outputSchema:Di}),ki=r.z.object({background:r.z.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:r.z.enum([`low`,`high`]).optional(),inputImageMask:r.z.object({fileId:r.z.string().optional(),imageUrl:r.z.string().optional()}).optional(),model:r.z.string().optional(),moderation:r.z.enum([`auto`]).optional(),outputCompression:r.z.number().int().min(0).max(100).optional(),outputFormat:r.z.enum([`png`,`jpeg`,`webp`]).optional(),quality:r.z.enum([`auto`,`low`,`medium`,`high`]).optional(),size:r.z.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),Ai=r.z.object({result:r.z.string()}),ji=kr({id:`openai.image_generation`,name:`image_generation`,inputSchema:r.z.object({}),outputSchema:Ai}),Mi=(e={})=>ji(e),Ni=r.z.object({action:r.z.object({type:r.z.literal(`exec`),command:r.z.array(r.z.string()),timeoutMs:r.z.number().optional(),user:r.z.string().optional(),workingDirectory:r.z.string().optional(),env:r.z.record(r.z.string(),r.z.string()).optional()})}),Pi=r.z.object({output:r.z.string()}),Fi=kr({id:`openai.local_shell`,name:`local_shell`,inputSchema:Ni,outputSchema:Pi}),Ii=r.z.object({filters:r.z.object({allowedDomains:r.z.array(r.z.string()).optional()}).optional(),searchContextSize:r.z.enum([`low`,`medium`,`high`]).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),country:r.z.string().optional(),city:r.z.string().optional(),region:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),Li=Or({id:`openai.web_search`,name:`web_search`,inputSchema:r.z.object({action:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`search`),query:r.z.string().nullish()}),r.z.object({type:r.z.literal(`open_page`),url:r.z.string()}),r.z.object({type:r.z.literal(`find`),url:r.z.string(),pattern:r.z.string()})]).nullish()})}),Ri=(e={})=>Li(e),zi=r.z.object({searchContextSize:r.z.enum([`low`,`medium`,`high`]).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),country:r.z.string().optional(),city:r.z.string().optional(),region:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),Bi=Or({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:r.z.object({action:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`search`),query:r.z.string().nullish()}),r.z.object({type:r.z.literal(`open_page`),url:r.z.string()}),r.z.object({type:r.z.literal(`find`),url:r.z.string(),pattern:r.z.string()})]).nullish()})}),Vi={codeInterpreter:Ci,fileSearch:Oi,imageGeneration:Mi,localShell:Fi,webSearchPreview:Bi,webSearch:Ri};function Hi(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Ui({prompt:e,systemMessageMode:n,fileIdPrefixes:r,store:i,hasLocalShellTool:a=!1}){let o=[],s=[];for(let{role:c,content:l}of e)switch(c){case`system`:switch(n){case`system`:o.push({role:`system`,content:l});break;case`developer`:o.push({role:`developer`,content:l});break;case`remove`:s.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=n;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:o.push({role:`user`,content:l.map((e,n)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&Hi(e.data,r)?{file_id:e.data}:{image_url:`data:${t};base64,${Br(e.data)}`},detail:e.providerOptions?.openai?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&Hi(e.data,r)?{file_id:e.data}:{filename:e.filename??`part-${n}.pdf`,file_data:`data:application/pdf;base64,${Br(e.data)}`}};else throw new t.UnsupportedFunctionalityError({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of l)switch(n.type){case`text`:o.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-call`:if(t[n.toolCallId]=n,n.providerExecuted)break;if(a&&n.toolName===`local_shell`){let e=Ni.parse(n.input);o.push({type:`local_shell_call`,call_id:n.toolCallId,id:n.providerOptions?.openai?.itemId??void 0,action:{type:`exec`,command:e.action.command,timeout_ms:e.action.timeoutMs,user:e.action.user,working_directory:e.action.workingDirectory,env:e.action.env}});break}o.push({type:`function_call`,call_id:n.toolCallId,name:n.toolName,arguments:JSON.stringify(n.input),id:n.providerOptions?.openai?.itemId??void 0});break;case`tool-result`:i?o.push({type:`item_reference`,id:n.toolCallId}):s.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let t=await Sr({provider:`openai`,providerOptions:n.providerOptions,schema:Wi}),r=t?.itemId;if(r!=null){let a=e[r];if(i)a===void 0&&(o.push({type:`item_reference`,id:r}),e[r]={type:`reasoning`,id:r,summary:[]});else{let i=[];n.text.length>0?i.push({type:`summary_text`,text:n.text}):a!==void 0&&s.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),a===void 0?(e[r]={type:`reasoning`,id:r,encrypted_content:t?.reasoningEncryptedContent,summary:i},o.push(e[r])):a.summary.push(...i)}}else s.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case`tool`:for(let e of l){let t=e.output;if(a&&e.toolName===`local_shell`&&t.type===`json`){o.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:Pi.parse(t.value).output});break}let n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}o.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=c;throw Error(`Unsupported role: ${e}`)}}return{input:o,warnings:s}}var Wi=r.z.object({itemId:r.z.string().nullish(),reasoningEncryptedContent:r.z.string().nullish()});function Gi({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function Ki({tools:e,toolChoice:n,strictJsonSchema:r}){e=e?.length?e:void 0;let i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};let a=[];for(let t of e)switch(t.type){case`function`:a.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:r});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=Ei.parse(t.args);a.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:a.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=zi.parse(t.args);a.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Ii.parse(t.args);a.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=xi.parse(t.args);a.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=ki.parse(t.args);a.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,size:e.size,quality:e.quality,moderation:e.moderation,output_format:e.outputFormat,output_compression:e.outputCompression});break}}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=n.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:n.toolName===`code_interpreter`||n.toolName===`file_search`||n.toolName===`image_generation`||n.toolName===`web_search_preview`||n.toolName===`web_search`?{type:n.toolName}:{type:`function`,name:n.toolName},toolWarnings:i};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${o}`})}}var qi=r.z.object({type:r.z.literal(`web_search_call`),id:r.z.string(),status:r.z.string(),action:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`search`),query:r.z.string().nullish()}),r.z.object({type:r.z.literal(`open_page`),url:r.z.string()}),r.z.object({type:r.z.literal(`find`),url:r.z.string(),pattern:r.z.string()})]).nullish()}),Ji=r.z.object({type:r.z.literal(`file_search_call`),id:r.z.string(),queries:r.z.array(r.z.string()),results:r.z.array(r.z.object({attributes:r.z.record(r.z.string(),r.z.unknown()),file_id:r.z.string(),filename:r.z.string(),score:r.z.number(),text:r.z.string()})).nullish()}),Yi=r.z.object({type:r.z.literal(`code_interpreter_call`),id:r.z.string(),code:r.z.string().nullable(),container_id:r.z.string(),outputs:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`logs`),logs:r.z.string()}),r.z.object({type:r.z.literal(`image`),url:r.z.string()})])).nullable()}),Xi=r.z.object({type:r.z.literal(`local_shell_call`),id:r.z.string(),call_id:r.z.string(),action:r.z.object({type:r.z.literal(`exec`),command:r.z.array(r.z.string()),timeout_ms:r.z.number().optional(),user:r.z.string().optional(),working_directory:r.z.string().optional(),env:r.z.record(r.z.string(),r.z.string()).optional()})}),Zi=r.z.object({type:r.z.literal(`image_generation_call`),id:r.z.string(),result:r.z.string()}),Qi=20,$i=r.z.array(r.z.object({token:r.z.string(),logprob:r.z.number(),top_logprobs:r.z.array(r.z.object({token:r.z.string(),logprob:r.z.number()}))})),ea=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){let p=[],m=ka(this.modelId);i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`});let h=await Sr({provider:`openai`,providerOptions:l,schema:Aa}),{input:g,warnings:_}=await Ui({prompt:c,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:h?.store??!0,hasLocalShellTool:x(`openai.local_shell`)});p.push(..._);let v=h?.strictJsonSchema??!1,y=h?.include;function b(e){y=y==null?[e]:[...y,e]}function x(e){return u?.find(t=>t.type===`provider-defined`&&t.id===e)!=null}let S=typeof h?.logprobs==`number`?h?.logprobs:h?.logprobs===!0?Qi:void 0;S&&b(`message.output_text.logprobs`);let C=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;C&&b(`web_search_call.action.sources`),x(`openai.code_interpreter`)&&b(`code_interpreter_call.outputs`);let w={model:this.modelId,input:g,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||h?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:v,name:f.name??`response`,description:f.description,schema:f.schema}},...h?.textVerbosity&&{verbosity:h.textVerbosity}}},max_tool_calls:h?.maxToolCalls,metadata:h?.metadata,parallel_tool_calls:h?.parallelToolCalls,previous_response_id:h?.previousResponseId,store:h?.store,user:h?.user,instructions:h?.instructions,service_tier:h?.serviceTier,include:y,prompt_cache_key:h?.promptCacheKey,safety_identifier:h?.safetyIdentifier,top_logprobs:S,...m.isReasoningModel&&(h?.reasoningEffort!=null||h?.reasoningSummary!=null)&&{reasoning:{...h?.reasoningEffort!=null&&{effort:h.reasoningEffort},...h?.reasoningSummary!=null&&{summary:h.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:`auto`}};m.isReasoningModel?(w.temperature!=null&&(w.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),w.top_p!=null&&(w.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(h?.reasoningEffort!=null&&p.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),h?.reasoningSummary!=null&&p.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),h?.serviceTier===`flex`&&!m.supportsFlexProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete w.service_tier),h?.serviceTier===`priority`&&!m.supportsPriorityProcessing&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete w.service_tier);let{tools:T,toolChoice:E,toolWarnings:D}=Ki({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:T,tool_choice:E},warnings:[...p,...D]}}async doGenerate(e){var n,i;let{args:a,warnings:o,webSearchToolName:s}=await this.getArgs(e),c=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:l,value:u,rawValue:d}=await wr({url:c,headers:Kn(this.config.headers(),e.headers),body:a,failedResponseHandler:Ur,successfulResponseHandler:Mr(r.z.object({id:r.z.string(),created_at:r.z.number(),error:r.z.object({code:r.z.string(),message:r.z.string()}).nullish(),model:r.z.string(),output:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message`),role:r.z.literal(`assistant`),id:r.z.string(),content:r.z.array(r.z.object({type:r.z.literal(`output_text`),text:r.z.string(),logprobs:$i.nullish(),annotations:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`url_citation`),start_index:r.z.number(),end_index:r.z.number(),url:r.z.string(),title:r.z.string()}),r.z.object({type:r.z.literal(`file_citation`),file_id:r.z.string(),filename:r.z.string().nullish(),index:r.z.number().nullish(),start_index:r.z.number().nullish(),end_index:r.z.number().nullish(),quote:r.z.string().nullish()}),r.z.object({type:r.z.literal(`container_file_citation`)})]))}))}),qi,Ji,Yi,Zi,Xi,r.z.object({type:r.z.literal(`function_call`),call_id:r.z.string(),name:r.z.string(),arguments:r.z.string(),id:r.z.string()}),r.z.object({type:r.z.literal(`computer_call`),id:r.z.string(),status:r.z.string().optional()}),r.z.object({type:r.z.literal(`reasoning`),id:r.z.string(),encrypted_content:r.z.string().nullish(),summary:r.z.array(r.z.object({type:r.z.literal(`summary_text`),text:r.z.string()}))})])),service_tier:r.z.string().nullish(),incomplete_details:r.z.object({reason:r.z.string()}).nullish(),usage:ta})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(u.error)throw new t.APICallError({message:u.error.message,url:c,requestBodyValues:a,statusCode:400,responseHeaders:l,responseBody:d,isRetryable:!1});let f=[],p=[],m=!1;for(let t of u.output)switch(t.type){case`reasoning`:t.summary.length===0&&t.summary.push({type:`summary_text`,text:``});for(let e of t.summary)f.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:t.id,reasoningEncryptedContent:t.encrypted_content??null}}});break;case`image_generation_call`:f.push({type:`tool-call`,toolCallId:t.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:t.id,toolName:`image_generation`,result:{result:t.result},providerExecuted:!0});break;case`local_shell_call`:f.push({type:`tool-call`,toolCallId:t.call_id,toolName:`local_shell`,input:JSON.stringify({action:t.action}),providerMetadata:{openai:{itemId:t.id}}});break;case`message`:for(let r of t.content){e.providerOptions?.openai?.logprobs&&r.logprobs&&p.push(r.logprobs),f.push({type:`text`,text:r.text,providerMetadata:{openai:{itemId:t.id}}});for(let e of r.annotations)e.type===`url_citation`?f.push({type:`source`,sourceType:`url`,id:(n=this.config).generateId?.call(n)??Qn(),url:e.url,title:e.title}):e.type===`file_citation`&&f.push({type:`source`,sourceType:`document`,id:(i=this.config).generateId?.call(i)??Qn(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:m=!0,f.push({type:`tool-call`,toolCallId:t.call_id,toolName:t.name,input:t.arguments,providerMetadata:{openai:{itemId:t.id}}});break;case`web_search_call`:f.push({type:`tool-call`,toolCallId:t.id,toolName:s??`web_search`,input:JSON.stringify({action:t.action}),providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:t.id,toolName:s??`web_search`,result:{status:t.status},providerExecuted:!0});break;case`computer_call`:f.push({type:`tool-call`,toolCallId:t.id,toolName:`computer_use`,input:``,providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:t.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:t.status||`completed`},providerExecuted:!0});break;case`file_search_call`:f.push({type:`tool-call`,toolCallId:t.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:t.id,toolName:`file_search`,result:{queries:t.queries,results:t.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});break;case`code_interpreter_call`:f.push({type:`tool-call`,toolCallId:t.id,toolName:`code_interpreter`,input:JSON.stringify({code:t.code,containerId:t.container_id}),providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:t.id,toolName:`code_interpreter`,result:{outputs:t.outputs},providerExecuted:!0});break}let h={openai:{responseId:u.id}};return p.length>0&&(h.openai.logprobs=p),typeof u.service_tier==`string`&&(h.openai.serviceTier=u.service_tier),{content:f,finishReason:Gi({finishReason:u.incomplete_details?.reason,hasFunctionCall:m}),usage:{inputTokens:u.usage.input_tokens,outputTokens:u.usage.output_tokens,totalTokens:u.usage.input_tokens+u.usage.output_tokens,reasoningTokens:u.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:u.usage.input_tokens_details?.cached_tokens??void 0},request:{body:a},response:{id:u.id,timestamp:new Date(u.created_at*1e3),modelId:u.model,headers:l,body:d},providerMetadata:h,warnings:o}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await wr({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Ur,successfulResponseHandler:jr(ma),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let g=t.value;if(Ca(g))g.item.type===`function_call`?(d[g.output_index]={toolName:g.item.name,toolCallId:g.item.call_id},n.enqueue({type:`tool-input-start`,id:g.item.call_id,toolName:g.item.name})):g.item.type===`web_search_call`?(d[g.output_index]={toolName:r??`web_search`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:r??`web_search`})):g.item.type===`computer_call`?(d[g.output_index]={toolName:`computer_use`,toolCallId:g.item.id},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`computer_use`})):g.item.type===`code_interpreter_call`?(d[g.output_index]={toolName:`code_interpreter`,toolCallId:g.item.id,codeInterpreter:{containerId:g.item.container_id}},n.enqueue({type:`tool-input-start`,id:g.item.id,toolName:`code_interpreter`}),n.enqueue({type:`tool-input-delta`,id:g.item.id,delta:`{"containerId":"${g.item.container_id}","code":"`})):g.item.type===`file_search_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}):g.item.type===`image_generation_call`?n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}):g.item.type===`message`?n.enqueue({type:`text-start`,id:g.item.id,providerMetadata:{openai:{itemId:g.item.id}}}):wa(g)&&(p[g.item.id]={encryptedContent:g.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${g.item.id}:0`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}}));else if(ga(g)){if(g.item.type===`function_call`)d[g.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:g.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:g.item.name,input:g.item.arguments,providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`web_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`web_search`,input:JSON.stringify({action:g.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`web_search`,result:{status:g.item.status},providerExecuted:!0});else if(g.item.type===`computer_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:g.item.id}),n.enqueue({type:`tool-call`,toolCallId:g.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:g.item.status||`completed`},providerExecuted:!0});else if(g.item.type===`file_search_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`file_search`,result:{queries:g.item.queries,results:g.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null},providerExecuted:!0});else if(g.item.type===`code_interpreter_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`code_interpreter`,result:{outputs:g.item.outputs},providerExecuted:!0});else if(g.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:g.item.id,toolName:`image_generation`,result:{result:g.item.result},providerExecuted:!0});else if(g.item.type===`local_shell_call`)d[g.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:g.item.call_id,toolName:`local_shell`,input:JSON.stringify({action:{type:`exec`,command:g.item.action.command,timeoutMs:g.item.action.timeout_ms,user:g.item.action.user,workingDirectory:g.item.action.working_directory,env:g.item.action.env}}),providerMetadata:{openai:{itemId:g.item.id}}});else if(g.item.type===`message`)n.enqueue({type:`text-end`,id:g.item.id});else if(_a(g)){let e=p[g.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${g.item.id}:${t}`,providerMetadata:{openai:{itemId:g.item.id,reasoningEncryptedContent:g.item.encrypted_content??null}}});delete p[g.item.id]}}else if(ba(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(xa(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(g.delta).slice(1,-1)})}else if(Sa(g)){let e=d[g.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:`code_interpreter`,input:JSON.stringify({code:g.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else ya(g)?(u=g.response.id,n.enqueue({type:`response-metadata`,id:g.response.id,timestamp:new Date(g.response.created_at*1e3),modelId:g.response.model})):ha(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):Ea(g)?g.summary_index>0&&((i=p[g.item_id])==null||i.summaryParts.push(g.summary_index),n.enqueue({type:`reasoning-start`,id:`${g.item_id}:${g.summary_index}`,providerMetadata:{openai:{itemId:g.item_id,reasoningEncryptedContent:p[g.item_id]?.encryptedContent??null}}})):Da(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):va(g)?(s=Gi({finishReason:g.response.incomplete_details?.reason,hasFunctionCall:f}),c.inputTokens=g.response.usage.input_tokens,c.outputTokens=g.response.usage.output_tokens,c.totalTokens=g.response.usage.input_tokens+g.response.usage.output_tokens,c.reasoningTokens=g.response.usage.output_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=g.response.usage.input_tokens_details?.cached_tokens??void 0,typeof g.response.service_tier==`string`&&(m=g.response.service_tier)):Ta(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??Qn(),url:g.annotation.url,title:g.annotation.title}):g.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(h=o.config).generateId?.call(h)??Qn(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):Oa(g)&&n.enqueue({type:`error`,error:g})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},ta=r.z.object({input_tokens:r.z.number(),input_tokens_details:r.z.object({cached_tokens:r.z.number().nullish()}).nullish(),output_tokens:r.z.number(),output_tokens_details:r.z.object({reasoning_tokens:r.z.number().nullish()}).nullish()}),na=r.z.object({type:r.z.literal(`response.output_text.delta`),item_id:r.z.string(),delta:r.z.string(),logprobs:$i.nullish()}),ra=r.z.object({type:r.z.literal(`error`),code:r.z.string(),message:r.z.string(),param:r.z.string().nullish(),sequence_number:r.z.number()}),ia=r.z.object({type:r.z.enum([`response.completed`,`response.incomplete`]),response:r.z.object({incomplete_details:r.z.object({reason:r.z.string()}).nullish(),usage:ta,service_tier:r.z.string().nullish()})}),aa=r.z.object({type:r.z.literal(`response.created`),response:r.z.object({id:r.z.string(),created_at:r.z.number(),model:r.z.string(),service_tier:r.z.string().nullish()})}),oa=r.z.object({type:r.z.literal(`response.output_item.added`),output_index:r.z.number(),item:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message`),id:r.z.string()}),r.z.object({type:r.z.literal(`reasoning`),id:r.z.string(),encrypted_content:r.z.string().nullish()}),r.z.object({type:r.z.literal(`function_call`),id:r.z.string(),call_id:r.z.string(),name:r.z.string(),arguments:r.z.string()}),r.z.object({type:r.z.literal(`web_search_call`),id:r.z.string(),status:r.z.string(),action:r.z.object({type:r.z.literal(`search`),query:r.z.string().optional()}).nullish()}),r.z.object({type:r.z.literal(`computer_call`),id:r.z.string(),status:r.z.string()}),r.z.object({type:r.z.literal(`file_search_call`),id:r.z.string()}),r.z.object({type:r.z.literal(`image_generation_call`),id:r.z.string()}),r.z.object({type:r.z.literal(`code_interpreter_call`),id:r.z.string(),container_id:r.z.string(),code:r.z.string().nullable(),outputs:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`logs`),logs:r.z.string()}),r.z.object({type:r.z.literal(`image`),url:r.z.string()})])).nullable(),status:r.z.string()})])}),sa=r.z.object({type:r.z.literal(`response.output_item.done`),output_index:r.z.number(),item:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message`),id:r.z.string()}),r.z.object({type:r.z.literal(`reasoning`),id:r.z.string(),encrypted_content:r.z.string().nullish()}),r.z.object({type:r.z.literal(`function_call`),id:r.z.string(),call_id:r.z.string(),name:r.z.string(),arguments:r.z.string(),status:r.z.literal(`completed`)}),Yi,Zi,qi,Ji,Xi,r.z.object({type:r.z.literal(`computer_call`),id:r.z.string(),status:r.z.literal(`completed`)})])}),ca=r.z.object({type:r.z.literal(`response.function_call_arguments.delta`),item_id:r.z.string(),output_index:r.z.number(),delta:r.z.string()}),la=r.z.object({type:r.z.literal(`response.code_interpreter_call_code.delta`),item_id:r.z.string(),output_index:r.z.number(),delta:r.z.string()}),ua=r.z.object({type:r.z.literal(`response.code_interpreter_call_code.done`),item_id:r.z.string(),output_index:r.z.number(),code:r.z.string()}),da=r.z.object({type:r.z.literal(`response.output_text.annotation.added`),annotation:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`url_citation`),url:r.z.string(),title:r.z.string()}),r.z.object({type:r.z.literal(`file_citation`),file_id:r.z.string(),filename:r.z.string().nullish(),index:r.z.number().nullish(),start_index:r.z.number().nullish(),end_index:r.z.number().nullish(),quote:r.z.string().nullish()})])}),fa=r.z.object({type:r.z.literal(`response.reasoning_summary_part.added`),item_id:r.z.string(),summary_index:r.z.number()}),pa=r.z.object({type:r.z.literal(`response.reasoning_summary_text.delta`),item_id:r.z.string(),summary_index:r.z.number(),delta:r.z.string()}),ma=r.z.union([na,ia,aa,oa,sa,ca,la,ua,da,fa,pa,ra,r.z.object({type:r.z.string()}).loose()]);function ha(e){return e.type===`response.output_text.delta`}function ga(e){return e.type===`response.output_item.done`}function _a(e){return ga(e)&&e.item.type===`reasoning`}function va(e){return e.type===`response.completed`||e.type===`response.incomplete`}function ya(e){return e.type===`response.created`}function ba(e){return e.type===`response.function_call_arguments.delta`}function xa(e){return e.type===`response.code_interpreter_call_code.delta`}function Sa(e){return e.type===`response.code_interpreter_call_code.done`}function Ca(e){return e.type===`response.output_item.added`}function wa(e){return Ca(e)&&e.item.type===`reasoning`}function Ta(e){return e.type===`response.output_text.annotation.added`}function Ea(e){return e.type===`response.reasoning_summary_part.added`}function Da(e){return e.type===`response.reasoning_summary_text.delta`}function Oa(e){return e.type===`error`}function ka(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var Aa=r.z.object({include:r.z.array(r.z.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:r.z.string().nullish(),logprobs:r.z.union([r.z.boolean(),r.z.number().min(1).max(Qi)]).optional(),maxToolCalls:r.z.number().nullish(),metadata:r.z.any().nullish(),parallelToolCalls:r.z.boolean().nullish(),previousResponseId:r.z.string().nullish(),promptCacheKey:r.z.string().nullish(),reasoningEffort:r.z.string().nullish(),reasoningSummary:r.z.string().nullish(),safetyIdentifier:r.z.string().nullish(),serviceTier:r.z.enum([`auto`,`flex`,`priority`]).nullish(),store:r.z.boolean().nullish(),strictJsonSchema:r.z.boolean().nullish(),textVerbosity:r.z.enum([`low`,`medium`,`high`]).nullish(),user:r.z.string().nullish()}),ja=r.z.object({instructions:r.z.string().nullish(),speed:r.z.number().min(.25).max(4).default(1).nullish()}),Ma=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await Sr({provider:`openai`,providerOptions:o,schema:ja}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await wr({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),body:r,failedResponseHandler:Ur,successfulResponseHandler:Nr(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:a,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Na=r.z.object({include:r.z.array(r.z.string()).optional(),language:r.z.string().optional(),prompt:r.z.string().optional(),temperature:r.z.number().min(0).max(1).default(0).optional(),timestampGranularities:r.z.array(r.z.enum([`word`,`segment`])).default([`segment`]).optional()}),Pa={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},Fa=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await Sr({provider:`openai`,providerOptions:n,schema:Na}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([Rr(e)]);a.append(`model`,this.modelId);let s=ar(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:r,warnings:i}=await this.getArgs(e),{value:a,responseHeaders:o,rawValue:s}=await Tr({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),formData:r,failedResponseHandler:Ur,successfulResponseHandler:Mr(Ia),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in Pa?Pa[a.language]:void 0;return{text:a.text,segments:a.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??a.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:c,durationInSeconds:a.duration??void 0,warnings:i,response:{timestamp:n,modelId:this.modelId,headers:o,body:s}}}},Ia=r.z.object({text:r.z.string(),language:r.z.string().nullish(),duration:r.z.number().nullish(),words:r.z.array(r.z.object({word:r.z.string(),start:r.z.number(),end:r.z.number()})).nullish(),segments:r.z.array(r.z.object({id:r.z.number(),seek:r.z.number(),start:r.z.number(),end:r.z.number(),text:r.z.string(),tokens:r.z.array(r.z.number()),temperature:r.z.number(),avg_logprob:r.z.number(),compression_ratio:r.z.number(),no_speech_prob:r.z.number()})).nullish()}),La=`2.0.42`;function Ra(e={}){let t=Vr(ir({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>Xn({Authorization:`Bearer ${rr({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${La}`),i=i=>new Yr(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new ci(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new pi(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new _i(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new Fa(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new Ma(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),u=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return d(e)},d=i=>new ea(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),f=function(e){return u(e)};return f.languageModel=u,f.chat=i,f.completion=a,f.responses=d,f.embedding=o,f.textEmbedding=o,f.textEmbeddingModel=o,f.image=s,f.imageModel=s,f.transcription=c,f.transcriptionModel=c,f.speech=l,f.speechModel=l,f.tools=Vi,f}var za=Ra();function Ba(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function Va(e){return Object.fromEntries([...e.headers])}function Ha(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function Ua(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Wa(e,...t){let n=Ua(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ga=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},Ka=Ga();function qa(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Ja=[`fetch failed`,`failed to fetch`];function Ya({error:e,url:n,requestBodyValues:r}){if(qa(e))return e;if(e instanceof TypeError&&Ja.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var Xa=`3.0.10`,Za=/"__proto__"\s*:/,Qa=/"constructor"\s*:/;function $a(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Za.test(e)===!1&&Qa.test(e)===!1?t:eo(t)}function eo(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function to(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return $a(e)}finally{Error.stackTraceLimit=t}}var no=Symbol.for(`vercel.ai.validator`);function ro(e){return{[no]:!0,validate:e}}function io(e){return typeof e==`object`&&!!e&&no in e&&e[no]===!0&&`validate`in e}function ao(e){return io(e)?e:oo(e)}function oo(e){return ro(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function so({value:e,schema:n}){let r=await co({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function co({value:e,schema:n}){let r=ao(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function lo({text:e,schema:n}){try{let t=to(e);return n==null?t:so({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function uo({text:e,schema:n}){try{let t=to(e);return n==null?{success:!0,value:t,rawValue:t}:await co({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}var fo=()=>globalThis.fetch,po=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>mo({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),mo=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=fo()})=>{try{let c=await s(e,{method:`POST`,headers:Wa(n,`ai-sdk/provider-utils/${Xa}`,Ha()),body:r.content,signal:o}),l=Va(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw qa(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(qa(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw Ya({error:t,url:e,requestBodyValues:r.values})}},ho=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=Va(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await lo({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},go=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await uo({text:a,schema:e}),s=Va(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},_o=Symbol(`Let zodToJsonSchema decide on which parser to use`),vo=Symbol.for(`vercel.ai.schema`),{btoa:yo,atob:bo}=globalThis,xo=r.z.object({user:r.z.string().optional(),reasoningEffort:r.z.string().optional()}),So={errorSchema:r.z.object({error:r.z.object({message:r.z.string(),type:r.z.string().nullish(),param:r.z.any().nullish(),code:r.z.union([r.z.string(),r.z.number()]).nullish()})}),errorToMessage:e=>e.error.message},Co=r.z.object({prompt_tokens:r.z.number().nullish(),completion_tokens:r.z.number().nullish(),total_tokens:r.z.number().nullish(),prompt_tokens_details:r.z.object({cached_tokens:r.z.number().nullish()}).nullish(),completion_tokens_details:r.z.object({reasoning_tokens:r.z.number().nullish(),accepted_prediction_tokens:r.z.number().nullish(),rejected_prediction_tokens:r.z.number().nullish()}).nullish()}).nullish(),wo=r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({message:r.z.object({role:r.z.literal(`assistant`).nullish(),content:r.z.string().nullish(),reasoning_content:r.z.string().nullish(),reasoning:r.z.string().nullish(),tool_calls:r.z.array(r.z.object({id:r.z.string().nullish(),function:r.z.object({name:r.z.string(),arguments:r.z.string()})})).nullish()}),finish_reason:r.z.string().nullish()})),usage:Co}),To=r.z.object({echo:r.z.boolean().optional(),logitBias:r.z.record(r.z.string(),r.z.number()).optional(),suffix:r.z.string().optional(),user:r.z.string().optional()}),Eo=r.z.object({prompt_tokens:r.z.number(),completion_tokens:r.z.number(),total_tokens:r.z.number()}),Do=r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({text:r.z.string(),finish_reason:r.z.string()})),usage:Eo.nullish()}),Oo=r.z.object({dimensions:r.z.number().optional(),user:r.z.string().optional()}),ko=r.z.object({data:r.z.array(r.z.object({embedding:r.z.array(r.z.number())})),usage:r.z.object({prompt_tokens:r.z.number()}).nullish(),providerMetadata:r.z.record(r.z.string(),r.z.record(r.z.string(),r.z.any())).optional()}),Ao=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c;let l=[];r!=null&&l.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&l.push({type:`unsupported-setting`,setting:`seed`});let u=((c=this.config._internal)?.currentDate)?.call(c)??new Date,{value:d,responseHeaders:f}=await po({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Ba(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:ho(this.config.errorStructure??So),successfulResponseHandler:go(jo),abortSignal:s,fetch:this.config.fetch});return{images:d.data.map(e=>e.b64_json),warnings:l,response:{timestamp:u,modelId:this.modelId,headers:f}}}},jo=r.z.object({data:r.z.array(r.z.object({b64_json:r.z.string()}))});function Mo(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function No(e){return Object.fromEntries([...e.headers])}function Po(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function Fo(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Io(e,...t){let n=Fo(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Lo=({prefix:e,size:n=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,t=Array(n);for(let i=0;i<n;i++)t[i]=r[Math.random()*e|0];return t.join(``)};if(e==null)return a;if(r.includes(i))throw new t.InvalidArgumentError({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`},Ro=Lo();function zo(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Bo=[`fetch failed`,`failed to fetch`];function Vo({error:e,url:n,requestBodyValues:r}){if(zo(e))return e;if(e instanceof TypeError&&Bo.includes(e.message.toLowerCase())){let i=e.cause;if(i!=null)return new t.APICallError({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return e}var Ho=`3.0.10`;function Uo({apiKey:e,environmentVariableName:n,apiKeyParameterName:r=`apiKey`,description:i}){if(typeof e==`string`)return e;if(e!=null)throw new t.LoadAPIKeyError({message:`${i} API key must be a string.`});if(typeof process>`u`)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[n],e==null)throw new t.LoadAPIKeyError({message:`${i} API key is missing. Pass it using the '${r}' parameter or the ${n} environment variable.`});if(typeof e!=`string`)throw new t.LoadAPIKeyError({message:`${i} API key must be a string. The value of the ${n} environment variable is not a string.`});return e}var Wo=/"__proto__"\s*:/,Go=/"constructor"\s*:/;function Ko(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Wo.test(e)===!1&&Go.test(e)===!1?t:qo(t)}function qo(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Jo(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Ko(e)}finally{Error.stackTraceLimit=t}}var Yo=Symbol.for(`vercel.ai.validator`);function Xo(e){return{[Yo]:!0,validate:e}}function Zo(e){return typeof e==`object`&&!!e&&Yo in e&&e[Yo]===!0&&`validate`in e}function Qo(e){return Zo(e)?e:$o(e)}function $o(e){return Xo(async n=>{let r=await e[`~standard`].validate(n);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new t.TypeValidationError({value:n,cause:r.issues})}})}async function es({value:e,schema:n}){let r=await ts({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function ts({value:e,schema:n}){let r=Qo(n);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:t.TypeValidationError.wrap({value:e,cause:n}),rawValue:e}}}async function ns({text:e,schema:n}){try{let t=Jo(e);return n==null?t:es({value:t,schema:n})}catch(n){throw t.JSONParseError.isInstance(n)||t.TypeValidationError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n})}}async function rs({text:e,schema:n}){try{let t=Jo(e);return n==null?{success:!0,value:t,rawValue:t}:await ts({value:t,schema:n})}catch(n){return{success:!1,error:t.JSONParseError.isInstance(n)?n:new t.JSONParseError({text:e,cause:n}),rawValue:void 0}}}function os({stream:e,schema:n}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform({data:e},t){e!==`[DONE]`&&t.enqueue(await rs({text:e,schema:n}))}}))}async function ss({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await ts({value:n[e],schema:r});if(!i.success)throw new t.InvalidArgumentError({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var cs=()=>globalThis.fetch,ls=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>us({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),us=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=cs()})=>{try{let c=await s(e,{method:`POST`,headers:Io(n,`ai-sdk/provider-utils/${Ho}`,Po()),body:r.content,signal:o}),l=No(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw zo(n)||t.APICallError.isInstance(n)?n:new t.APICallError({message:`Failed to process error response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:e,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(zo(n)||t.APICallError.isInstance(n))?n:new t.APICallError({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(t){throw Vo({error:t,url:e,requestBodyValues:r.values})}},ds=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=No(i);if(s.trim()===``)return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await ns({text:s,schema:e});return{responseHeaders:c,value:new t.APICallError({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new t.APICallError({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},fs=e=>async({response:n})=>{let r=No(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:os({stream:n.body,schema:e})}},ps=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await rs({text:a,schema:e}),s=No(n);if(!o.success)throw new t.APICallError({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},ms=Symbol(`Let zodToJsonSchema decide on which parser to use`),hs=Symbol.for(`vercel.ai.schema`),{btoa:gs,atob:_s}=globalThis;function vs(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return gs(t)}function ys(e){return e instanceof Uint8Array?vs(e):e}function bs(e){return e?.replace(/\/$/,``)}function xs(e){let n=[],r=[];for(let{role:r,content:i}of e)switch(r){case`system`:n.push({role:`system`,content:i});break;case`user`:if(i.length===1&&i[0].type===`text`){n.push({role:`user`,content:i[0].text});break}n.push({role:`user`,content:i.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${ys(e.data)}`}}}else throw new t.UnsupportedFunctionalityError({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of i)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:JSON.stringify(n.input)}});break}n.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of i){let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function Ss({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Cs(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var ws=r.z.object({type:r.z.literal(`web`),country:r.z.string().length(2).optional(),excludedWebsites:r.z.array(r.z.string()).max(5).optional(),allowedWebsites:r.z.array(r.z.string()).max(5).optional(),safeSearch:r.z.boolean().optional()}),Ts=r.z.object({type:r.z.literal(`x`),excludedXHandles:r.z.array(r.z.string()).optional(),includedXHandles:r.z.array(r.z.string()).optional(),postFavoriteCount:r.z.number().int().optional(),postViewCount:r.z.number().int().optional(),xHandles:r.z.array(r.z.string()).optional()}),Es=r.z.object({type:r.z.literal(`news`),country:r.z.string().length(2).optional(),excludedWebsites:r.z.array(r.z.string()).max(5).optional(),safeSearch:r.z.boolean().optional()}),Ds=r.z.object({type:r.z.literal(`rss`),links:r.z.array(r.z.string().url()).max(1)}),Os=r.z.discriminatedUnion(`type`,[ws,Ts,Es,Ds]),ks=r.z.object({reasoningEffort:r.z.enum([`low`,`high`]).optional(),searchParameters:r.z.object({mode:r.z.enum([`off`,`auto`,`on`]),returnCitations:r.z.boolean().optional(),fromDate:r.z.string().optional(),toDate:r.z.string().optional(),maxSearchResults:r.z.number().min(1).max(50).optional(),sources:r.z.array(Os).optional()}).optional()}),As=r.z.object({error:r.z.object({message:r.z.string(),type:r.z.string().nullish(),param:r.z.any().nullish(),code:r.z.union([r.z.string(),r.z.number()]).nullish()})}),js=ds({errorSchema:As,errorToMessage:e=>e.error.message});function Ms({tools:e,toolChoice:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)t.type===`provider-defined`?r.push({type:`unsupported-tool`,tool:t}):i.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(n==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=n.type;switch(a){case`auto`:case`none`:return{tools:i,toolChoice:a,toolWarnings:r};case`required`:return{tools:i,toolChoice:`required`,toolWarnings:r};case`tool`:return{tools:i,toolChoice:{type:`function`,function:{name:n.toolName}},toolWarnings:r};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${a}`})}}var Ns=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){let p=[],m=await ss({provider:`xai`,providerOptions:u,schema:ks})??{};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&p.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:h,warnings:g}=xs(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=Ms({tools:d,toolChoice:f});return p.push(...y),{args:{model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:m.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:l.name??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:m.searchParameters?{mode:m.searchParameters.mode,return_citations:m.searchParameters.returnCitations,from_date:m.searchParameters.fromDate,to_date:m.searchParameters.toDate,max_search_results:m.searchParameters.maxSearchResults,sources:m.searchParameters.sources?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{excluded_x_handles:e.excludedXHandles,included_x_handles:e.includedXHandles??e.xHandles,post_favorite_count:e.postFavoriteCount,post_view_count:e.postViewCount},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:h,tools:_,tool_choice:v},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:a}=await ls({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:Mo(this.config.headers(),e.headers),body:t,failedResponseHandler:js,successfulResponseHandler:ps(Fs),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[];if(o.message.content!=null&&o.message.content.length>0){let e=o.message.content,n=t.messages[t.messages.length-1];n?.role===`assistant`&&e===n.content&&(e=``),e.length>0&&s.push({type:`text`,text:e})}if(o.message.reasoning_content!=null&&o.message.reasoning_content.length>0&&s.push({type:`reasoning`,text:o.message.reasoning_content}),o.message.tool_calls!=null)for(let e of o.message.tool_calls)s.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(i.citations!=null)for(let e of i.citations)s.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:s,finishReason:Cs(o.finish_reason),usage:{inputTokens:i.usage.prompt_tokens,outputTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens,reasoningTokens:i.usage.completion_tokens_details?.reasoning_tokens??void 0},request:{body:t},response:{...Ss(i),headers:r,body:a},warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await ls({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:Mo(this.config.headers(),e.headers),body:r,failedResponseHandler:js,successfulResponseHandler:fs(Is),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},c=!0,l={},u={},d=this;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let i=t.value;if(c&&=(n.enqueue({type:`response-metadata`,...Ss(i)}),!1),i.citations!=null)for(let e of i.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});i.usage!=null&&(s.inputTokens=i.usage.prompt_tokens,s.outputTokens=i.usage.completion_tokens,s.totalTokens=i.usage.total_tokens,s.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0);let a=i.choices[0];if(a?.finish_reason!=null&&(o=Cs(a.finish_reason)),a?.delta==null)return;let f=a.delta,p=a.index;if(f.content!=null&&f.content.length>0){let e=f.content,t=r.messages[r.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let a=`text-${i.id||p}`;l[a]??(l[a]={type:`text`},n.enqueue({type:`text-start`,id:a})),n.enqueue({type:`text-delta`,id:a,delta:e})}if(f.reasoning_content!=null&&f.reasoning_content.length>0){let e=`reasoning-${i.id||p}`;if(u[e]===f.reasoning_content)return;u[e]=f.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:f.reasoning_content})}if(f.tool_calls!=null)for(let e of f.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:o,usage:s})}})),request:{body:r},response:{headers:i}}}},Ps=r.z.object({prompt_tokens:r.z.number(),completion_tokens:r.z.number(),total_tokens:r.z.number(),completion_tokens_details:r.z.object({reasoning_tokens:r.z.number().nullish()}).nullish()}),Fs=r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({message:r.z.object({role:r.z.literal(`assistant`),content:r.z.string().nullish(),reasoning_content:r.z.string().nullish(),tool_calls:r.z.array(r.z.object({id:r.z.string(),type:r.z.literal(`function`),function:r.z.object({name:r.z.string(),arguments:r.z.string()})})).nullish()}),index:r.z.number(),finish_reason:r.z.string().nullish()})),object:r.z.literal(`chat.completion`),usage:Ps,citations:r.z.array(r.z.string().url()).nullish()}),Is=r.z.object({id:r.z.string().nullish(),created:r.z.number().nullish(),model:r.z.string().nullish(),choices:r.z.array(r.z.object({delta:r.z.object({role:r.z.enum([`assistant`]).optional(),content:r.z.string().nullish(),reasoning_content:r.z.string().nullish(),tool_calls:r.z.array(r.z.object({id:r.z.string(),type:r.z.literal(`function`),function:r.z.object({name:r.z.string(),arguments:r.z.string()})})).nullish()}),finish_reason:r.z.string().nullish(),index:r.z.number()})),usage:Ps.nullish(),citations:r.z.array(r.z.string().url()).nullish()}),Ls=`2.0.23`,Rs={errorSchema:As,errorToMessage:e=>e.error.message};function zs(e={}){let n=bs(e.baseURL??`https://api.x.ai/v1`),r=()=>Io({Authorization:`Bearer ${Uo({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${Ls}`),i=t=>new Ns(t,{provider:`xai.chat`,baseURL:n,headers:r,generateId:Ro,fetch:e.fetch}),a=t=>new Ao(t,{provider:`xai.image`,url:({path:e})=>`${n}${e}`,headers:r,fetch:e.fetch,errorStructure:Rs}),o=e=>i(e);return o.languageModel=i,o.chat=i,o.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},o.imageModel=a,o.image=a,o}var Bs=zs();function Vs(e){if(!e.body)throw Error(`Response body is required`);let n=e.headers.get(t.StreamResponseFormatHeader);if(!n||n===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new t.EventSourceParserStream).pipeThrough(new TransformStream({async transform(e,t){if(e.data!==`[DONE]`)try{let n=JSON.parse(e.data);t.enqueue(n)}catch(e){t.error(e);return}}}));let r=e=>(0,m.streamText)({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(n){case`openai-chat`:return r(Ra({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return r(Ra({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return r(gt({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return r(Wn({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return r(zs({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${n}`)}}function Hs(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var Us=class{_lockP=null;async lock(){let e=this._lockP,{promise:t,resolve:n}=Hs();return this._lockP=t,await e,n}withLock(e){return Gs(this.lock(),e)}},Ws=class{_lock=new Us;_writeP=null;_readP=[];read(){return this._lock.withLock(async()=>{await this._writeP;let{promise:e,resolve:t}=Hs();return this._readP.push(e),t})}withRead(e){return Gs(this.read(),e)}async write(){return await this._lock.withLock(async()=>{await this._writeP,await Promise.all(this._readP);let{promise:e,resolve:t}=Hs();return this._writeP=e,this._readP=[],t})}withWrite(e){return Gs(this.write(),e)}};async function Gs(e,t){let n=await e;try{return await t()}finally{n()}}var Ks=class{constructor(e){this.onRelease=e}[Symbol.dispose](){this.onRelease()}},qs=class{constructor(e){this.onRelease=e}[Symbol.dispose](){this.onRelease()}},Js=class{_lock=new Ws;async read(){let e=await this._lock.read();return new Ks(e)}async write(){let e=await this._lock.write();return new qs(e)}},Ys=class{baseUrl;client;agentLock;constructor(e){this.client=t.hc(e.baseUrl),this.baseUrl=e.baseUrl,this.agentLock=new Js}async chat(e,t){let n=await this.client._agent.chat.$post({json:e},{headers:t?.headers,init:{signal:t?.signal}});return n.ok||await this.handleError(n),Vs(n)}async capabilities(){let e=await this.client._agent.capabilities.$get();return e.ok||await this.handleError(e),e.json()}async ui(e,t){let n=await this.client._agent.ui.$get({query:e.selectedOptions?{selected_options:JSON.stringify(e.selectedOptions)}:{}},{init:{signal:t?.signal}});if(!n.ok||n.status!==200){if(n.status===404)return;await this.handleError(n)}return n.json()}async health(){let e=await this.client._agent.health.$get();e.ok||await this.handleError(e)}async handleError(e){let t;try{t=await e.text()}catch{}if(t){let n;try{n=JSON.parse(t)}catch{}throw n?Error(n.error):Error(`Failed (${e.status}): ${t}`)}throw Error(`Failed (${e.status}): ${e.statusText}`)}};function Xs(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}function Zs(e){let[n,r]=(0,_.useState)(void 0),[i,a]=(0,_.useState)([]),[o,s]=(0,_.useState)(void 0),[c,l]=(0,_.useState)(e.buildResult),[u,d]=(0,_.useState)(e.env),[f,p]=(0,_.useState)(e.apiServerUrl),[m,h]=(0,_.useState)(void 0);return(0,_.useEffect)(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),(0,_.useEffect)(()=>{if(!c||`error`in c){r(void 0),a([]),s(void 0),h(void 0);return}let e=new AbortController,n=!1;s(void 0),r(void 0),h(void 0);let i;return(async()=>{let n=await Qs(),o=(0,g.spawn)(`node`,[`--no-deprecation`,c.entry],{stdio:`pipe`,env:{...process.env,...u,[t.APIServerURLEnvironmentVariable]:f,PORT:n.toString(),HOST:`127.0.0.1`},detached:!1}),s=()=>{try{o.kill()}catch{}};process.once(`exit`,s),process.once(`SIGINT`,s),process.once(`SIGTERM`,s),process.once(`uncaughtException`,s),e.signal.addEventListener(`abort`,()=>{process.off(`exit`,s),process.off(`SIGINT`,s),process.off(`SIGTERM`,s),process.off(`uncaughtException`,s),s()});let l=!1;o.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!l&&t.startsWith(`Agent server listening on`)||(l||console.log(`stdout: ${t}`),t.length&&a(e=>[...e,{level:`log`,message:t}]))}),o.stderr.on(`data`,e=>{l||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&a(e=>[...e,{level:`error`,message:t}])}),o.on(`error`,t=>{e.abort(t)}),o.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let d=new Ys({baseUrl:`http://127.0.0.1:${n}`});for(i=d.agentLock;!e.signal.aborted;){try{await d.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;l=!0;let p=await d.capabilities();h(p),r(d)})().catch(e=>{n||s(e instanceof Error?e:Error(String(e)))}),()=>{n=!0,(async()=>{try{var t=Xs();t.u(await i?.write()),e.abort()}catch(e){t.e=e}finally{t.d()}})()}},[c,u,f]),(0,_.useMemo)(()=>({agent:n,logs:i,error:o,capabilities:m}),[n,i,o,m])}async function Qs(){let e=(0,d.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var $s=Object.getOwnPropertyNames,W=(e,t)=>function(){return t||(0,e[$s(e)[0]])((t={exports:{}}).exports,t),t.exports},G=(0,v.createRequire)(require(`url`).pathToFileURL(__filename).href);y.z.object({email:y.z.string().email(),password:y.z.string().min(8)}),y.z.object({email:y.z.string().email(),code:y.z.string()}),y.z.object({email:y.z.string().email(),password:y.z.string().min(8)});var ec=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}},tc=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function nc(e){}function rc(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=nc,onError:n=nc,onRetry:r=nc,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=ic(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
16
|
+
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new tc(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new tc(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
17
|
+
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function ic(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
18
18
|
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
19
|
-
`&&r++}}return[t,n]}var
|
|
20
|
-
Error message: ${
|
|
21
|
-
Error message: ${rc(t)}`,cause:t}),this[_c]=!0,this.value=e}static isInstance(e){return nc.hasMarker(e,hc)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};_c=gc;var yc=vc,bc=({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new cc({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`};bc();var xc=/"__proto__"\s*:/,Sc=/"constructor"\s*:/;function Cc(e){let t=JSON.parse(e);return typeof t!=`object`||!t||xc.test(e)===!1&&Sc.test(e)===!1?t:wc(t)}function wc(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Tc(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Cc(e)}finally{Error.stackTraceLimit=t}}var Ec=Symbol.for(`vercel.ai.validator`);function Dc(e){return{[Ec]:!0,validate:e}}function Oc(e){return typeof e==`object`&&!!e&&Ec in e&&e[Ec]===!0&&`validate`in e}function kc(e){return Oc(e)?e:Ac(e)}function Ac(e){return Dc(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new yc({value:t,cause:n.issues})}})}async function jc({value:e,schema:t}){let n=kc(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:yc.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:yc.wrap({value:e,cause:t}),rawValue:e}}}async function Mc({text:e,schema:t}){try{let n=Tc(e);return t==null?{success:!0,value:n,rawValue:n}:await jc({value:n,schema:t})}catch(t){return{success:!1,error:pc.isInstance(t)?t:new pc({text:e,cause:t}),rawValue:void 0}}}var{btoa:Nc,atob:Pc}=globalThis;function Fc(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}const K=async(e,t)=>{if(e.status!==t){let n=await e.text();try{let r=JSON.parse(n);throw r.message?Error(r.message,{cause:r.details}):Error(`Expected status ${t}, got ${e.status}: ${n}`)}catch{throw Error(`Expected status ${t}, got ${e.status}: ${n}`)}}},Ic=y.z.object({per_page:y.z.number().int().positive().max(100).default(10).optional(),page:y.z.number().int().nonnegative().default(0).optional()}),Lc=e=>y.z.object({has_more:y.z.boolean(),items:y.z.array(e)}),Rc=y.z.object({limit:y.z.number().int().positive().max(100).default(10).optional(),cursor:y.z.string().optional()}),zc=e=>y.z.object({next_cursor:y.z.string().nullable(),items:y.z.array(e)}),Bc=y.z.any().nullable().refine(e=>e?Object.keys(e).length<=16:!0,{message:`Metadata must contain at most 16 keys`}),Vc=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,Hc=(e,t)=>{let n=new Zs;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(n.writable).catch(e=>{}),Uc(n.readable,t)},Uc=(e,t)=>{let n=e.pipeThrough(new TransformStream({async transform(e,n){let r=await Mc({text:e.data});if(!r.success){n.error(r.error);return}let i=t.safeParse({event:e.event,data:r.value});if(!i.success){n.error(i.error);return}n.enqueue(i.data)}}));return Fc(n)},Wc=y.z.union([y.z.object({agent_id:y.z.uuid(),deployment_id:y.z.uuid()}),y.z.object({agent_id:y.z.uuid(),deployment_number:y.z.number().int().positive()})]),Gc=y.z.object({agent_id:y.z.uuid(),deployment_id:y.z.uuid()}),Kc=y.z.object({path:y.z.string(),id:y.z.uuid()}),qc=Kc.or(y.z.object({path:y.z.string(),data:y.z.string().max(1024*1024*5)})),Jc=y.z.enum([`production`,`preview`]),Yc=y.z.object({agent_id:y.z.uuid(),output_files:y.z.array(qc).optional(),source_files:y.z.array(qc).optional(),files:y.z.array(qc).optional(),target:Jc,entrypoint:y.z.string().optional(),message:y.z.string().max(128).optional()}).transform(e=>e.files&&!e.output_files?{...e,output_files:e.files,files:void 0}:e),Xc=y.z.object({id:y.z.uuid(),number:y.z.number().int().positive(),created_at:y.z.iso.datetime(),updated_at:y.z.iso.datetime(),created_by:y.z.uuid().nullable(),created_from:y.z.enum([`cli`]),agent_id:y.z.uuid(),source_files:y.z.array(Kc),output_files:y.z.array(Kc),status:y.z.enum([`success`,`failed`,`deploying`,`pending`]),target:Jc,error_message:y.z.string().nullable(),user_message:y.z.string().nullable(),platform:y.z.enum([`lambda`]),platform_memory_mb:y.z.number().int().positive(),platform_region:y.z.string().nullable()}),Zc=y.z.object({id:y.z.uuid(),created_at:y.z.string().datetime(),updated_at:y.z.string().datetime(),agent_id:y.z.uuid(),deployment_id:y.z.uuid(),level:y.z.enum([`log`,`info`,`warning`,`error`]),message:y.z.string()}),Qc=Ic.extend({agent_id:y.z.uuid(),order:y.z.enum([`asc`,`desc`]).default(`asc`).optional()}),$c=Lc(Xc);var el=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),e.order&&t.set(`order`,e.order);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t;t=`deployment_id`in e?e.deployment_id:e.deployment_number.toString();let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments/${t}`);return await K(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/deployments`,JSON.stringify(e));return await K(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);await K(t,200)}};y.z.object({agent_id:y.z.uuid(),target:Jc.array().optional()}),y.z.object({id:y.z.uuid(),created_at:y.z.date(),updated_at:y.z.date(),created_by:y.z.uuid(),updated_by:y.z.uuid(),key:y.z.string(),value:y.z.string().nullable(),secret:y.z.boolean(),target:Jc.array()});const tl=y.z.object({key:y.z.string(),value:y.z.string(),secret:y.z.boolean(),target:Jc.array().optional(),upsert:y.z.boolean().optional()});tl.extend({agent_id:y.z.uuid()}),y.z.object({agent_id:y.z.uuid(),id:y.z.uuid()}),y.z.object({agent_id:y.z.uuid(),id:y.z.uuid(),key:y.z.string().optional(),value:y.z.string().optional(),secret:y.z.boolean().optional(),target:Jc.array().default([`preview`,`production`]).optional()});var nl=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;if(e.target)for(let n of e.target)t.append(`target`,n);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/env?${t.toString()}`);return await K(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/env`,JSON.stringify(e));return await K(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/env/${e.id}`);await K(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/agents/${e.agent_id}/env/${e.id}`,JSON.stringify(e));return await K(t,200),t.json()}};const rl=y.z.object({id:y.z.string(),agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid(),received_at:y.z.date(),request_method:y.z.string(),request_handler_location:y.z.string().nullable(),duration_ms:y.z.number().nullable(),error:y.z.string().nullable(),response_status:y.z.number().nullable()});rl.extend({request_headers:y.z.record(y.z.string(),y.z.string()),request_headers_redacted:y.z.boolean(),request_body:y.z.string().nullable(),request_body_redacted:y.z.boolean(),response_headers:y.z.record(y.z.string(),y.z.string()).nullable(),response_headers_redacted:y.z.boolean(),response_body:y.z.string().nullable(),response_body_redacted:y.z.boolean()}),Rc.extend({agent_id:y.z.string(),agent_deployment_id:y.z.number().optional()}),zc(rl);var il=class{constructor(e){this.client=e}async log(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs/${e.webhook_id}`);return await K(t,200),t.json()}async logs(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id.toString()),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs?${t.toString()}`);return await K(n,200),n.json()}};Rc.extend({agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid().optional()}),y.z.object({agent_id:y.z.uuid(),run_id:y.z.uuid()});var al=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs/${e.run_id}`);return await K(t,200),t.json()}};const ol=y.z.enum([`streaming`,`stalled`,`completed`,`interrupted`,`error`]),sl=y.z.enum([`tool_call`,`queued_message`]),cl=y.z.object({id:y.z.uuid(),number:y.z.number().int().positive(),chat_id:y.z.uuid(),chat_run_id:y.z.uuid(),agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid(),started_at:y.z.string().datetime(),status:ol,error:y.z.string().nullable(),continuation_reason:sl.nullable(),response_status:y.z.number().nullable(),response_message_id:y.z.uuid().nullable(),time_to_first_token_micros:y.z.number().nullable()});cl.extend({heartbeat_at:y.z.date(),completed_at:y.z.date().nullable(),interrupted_at:y.z.date().nullable(),first_message_id:y.z.uuid().nullable(),last_message_id:y.z.uuid().nullable(),response_headers:y.z.record(y.z.string(),y.z.string()).nullable(),response_headers_redacted:y.z.boolean(),response_body:y.z.string().nullable(),response_body_redacted:y.z.boolean(),usage_model:y.z.string().nullable(),usage_total_input_tokens:y.z.number().nullable(),usage_total_output_tokens:y.z.number().nullable(),usage_total_tokens:y.z.number().nullable(),usage_total_cached_input_tokens:y.z.number().nullable(),usage_cost_usd:y.z.number().nullable()}),Rc.extend({chat_id:y.z.uuid(),run_id:y.z.uuid().optional()}),zc(cl);var ll=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id);let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps/${e.step_id}`);return await K(t,200),t.json()}};Rc.extend({agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid().optional(),chat_id:y.z.uuid().optional(),run_id:y.z.uuid().optional(),status:ol.optional()}),zc(cl);var ul=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id),e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.chat_id&&t.set(`chat_id`,e.chat_id),e.status&&t.set(`status`,e.status);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps/${e.step_id}`);return await K(t,200),t.json()}};const dl=y.z.object({type:y.z.literal(`eq`),key:y.z.string(),value:y.z.string()}),fl=y.z.object({type:y.z.literal(`and`),get filters(){return y.z.array(y.z.union([dl,fl]))}}),pl=y.z.object({start_time:y.z.iso.datetime().pipe(y.z.coerce.date()),end_time:y.z.iso.datetime().pipe(y.z.coerce.date()),filters:y.z.string().transform(e=>JSON.parse(e)).pipe(fl),limit:y.z.string().pipe(y.z.coerce.number().min(1).max(1e4)).optional()});var ml=class{constructor(e){this.client=e}async spans(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),t.set(`filters`,JSON.stringify(e.filters)),e.limit!==void 0&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/traces/spans?${t.toString()}`);return await K(n,200),await n.json()}};y.default.object({start_time:y.default.iso.datetime().pipe(y.default.coerce.date()),end_time:y.default.iso.datetime().pipe(y.default.coerce.date()),message_pattern:y.default.string().optional(),filters:y.default.string().transform(e=>JSON.parse(e)).pipe(fl).optional(),limit:y.default.string().pipe(y.default.coerce.number().min(1).max(1e4)).optional()});const hl=y.default.object({timestamp:y.default.iso.datetime().pipe(y.default.coerce.date()),message:y.default.string(),level:y.default.enum([`info`,`error`,`warn`])}),gl=y.default.object({logs:y.default.array(hl)});var _l=class{constructor(e){this.client=e}async logs(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),e.limit&&t.set(`limit`,e.limit.toString()),e.message_pattern&&t.set(`message_pattern`,e.message_pattern),e.filters&&t.set(`filters`,JSON.stringify(e.filters));let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/logs?${t.toString()}`);await K(n,200);let r=await n.json();return gl.parse(r)}};const vl=y.z.enum([`private`,`public`]),yl=y.z.object({organization_id:y.z.uuid(),name:y.z.string().regex(Vc),description:y.z.string().optional(),visibility:vl.default(`private`).optional(),source_files:y.z.array(qc).optional(),output_files:y.z.array(qc).optional(),entrypoint:y.z.string().optional(),env:y.z.array(tl).optional(),request_id:y.z.uuid().optional()}),bl=y.z.object({id:y.z.uuid(),organization_id:y.z.uuid(),created_at:y.z.iso.datetime(),updated_at:y.z.iso.datetime(),created_by:y.z.uuid(),name:y.z.string().regex(Vc),description:y.z.string().nullable(),avatar_url:y.z.string().nullable(),visibility:vl,active_deployment_id:y.z.uuid().nullable(),pinned:y.z.boolean().default(!1),request_url:y.z.url().nullable().describe(`The URL for the agent requests. Only visible to owners.`)}),xl=y.z.object({id:y.z.uuid(),name:y.z.string().regex(Vc).optional(),description:y.z.string().optional(),visibility:vl.optional(),active_deployment_id:y.z.uuid().optional(),avatar_file_id:y.z.uuid().nullable().optional()}),Sl=Ic.extend({organization_id:y.z.uuid().optional(),pinned:y.z.boolean().optional()}),Cl=Lc(bl),wl=y.z.object({agent_id:y.z.uuid(),input:y.z.string(),caret:y.z.number().optional(),selection:y.z.tuple([y.z.number(),y.z.number()]).optional(),chat_id:y.z.uuid().optional(),agent_deployment_id:y.z.uuid().optional()}),Tl=y.z.object({text:y.z.string(),caret:y.z.number().optional(),selection:y.z.tuple([y.z.number(),y.z.number()]).optional()}),El=y.z.object({agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid().optional(),selected:y.z.record(y.z.string(),y.z.string()).optional()}),Dl=y.z.object({agent_id:y.z.uuid(),start_time:y.z.iso.datetime().pipe(y.z.coerce.date()),end_time:y.z.iso.datetime().pipe(y.z.coerce.date())}),Ol=y.z.object({seconds:y.z.string()});var kl=class{constructor(e){this.client=e,this.deployments=new el(e),this.env=new nl(e),this.webhook=new il(e),this.runs=new al(e),this.steps=new ul(e),this.logs=new _l(e),this.traces=new ml(e)}async create(e){let t=await this.client.request(`POST`,`/api/agents`,JSON.stringify(e));return await K(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/agents/${e.id}`,JSON.stringify(e));return await K(t,200),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e}`);return await K(t,200),t.json()}async list(e){let t=new URLSearchParams;e.organization_id&&t.set(`organization_id`,e.organization_id),e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),typeof e.pinned==`boolean`&&t.set(`pinned`,e.pinned.toString());let n=await this.client.request(`GET`,`/api/agents?${t.toString()}`);return await K(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}`);await K(t,204)}async completions(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/completions`,JSON.stringify(e));if(await K(t,200),t.headers.get(`content-type`)===`application/json`){let e=await t.json();return Fc(new ReadableStream({start(t){t.enqueue(e),t.close()}}))}return Hc(t,Tl)}async uiOptions(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.selected&&t.set(`selected`,JSON.stringify(e.selected));let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/ui-options?${t.toString()}`);return await K(n,200),n.json()}async pin(e){let t=await this.client.request(`POST`,`/api/agents/${e}/pin`);await K(t,204)}async unpin(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}/pin`);await K(t,204)}async getRuntimeUsage(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString());let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/usage/runtime?${t.toString()}`);return await K(n,200),n.json()}},Al=class{constructor(e){this.client=e}async upload(e){let t=new FormData;t.append(`file`,e);let n=await this.client.request(`POST`,`/api/files`,t);return await K(n,201),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/files/${e}`);return await K(t,200),new File([await t.blob()],``)}};const jl=y.z.enum([`owner`,`admin`,`billing_admin`,`member`]),Ml=y.z.object({user_id:y.z.uuid(),organization_id:y.z.uuid(),role:jl,created_at:y.z.date(),updated_at:y.z.date()}),Nl=y.z.object({id:y.z.uuid(),created_at:y.z.date(),updated_at:y.z.date(),display_name:y.z.string().nullable(),email:y.z.email(),avatar_url:y.z.url().nullable(),username:y.z.string()}),Pl=Ml.extend({user:Nl});Ic.extend({organization_id:y.z.uuid()}),Lc(Pl),y.z.object({organization_id:y.z.uuid(),user_id:y.z.uuid()}),y.z.object({role:y.z.enum([`owner`,`admin`,`member`,`billing_admin`]).optional()}).extend({organization_id:y.z.uuid(),user_id:y.z.uuid()});var Fl=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.per_page&&t.set(`per_page`,e.per_page.toString()),e.page&&t.set(`page`,e.page.toString());let n=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);return await K(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);await K(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/organizations/${e.organization_id}/members/${e.user_id}`,JSON.stringify({role:e.role}));return await K(t,200),t.json()}},Il=class{constructor(e){this.client=e}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/agents/${e.agent_name}`);return await K(t,200),t.json()}};const Ll=y.z.object({id:y.z.uuid(),name:y.z.string(),created_at:y.z.date(),updated_at:y.z.date(),membership:Ml.nullable(),members_url:y.z.url(),invites_url:y.z.url(),avatar_url:y.z.url().nullable()}),Rl=y.z.object({name:y.z.string().regex(Vc)}),zl=y.z.object({name:y.z.string().max(100).optional(),avatar_file_id:y.z.string().nullable().optional(),avatar_url:y.z.string().url().nullable().optional()});var Bl=class{constructor(e){this.client=e,this.members=new Fl(e),this.agents=new Il(e)}async list(){let e=await this.client.request(`GET`,`/api/organizations`);return await K(e,200),e.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e}`);return await K(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/organizations`,JSON.stringify(e));return await K(t,201),t.json()}async update(e,t){let n=await this.client.request(`PATCH`,`/api/organizations/${e}`,JSON.stringify(t));return await K(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e}`);await K(t,204)}};const Vl=y.default.object({id:y.default.uuid(),created_at:y.default.date(),updated_at:y.default.date(),email:y.default.string().email(),email_verified:y.default.boolean(),display_name:y.default.string(),username:y.default.string(),organization_id:y.default.uuid(),avatar_url:y.default.string().url().nullable()}),Hl=y.default.object({display_name:y.default.string().max(100).optional(),username:y.default.string().regex(Vc).optional(),avatar_file_id:y.default.string().nullable().optional()}),Ul=y.default.object({provider:y.default.enum([`github`,`google`]),provider_account_id:y.default.string()}),Wl=y.default.object({github:y.default.array(Ul),google:y.default.array(Ul)});var Gl=class{constructor(e){this.client=e}async me(){return this.get(`me`)}async get(e){let t=await this.client.request(`GET`,`/api/users/${e}`);return await K(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/users/me`,JSON.stringify(e));return await K(t,200),t.json()}async accounts(){let e=await this.client.request(`GET`,`/api/users/me/accounts`);return await K(e,200),e.json()}async unlinkProvider(e,t){let n=await this.client.request(`DELETE`,`/api/users/me/accounts/${e}/${t}`);await K(n,204)}async delete(){let e=await this.client.request(`DELETE`,`/api/users/me`);await K(e,204)}};const Kl=y.z.enum([`ai-sdk`]),ql=y.z.array(y.z.custom()),Jl=y.z.enum([`user`,`assistant`,`system`]),Yl=y.z.object({id:y.z.uuid(),created_at:y.z.string().datetime(),chat_id:y.z.uuid(),metadata:Bc}).extend({format:y.z.literal(`ai-sdk`),parts:ql,role:Jl}),Xl=y.z.discriminatedUnion(`format`,[Yl]),Zl=Rc.extend({chat_id:y.z.uuid(),format:Kl.default(`ai-sdk`).optional()}),Ql=zc(Xl),$l=y.z.object({chat_id:y.z.uuid(),message_id:y.z.uuid()}),eu=y.z.object({id:y.z.uuid().optional(),role:Jl,parts:ql,metadata:Bc.optional(),format:y.z.literal(`ai-sdk`).optional()}),tu=y.z.object({message_id:y.z.uuid(),metadata:Bc.optional(),role:Jl.optional(),parts:ql.optional(),format:y.z.literal(`ai-sdk`).optional(),behavior:y.z.enum([`interrupt`,`enqueue`,`none`]).optional()}),nu=y.z.enum([`enqueue`,`interrupt`,`append`]),ru=y.z.object({chat_id:y.z.uuid(),behavior:nu.optional(),messages:y.z.array(eu).min(1)}),iu=y.z.object({messages:y.z.array(Xl)});var au=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;t.set(`chat_id`,e.chat_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor),e.format&&t.set(`format`,e.format);let n=await this.client.request(`GET`,`/api/messages?${t.toString()}`);return await K(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/messages/${e}`);await K(t,204)}async get(e){let t=await this.client.request(`GET`,`/api/messages/${e}`);return await K(t,200),t.json()}async update(e){let t=await this.client.request(`PUT`,`/api/messages/${e.message_id}`,JSON.stringify(e));await K(t,200)}async send(e){let t=await this.client.request(`POST`,`/api/messages`,JSON.stringify(e));return await K(t,201),t.json()}};Rc.extend({chat_id:y.z.uuid()});const ou=y.z.object({id:y.z.uuid(),started_at:y.z.date(),agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid().nullable(),chat_id:y.z.uuid(),step_count:y.z.number().int().positive(),status:ol.nullable(),error:y.z.string().nullable()});zc(ou);var su=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.cursor&&t.set(`cursor`,e.cursor),e.limit&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/runs?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/runs/${e.run_id}`);return await K(t,200),t.json()}};const cu=y.z.enum([`streaming`,`idle`,`error`,`interrupted`]),lu=y.z.enum([`private`,`organization`,`public`]),uu=y.z.object({id:y.z.uuid(),created_at:y.z.iso.datetime(),updated_at:y.z.iso.datetime(),created_by:y.z.uuid().nullable(),organization_id:y.z.uuid(),title:y.z.string().nullable(),visibility:lu,metadata:Bc,archived:y.z.boolean(),status:cu,error:y.z.string().nullable(),agent_deployment_id:y.z.uuid().nullable(),agent:bl}),du=y.z.enum([`websocket`,`sse`]),fu=y.z.object({organization_id:y.z.uuid(),title:y.z.string().optional(),visibility:lu.default(`private`).optional(),metadata:Bc.optional(),agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid().optional(),messages:y.z.array(eu).optional()}),pu=fu.extend({stream:y.z.literal(!0)}),mu=fu.extend({stream:y.z.literal(!1).optional()}),hu=y.z.union([pu,mu]),gu=y.z.union([Rc.extend({organization_id:y.z.uuid()}),Rc.extend({agent_id:y.z.uuid()})]),_u=uu.extend({messages:y.z.array(Xl)}),vu=zc(uu),yu=y.z.discriminatedUnion(`event`,[y.z.strictObject({event:y.z.literal(`chat.updated`),data:uu}),y.z.strictObject({event:y.z.literal(`message.created`),data:Xl}),y.z.strictObject({event:y.z.literal(`message.updated`),data:Xl}),y.z.strictObject({event:y.z.literal(`message.deleted`),data:y.z.object({id:y.z.uuid()})}),y.z.strictObject({event:y.z.literal(`message.chunk.added`),data:y.z.object({id:y.z.uuid(),chunk:y.z.custom()})})]),bu=y.z.strictObject({event:y.z.literal(`chat.created`),data:_u});var xu=class{constructor(e){this.client=e,this.runs=new su(e),this.steps=new ll(e)}async create(e){let t={};e.stream&&(t.Accept=`text/event-stream`);let n=await this.client.request(`POST`,`/api/chats`,JSON.stringify(e),{headers:t});if(await K(n,201),e.stream){let e=n.headers.get(`Content-Type`);if(e!==`text/event-stream`)throw Error(`Expected text/event-stream, got ${e}`);if(!n.body)throw Error(`The stream endpoint did not return a body!`);let t=Hc(n,y.z.discriminatedUnion(`event`,[yu,bu])),r=t.getReader(),{done:i,value:a}=await r.read();if(i)throw Error(`The stream ended before the chat.created event was received!`);if(a.event!==`chat.created`)throw Error(`Expected chat.created, got ${a.event}`);return r.releaseLock(),{...a.data,messages:a.data.messages,stream:t}}return n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e}`);return await K(t,200),t.json()}async list(e){let t=new URLSearchParams;`organization_id`in e&&e.organization_id?t.set(`organization_id`,e.organization_id):`agent_id`in e&&e.agent_id&&t.set(`agent_id`,e.agent_id),e.cursor&&t.set(`cursor`,e.cursor),e.limit&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/chats?${t.toString()}`);return await K(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/chats/${e}`);await K(t,204)}async stop(e){let t=await this.client.request(`POST`,`/api/chats/${e}/stop`);await K(t,200)}async stream(e,t={transport:`websocket`}){if(t?.transport===`websocket`)return this.streamWS(e,t?.signal);let n=await this.client.request(`GET`,`/api/chats/${e}/stream`,void 0,{abortSignal:t?.signal,headers:{Accept:`text/event-stream`}});return await K(n,200),Hc(n,yu)}streamWS(e,t){let n=this.client.websocket(`/api/chats/${e}/stream`),r=new Zs,i=r.writable.getWriter(),a,o=new TextDecoder,s=!1,c=()=>{if(!s){s=!0,a?a.finally(()=>{i.close().catch(()=>{})}):i.close().catch(()=>{});try{n.close()}catch{}}};return t&&(t.aborted?c():t.addEventListener(`abort`,c,{once:!0})),n.addEventListener(`error`,()=>{c()}),n.addEventListener(`close`,()=>{c()}),n.addEventListener(`message`,e=>{if(s)return;let t;t=typeof e.data==`string`?e.data:o.decode(e.data),a=a?a.then(()=>{if(!s)return i.write(t).catch(()=>{})}):i.write(t).catch(()=>{})}),Uc(r.readable,yu)}};const Su=y.z.object({id:y.z.uuid(),organization_id:y.z.uuid(),role:jl,invited_by:y.z.uuid(),expires_at:y.z.date(),created_at:y.z.date(),updated_at:y.z.date(),reusable:y.z.boolean(),accepted_at:y.z.date().nullable(),email:y.z.string().email().nullable()}),Cu=y.z.object({organization_id:y.z.uuid(),role:jl,email:y.z.string().email().optional(),reusable:y.z.boolean().optional()}),wu=y.z.object({organization_id:y.z.uuid()}),Tu=y.z.object({organization_id:y.z.uuid(),invite_id:y.z.uuid()}),Eu=y.z.object({code:y.z.string()}),Du=Eu.extend({invite_id:y.z.uuid()});var Ou=class{constructor(e){this.client=e}async create(e){let t=await this.client.request(`POST`,`/api/invites`,JSON.stringify(e));return await K(t,201),t.json()}async list(e){let t=await this.client.request(`GET`,`/api/invites?organization_id=${e.organization_id}`);return await K(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/invites/${e.invite_id}`);await K(t,204)}async accept(e){let t=await this.client.request(`POST`,`/api/invites/${e.invite_id}/accept`,JSON.stringify({code:e.code}));return await K(t,201),t.json()}},ku=class{constructor(e){this.chats=new xu(this),this.runs=new su(this),this.agents=new kl(this),this.files=new Al(this),this.organizations=new Bl(this),this.invites=new Ou(this),this.users=new Gl(this),this.messages=new au(this),this.baseURL=new URL(e?.baseURL??(globalThis.window===void 0?`https://blink.so`:window.location.origin)),this.fetch=e?.fetch,this.authToken=e?.authToken,this.auth=new Ks(this,this.baseURL)}request(e,t,n,r){let i=new URL(t,this.baseURL),a=new Headers;if(this.authToken&&a.set(`Authorization`,`Bearer ${this.authToken}`),typeof n==`string`&&a.set(`Content-Type`,`application/json`),r?.headers)for(let[e,t]of Object.entries(r.headers))a.set(e,t);let o;if(r?.abortSignal&&r?.timeout)throw Error(`Cannot specify both abortSignal and timeout`);return r?.abortSignal&&(o=r.abortSignal),r?.timeout&&(o=AbortSignal.timeout(r.timeout)),(this.fetch??fetch)(i.toString(),{method:e,headers:a,body:n,signal:o})}websocket(e){let t=new URL(e,this.baseURL);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,new WebSocket(t.toString())}},Au=W({"../../node_modules/@blink-sdk/compute-protocol/dist/schema-CZdQiIXB.cjs":(e=>{var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>function(){return t||(0,e[i(e)[0]])((t={exports:{}}).exports,t),t.exports},c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));let u=G(`zod`);u=l(u);let d=(e,t)=>{let n=new Uint8Array(1+t.length);return n[0]=e,n.set(t,1),n},f=(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},p=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1)),m=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}({}),h=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}({}),g={[m.REQUEST]:u.z.string(),[m.PROXY_INIT]:u.z.object({method:u.z.string(),headers:u.z.record(u.z.string(),u.z.string()),url:u.z.string()}),[m.PROXY_BODY]:u.z.instanceof(Uint8Array),[m.PROXY_WEBSOCKET_MESSAGE]:u.z.object({type:u.z.enum([`text`,`binary`]),data:u.z.instanceof(Uint8Array)}),[m.PROXY_WEBSOCKET_CLOSE]:u.z.object({code:u.z.number().optional(),reason:u.z.string().optional()})},_={[h.RESPONSE]:u.z.string(),[h.NOTIFICATION]:u.z.string(),[h.PROXY_INIT]:u.z.object({status_code:u.z.number(),status_message:u.z.string(),headers:u.z.record(u.z.string(),u.z.string())}),[h.PROXY_DATA]:u.z.instanceof(Uint8Array),[h.PROXY_WEBSOCKET_MESSAGE]:u.z.instanceof(Uint8Array),[h.PROXY_WEBSOCKET_CLOSE]:u.z.object({code:u.z.number(),reason:u.z.string()})},v={[m.PROXY_INIT]:{method:u.z.string(),headers:u.z.record(u.z.string(),u.z.string()),url:u.z.string()}},y={process_execute:u.z.object({command:u.z.string(),args:u.z.array(u.z.string()),env:u.z.record(u.z.string(),u.z.string()).optional(),cwd:u.z.string().optional()}),process_send_input:u.z.object({pid:u.z.number(),data:u.z.string()}),process_wait:u.z.object({pid:u.z.number(),output_idle_timeout_ms:u.z.number().optional(),timeout_ms:u.z.number().optional()}),process_list:u.z.object({include_dead:u.z.boolean().optional()}),process_read_plain_output:u.z.object({pid:u.z.number(),start_line:u.z.number().optional(),end_line:u.z.number().optional()}),process_kill:u.z.object({pid:u.z.number(),signal:u.z.string().optional()}),set_env:u.z.object({env:u.z.record(u.z.string(),u.z.string())}),read_file:u.z.object({path:u.z.string(),line_start:u.z.number().optional(),line_end:u.z.number().optional()}),write_file:u.z.object({path:u.z.string(),content:u.z.string(),base64:u.z.boolean().optional(),mode:u.z.number().optional()}),read_directory:u.z.object({path:u.z.string()}),watch_directory:u.z.object({path:u.z.string()}),deploy_static_files:u.z.object({path:u.z.string()})},b=u.z.object({pid:u.z.number(),command:u.z.string(),args:u.z.array(u.z.string()),title:u.z.string().optional(),cwd:u.z.string(),env:u.z.record(u.z.string(),u.z.string()),exit_code:u.z.number().optional(),exit_signal:u.z.number().optional(),duration_ms:u.z.number().optional(),output_total_lines:u.z.number()}),x=b.extend({ansi_output:u.z.string(),plain_output:u.z.object({lines:u.z.array(u.z.string()),total_lines:u.z.number()})}),S={process_execute:u.z.object({pid:u.z.number()}),process_send_input:u.z.object({}),process_wait:x,process_list:u.z.object({processes:u.z.array(b)}),process_read_plain_output:u.z.object({lines:u.z.array(u.z.string()),total_lines:u.z.number(),duration_ms:u.z.number(),exit_code:u.z.number().optional(),exit_signal:u.z.number().optional()}),process_kill:u.z.object({}),set_env:u.z.object({}),read_file:u.z.object({total_lines:u.z.number(),lines_read:u.z.number(),start_line:u.z.number(),content:u.z.string(),mime_type:u.z.string()}),write_file:u.z.object({}),read_directory:u.z.object({entries:u.z.array(u.z.object({name:u.z.string(),type:u.z.enum([`file`,`directory`,`symlink`])}))}),watch_directory:u.z.object({}),deploy_static_files:u.z.object({deployment_id:u.z.string()})},C=u.z.object({type:u.z.enum([`create`,`update`,`delete`]),path:u.z.string()}),w=u.z.object({type:u.z.enum([`context`,`added`,`deleted`]),content:u.z.string(),oldLineNumber:u.z.number().optional(),newLineNumber:u.z.number().optional()}),T=u.z.object({oldStart:u.z.number(),oldLines:u.z.number(),newStart:u.z.number(),newLines:u.z.number(),lines:u.z.array(w)}),E=u.z.object({path:u.z.string(),status:u.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:u.z.string().optional(),insertions:u.z.number(),deletions:u.z.number(),chunks:u.z.array(T)}),D=u.z.object({totalFiles:u.z.number(),totalInsertions:u.z.number(),totalDeletions:u.z.number(),netChange:u.z.number(),startHash:u.z.string().optional(),currentHash:u.z.string().optional(),timespan:u.z.number(),files:u.z.array(E)}),O=u.z.object({path:u.z.string(),status:u.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:u.z.boolean()}),k=u.z.object({hash:u.z.string(),shortHash:u.z.string(),message:u.z.string(),author:u.z.string(),email:u.z.string(),date:u.z.date(),timestamp:u.z.date(),filesChanged:u.z.number(),insertions:u.z.number(),deletions:u.z.number(),commitDiff:u.z.array(E).optional()}),A=u.z.object({files:u.z.array(O),branch:u.z.string(),ahead:u.z.number(),behind:u.z.number(),timestamp:u.z.date(),sessionDiff:D.optional(),workingDirectoryDiff:D.optional(),newCommits:u.z.array(k),currentCommit:u.z.object({hash:u.z.string(),shortHash:u.z.string(),message:u.z.string(),author:u.z.string(),date:u.z.date()}).optional(),diffSkipped:u.z.boolean().optional(),payloadTruncated:u.z.boolean().optional(),estimatedSizeKB:u.z.number().optional()}),j=u.z.object({debounceDelay:u.z.number().optional(),gitStatusInterval:u.z.number().optional(),ignoreDotfiles:u.z.boolean().optional(),ignored:u.z.array(u.z.string()).optional(),watchGit:u.z.boolean().optional(),includeDiffs:u.z.boolean().optional(),maxDiffFiles:u.z.number().optional(),maxPayloadSizeKB:u.z.number().optional(),truncateLargeDiffs:u.z.boolean().optional()}),M={process_status:u.z.object({status:b}),process_output:u.z.object({pid:u.z.number(),output:u.z.string()}),file_change:u.z.object({changes:u.z.array(C)}),git_status:A};Object.defineProperty(e,`ClientMessageSchema`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`ClientMessageType`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,`DiffChunkSchema`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(e,`DiffLineSchema`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`DiffSummarySchema`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`FileChangeEventSchema`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`FileDiffSchema`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`GitCommitEventSchema`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`GitFileStatusSchema`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,`GitStatusEventSchema`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(e,`NotificationSchema`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(e,`ProcessStatusSchema`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`ProcessWaitSchema`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(e,`ProxySchema`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`RequestSchema`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`ResponseSchema`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`ServerMessageSchema`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`ServerMessageType`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(e,`WatchOptionsSchema`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,`__commonJS`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,`__toESM`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`createMessagePayload`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`createWebSocketMessagePayload`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,`parseWebSocketMessagePayload`,{enumerable:!0,get:function(){return p}})})}),ju=W({"../../node_modules/ws/lib/constants.js":((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:()=>{}}})}),Mu=W({"../../node_modules/ws/lib/buffer-util.js":((e,t)=>{let{EMPTY_BUFFER:n}=ju(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=G(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})}),Nu=W({"../../node_modules/ws/lib/limiter.js":((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])}}}})}),Pu=W({"../../node_modules/ws/lib/permessage-deflate.js":((e,t)=>{let n=G(`zlib`),r=Mu(),i=Nu(),{kStatusCode:a}=ju(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!p){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;p=new i(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})}),Fu=W({"../../node_modules/ws/lib/validation.js":((e,t)=>{let{isUtf8:n}=G(`buffer`),{hasBlob:r}=ju(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=G(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})}),Iu=W({"../../node_modules/ws/lib/receiver.js":((e,t)=>{let{Writable:n}=G(`stream`),r=Pu(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=ju(),{concat:c,toArrayBuffer:l,unmask:u}=Mu(),{isValidStatusCode:d,isValidUTF8:f}=Fu(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let t=this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`);e(t);return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(!this._fragmented){let t=this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let t=this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`);e(t);return}if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`);e(t);return}}else{let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){let t=this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`);e(t);return}}else if(this._masked){let t=this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`);e(t);return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){let t=this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`);e(t);return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);e(t);return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let e=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);t(e);return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){let t=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);e(t);return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){let e=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);t(e);return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})}),Lu=W({"../../node_modules/ws/lib/sender.js":((e,t)=>{let{Duplex:n}=G(`stream`),{randomFillSync:r}=G(`crypto`),i=Pu(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=ju(),{isBlob:c,isValidStatusCode:l}=Fu(),{mask:u,toBuffer:d}=Mu(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})}),Ru=W({"../../node_modules/ws/lib/event-target.js":((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=ju(),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)}})}),zu=W({"../../node_modules/ws/lib/extension.js":((e,t)=>{let{tokenChars:n}=Fu();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}})}),Bu=W({"../../node_modules/ws/lib/websocket.js":((e,t)=>{let n=G(`events`),r=G(`https`),i=G(`http`),a=G(`net`),o=G(`tls`),{randomBytes:s,createHash:c}=G(`crypto`),{Duplex:l,Readable:u}=G(`stream`),{URL:d}=G(`url`),f=Pu(),p=Iu(),m=Lu(),{isBlob:h}=Fu(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=ju(),{EventTarget:{addEventListener:w,removeEventListener:T}}=Ru(),{format:E,parse:D}=zu(),{toBuffer:O}=Mu(),k=Symbol(`kAborted`),A=[8,13],j=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),ee(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,R),i.on(`drain`,ne),i.on(`error`,z),i.on(`message`,B),i.on(`ping`,ie),i.on(`pong`,ae),a.onerror=se,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,V),t.on(`data`,le),t.on(`end`,ue),t.on(`error`,de),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(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())}),ce(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){L(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||_,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){L(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||_,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){L(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||_,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),N.prototype.addEventListener=w,N.prototype.removeEventListener=T,t.exports=N;function ee(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:A[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!A.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${A.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;P(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),_=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?te:F),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=E({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!M.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{I(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[k]||(x=e._req=null,P(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){I(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{let t=SyntaxError(`Invalid URL: ${i}`);P(e,t);return}ee(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||I(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){I(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+v).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){I(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){I(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){I(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=D(u)}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){I(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function P(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function F(e){return e.path=e.socketPath,a.connect(e)}function te(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function I(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,I),t.setHeader?(t[k]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(P,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function L(e,t,n){if(t){let n=h(t)?t.size:O(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${j[e.readyState]})`);process.nextTick(n,t)}}function R(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,le),process.nextTick(oe,n._socket),e===1005?n.close():n.close(e,t))}function ne(){let e=this[S];e.isPaused||e._socket.resume()}function z(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,le),process.nextTick(oe,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function re(){this[S].emitClose()}function B(e,t){this[S].emit(`message`,e,t)}function ie(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function ae(e){this[S].emit(`pong`,e)}function oe(e){e.resume()}function se(e){let t=this[S];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,ce(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ce(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function V(){let e=this[S];this.removeListener(`close`,V),this.removeListener(`data`,le),this.removeListener(`end`,ue),e._readyState=N.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,re),e._receiver.on(`finish`,re))}function le(e){this[S]._receiver.write(e)||this.pause()}function ue(){let e=this[S];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function de(){let e=this[S];this.removeListener(`error`,de),this.on(`error`,C),e&&(e._readyState=N.CLOSING,this.destroy())}})}),Vu=W({"../../node_modules/ws/lib/stream.js":((e,t)=>{Bu();let{Duplex:n}=G(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})}),Hu=W({"../../node_modules/ws/lib/subprotocol.js":((e,t)=>{let{tokenChars:n}=Fu();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}})}),Uu=W({"../../node_modules/ws/lib/websocket-server.js":((e,t)=>{let n=G(`events`),r=G(`http`),{Duplex:i}=G(`stream`),{createHash:a}=G(`crypto`),o=zu(),s=Pu(),c=Hu(),l=Bu(),{GUID:u,kWebSocket:d}=ju(),f=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=p(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(m,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,h);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){_(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){_(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!f.test(i)){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){g(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{_(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let p=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&p!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(p);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{_(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return g(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return g(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[d])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return g(i,503);let f=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+u).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(f.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});f.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,f,r),i.write(f.concat(`\r
|
|
19
|
+
`&&r++}}return[t,n]}var ac=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=rc({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}},oc=`vercel.ai.error`,sc=Symbol.for(oc),cc,lc=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[cc]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,oc)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};cc=sc;var uc=lc;function dc(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var fc=`AI_InvalidArgumentError`,pc=`vercel.ai.error.${fc}`,mc=Symbol.for(pc),hc,gc=class extends uc{constructor({message:e,cause:t,argument:n}){super({name:fc,message:e,cause:t}),this[hc]=!0,this.argument=n}static isInstance(e){return uc.hasMarker(e,pc)}};hc=mc;var _c=`AI_JSONParseError`,vc=`vercel.ai.error.${_c}`,yc=Symbol.for(vc),bc,xc=class extends uc{constructor({text:e,cause:t}){super({name:_c,message:`JSON parsing failed: Text: ${e}.
|
|
20
|
+
Error message: ${dc(t)}`,cause:t}),this[bc]=!0,this.text=e}static isInstance(e){return uc.hasMarker(e,vc)}};bc=yc;var Sc=`AI_TypeValidationError`,Cc=`vercel.ai.error.${Sc}`,wc=Symbol.for(Cc),Tc,Ec=class e extends uc{constructor({value:e,cause:t}){super({name:Sc,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
21
|
+
Error message: ${dc(t)}`,cause:t}),this[Tc]=!0,this.value=e}static isInstance(e){return uc.hasMarker(e,Cc)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};Tc=wc;var Dc=Ec,Oc=({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new gc({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`};Oc();var kc=/"__proto__"\s*:/,Ac=/"constructor"\s*:/;function jc(e){let t=JSON.parse(e);return typeof t!=`object`||!t||kc.test(e)===!1&&Ac.test(e)===!1?t:Mc(t)}function Mc(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Nc(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return jc(e)}finally{Error.stackTraceLimit=t}}var Pc=Symbol.for(`vercel.ai.validator`);function Fc(e){return{[Pc]:!0,validate:e}}function Ic(e){return typeof e==`object`&&!!e&&Pc in e&&e[Pc]===!0&&`validate`in e}function Lc(e){return Ic(e)?e:Rc(e)}function Rc(e){return Fc(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Dc({value:t,cause:n.issues})}})}async function zc({value:e,schema:t}){let n=Lc(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Dc.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:Dc.wrap({value:e,cause:t}),rawValue:e}}}async function Bc({text:e,schema:t}){try{let n=Nc(e);return t==null?{success:!0,value:n,rawValue:n}:await zc({value:n,schema:t})}catch(t){return{success:!1,error:xc.isInstance(t)?t:new xc({text:e,cause:t}),rawValue:void 0}}}var{btoa:Vc,atob:Hc}=globalThis;function Uc(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}const K=async(e,t)=>{if(e.status!==t){let n=await e.text();try{let r=JSON.parse(n);throw r.message?Error(r.message,{cause:r.details}):Error(`Expected status ${t}, got ${e.status}: ${n}`)}catch{throw Error(`Expected status ${t}, got ${e.status}: ${n}`)}}},Wc=y.z.object({per_page:y.z.number().int().positive().max(100).default(10).optional(),page:y.z.number().int().nonnegative().default(0).optional()}),Gc=e=>y.z.object({has_more:y.z.boolean(),items:y.z.array(e)}),Kc=y.z.object({limit:y.z.number().int().positive().max(100).default(10).optional(),cursor:y.z.string().optional()}),qc=e=>y.z.object({next_cursor:y.z.string().nullable(),items:y.z.array(e)}),Jc=y.z.any().nullable().refine(e=>e?Object.keys(e).length<=16:!0,{message:`Metadata must contain at most 16 keys`}),Yc=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,Xc=(e,t)=>{let n=new ac;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(n.writable).catch(e=>{}),Zc(n.readable,t)},Zc=(e,t)=>{let n=e.pipeThrough(new TransformStream({async transform(e,n){let r=await Bc({text:e.data});if(!r.success){n.error(r.error);return}let i=t.safeParse({event:e.event,data:r.value});if(!i.success){n.error(i.error);return}n.enqueue(i.data)}}));return Uc(n)},Qc=y.z.union([y.z.object({agent_id:y.z.uuid(),deployment_id:y.z.uuid()}),y.z.object({agent_id:y.z.uuid(),deployment_number:y.z.number().int().positive()})]),$c=y.z.object({agent_id:y.z.uuid(),deployment_id:y.z.uuid()}),el=y.z.object({path:y.z.string(),id:y.z.uuid()}),tl=el.or(y.z.object({path:y.z.string(),data:y.z.string().max(1024*1024*5)})),nl=y.z.enum([`production`,`preview`]),rl=y.z.object({agent_id:y.z.uuid(),output_files:y.z.array(tl).optional(),source_files:y.z.array(tl).optional(),files:y.z.array(tl).optional(),target:nl,entrypoint:y.z.string().optional(),message:y.z.string().max(128).optional()}).transform(e=>e.files&&!e.output_files?{...e,output_files:e.files,files:void 0}:e),il=y.z.object({id:y.z.uuid(),number:y.z.number().int().positive(),created_at:y.z.iso.datetime(),updated_at:y.z.iso.datetime(),created_by:y.z.uuid().nullable(),created_from:y.z.enum([`cli`]),agent_id:y.z.uuid(),source_files:y.z.array(el),output_files:y.z.array(el),status:y.z.enum([`success`,`failed`,`deploying`,`pending`]),target:nl,error_message:y.z.string().nullable(),user_message:y.z.string().nullable(),platform:y.z.enum([`lambda`]),platform_memory_mb:y.z.number().int().positive(),platform_region:y.z.string().nullable()}),al=y.z.object({id:y.z.uuid(),created_at:y.z.string().datetime(),updated_at:y.z.string().datetime(),agent_id:y.z.uuid(),deployment_id:y.z.uuid(),level:y.z.enum([`log`,`info`,`warning`,`error`]),message:y.z.string()}),ol=Wc.extend({agent_id:y.z.uuid(),order:y.z.enum([`asc`,`desc`]).default(`asc`).optional()}),sl=Gc(il);var cl=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),e.order&&t.set(`order`,e.order);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t;t=`deployment_id`in e?e.deployment_id:e.deployment_number.toString();let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments/${t}`);return await K(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/deployments`,JSON.stringify(e));return await K(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);await K(t,200)}};y.z.object({agent_id:y.z.uuid(),target:nl.array().optional()}),y.z.object({id:y.z.uuid(),created_at:y.z.date(),updated_at:y.z.date(),created_by:y.z.uuid(),updated_by:y.z.uuid(),key:y.z.string(),value:y.z.string().nullable(),secret:y.z.boolean(),target:nl.array()});const ll=y.z.object({key:y.z.string(),value:y.z.string(),secret:y.z.boolean(),target:nl.array().optional(),upsert:y.z.boolean().optional()});ll.extend({agent_id:y.z.uuid()}),y.z.object({agent_id:y.z.uuid(),id:y.z.uuid()}),y.z.object({agent_id:y.z.uuid(),id:y.z.uuid(),key:y.z.string().optional(),value:y.z.string().optional(),secret:y.z.boolean().optional(),target:nl.array().default([`preview`,`production`]).optional()});var ul=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;if(e.target)for(let n of e.target)t.append(`target`,n);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/env?${t.toString()}`);return await K(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/env`,JSON.stringify(e));return await K(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/env/${e.id}`);await K(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/agents/${e.agent_id}/env/${e.id}`,JSON.stringify(e));return await K(t,200),t.json()}};const dl=y.z.object({id:y.z.string(),agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid(),received_at:y.z.date(),request_method:y.z.string(),request_handler_location:y.z.string().nullable(),duration_ms:y.z.number().nullable(),error:y.z.string().nullable(),response_status:y.z.number().nullable()});dl.extend({request_headers:y.z.record(y.z.string(),y.z.string()),request_headers_redacted:y.z.boolean(),request_body:y.z.string().nullable(),request_body_redacted:y.z.boolean(),response_headers:y.z.record(y.z.string(),y.z.string()).nullable(),response_headers_redacted:y.z.boolean(),response_body:y.z.string().nullable(),response_body_redacted:y.z.boolean()}),Kc.extend({agent_id:y.z.string(),agent_deployment_id:y.z.number().optional()}),qc(dl);var fl=class{constructor(e){this.client=e}async log(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs/${e.webhook_id}`);return await K(t,200),t.json()}async logs(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id.toString()),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs?${t.toString()}`);return await K(n,200),n.json()}};Kc.extend({agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid().optional()}),y.z.object({agent_id:y.z.uuid(),run_id:y.z.uuid()});var pl=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs/${e.run_id}`);return await K(t,200),t.json()}};const ml=y.z.enum([`streaming`,`stalled`,`completed`,`interrupted`,`error`]),hl=y.z.enum([`tool_call`,`queued_message`]),gl=y.z.object({id:y.z.uuid(),number:y.z.number().int().positive(),chat_id:y.z.uuid(),chat_run_id:y.z.uuid(),agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid(),started_at:y.z.string().datetime(),status:ml,error:y.z.string().nullable(),continuation_reason:hl.nullable(),response_status:y.z.number().nullable(),response_message_id:y.z.uuid().nullable(),time_to_first_token_micros:y.z.number().nullable()});gl.extend({heartbeat_at:y.z.date(),completed_at:y.z.date().nullable(),interrupted_at:y.z.date().nullable(),first_message_id:y.z.uuid().nullable(),last_message_id:y.z.uuid().nullable(),response_headers:y.z.record(y.z.string(),y.z.string()).nullable(),response_headers_redacted:y.z.boolean(),response_body:y.z.string().nullable(),response_body_redacted:y.z.boolean(),usage_model:y.z.string().nullable(),usage_total_input_tokens:y.z.number().nullable(),usage_total_output_tokens:y.z.number().nullable(),usage_total_tokens:y.z.number().nullable(),usage_total_cached_input_tokens:y.z.number().nullable(),usage_cost_usd:y.z.number().nullable()}),Kc.extend({chat_id:y.z.uuid(),run_id:y.z.uuid().optional()}),qc(gl);var _l=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id);let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps/${e.step_id}`);return await K(t,200),t.json()}};Kc.extend({agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid().optional(),chat_id:y.z.uuid().optional(),run_id:y.z.uuid().optional(),status:ml.optional()}),qc(gl);var vl=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id),e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.chat_id&&t.set(`chat_id`,e.chat_id),e.status&&t.set(`status`,e.status);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps/${e.step_id}`);return await K(t,200),t.json()}};const yl=y.z.object({type:y.z.literal(`eq`),key:y.z.string(),value:y.z.string()}),bl=y.z.object({type:y.z.literal(`and`),get filters(){return y.z.array(y.z.union([yl,bl]))}}),xl=y.z.object({start_time:y.z.iso.datetime().pipe(y.z.coerce.date()),end_time:y.z.iso.datetime().pipe(y.z.coerce.date()),filters:y.z.string().transform(e=>JSON.parse(e)).pipe(bl),limit:y.z.string().pipe(y.z.coerce.number().min(1).max(1e4)).optional()});var Sl=class{constructor(e){this.client=e}async spans(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),t.set(`filters`,JSON.stringify(e.filters)),e.limit!==void 0&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/traces/spans?${t.toString()}`);return await K(n,200),await n.json()}};y.default.object({start_time:y.default.iso.datetime().pipe(y.default.coerce.date()),end_time:y.default.iso.datetime().pipe(y.default.coerce.date()),message_pattern:y.default.string().optional(),filters:y.default.string().transform(e=>JSON.parse(e)).pipe(bl).optional(),limit:y.default.string().pipe(y.default.coerce.number().min(1).max(1e4)).optional()});const Cl=y.default.object({timestamp:y.default.iso.datetime().pipe(y.default.coerce.date()),message:y.default.string(),level:y.default.enum([`info`,`error`,`warn`])}),wl=y.default.object({logs:y.default.array(Cl)});var Tl=class{constructor(e){this.client=e}async logs(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),e.limit&&t.set(`limit`,e.limit.toString()),e.message_pattern&&t.set(`message_pattern`,e.message_pattern),e.filters&&t.set(`filters`,JSON.stringify(e.filters));let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/logs?${t.toString()}`);await K(n,200);let r=await n.json();return wl.parse(r)}};const El=y.z.enum([`private`,`public`]),Dl=y.z.object({organization_id:y.z.uuid(),name:y.z.string().regex(Yc),description:y.z.string().optional(),visibility:El.default(`private`).optional(),source_files:y.z.array(tl).optional(),output_files:y.z.array(tl).optional(),entrypoint:y.z.string().optional(),env:y.z.array(ll).optional(),request_id:y.z.uuid().optional()}),Ol=y.z.object({id:y.z.uuid(),organization_id:y.z.uuid(),created_at:y.z.iso.datetime(),updated_at:y.z.iso.datetime(),created_by:y.z.uuid(),name:y.z.string().regex(Yc),description:y.z.string().nullable(),avatar_url:y.z.string().nullable(),visibility:El,active_deployment_id:y.z.uuid().nullable(),pinned:y.z.boolean().default(!1),request_url:y.z.url().nullable().describe(`The URL for the agent requests. Only visible to owners.`)}),kl=y.z.object({id:y.z.uuid(),name:y.z.string().regex(Yc).optional(),description:y.z.string().optional(),visibility:El.optional(),active_deployment_id:y.z.uuid().optional(),avatar_file_id:y.z.uuid().nullable().optional()}),Al=Wc.extend({organization_id:y.z.uuid().optional(),pinned:y.z.boolean().optional()}),jl=Gc(Ol),Ml=y.z.object({agent_id:y.z.uuid(),input:y.z.string(),caret:y.z.number().optional(),selection:y.z.tuple([y.z.number(),y.z.number()]).optional(),chat_id:y.z.uuid().optional(),agent_deployment_id:y.z.uuid().optional()}),Nl=y.z.object({text:y.z.string(),caret:y.z.number().optional(),selection:y.z.tuple([y.z.number(),y.z.number()]).optional()}),Pl=y.z.object({agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid().optional(),selected:y.z.record(y.z.string(),y.z.string()).optional()}),Fl=y.z.object({agent_id:y.z.uuid(),start_time:y.z.iso.datetime().pipe(y.z.coerce.date()),end_time:y.z.iso.datetime().pipe(y.z.coerce.date())}),Il=y.z.object({seconds:y.z.string()});var Ll=class{constructor(e){this.client=e,this.deployments=new cl(e),this.env=new ul(e),this.webhook=new fl(e),this.runs=new pl(e),this.steps=new vl(e),this.logs=new Tl(e),this.traces=new Sl(e)}async create(e){let t=await this.client.request(`POST`,`/api/agents`,JSON.stringify(e));return await K(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/agents/${e.id}`,JSON.stringify(e));return await K(t,200),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e}`);return await K(t,200),t.json()}async list(e){let t=new URLSearchParams;e.organization_id&&t.set(`organization_id`,e.organization_id),e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),typeof e.pinned==`boolean`&&t.set(`pinned`,e.pinned.toString());let n=await this.client.request(`GET`,`/api/agents?${t.toString()}`);return await K(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}`);await K(t,204)}async completions(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/completions`,JSON.stringify(e));if(await K(t,200),t.headers.get(`content-type`)===`application/json`){let e=await t.json();return Uc(new ReadableStream({start(t){t.enqueue(e),t.close()}}))}return Xc(t,Nl)}async uiOptions(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.selected&&t.set(`selected`,JSON.stringify(e.selected));let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/ui-options?${t.toString()}`);return await K(n,200),n.json()}async pin(e){let t=await this.client.request(`POST`,`/api/agents/${e}/pin`);await K(t,204)}async unpin(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}/pin`);await K(t,204)}async getRuntimeUsage(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString());let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/usage/runtime?${t.toString()}`);return await K(n,200),n.json()}},Rl=class{constructor(e){this.client=e}async upload(e){let t=new FormData;t.append(`file`,e);let n=await this.client.request(`POST`,`/api/files`,t);return await K(n,201),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/files/${e}`);return await K(t,200),new File([await t.blob()],``)}};const zl=y.z.enum([`owner`,`admin`,`billing_admin`,`member`]),Bl=y.z.object({user_id:y.z.uuid(),organization_id:y.z.uuid(),role:zl,created_at:y.z.date(),updated_at:y.z.date()}),Vl=y.z.object({id:y.z.uuid(),created_at:y.z.date(),updated_at:y.z.date(),display_name:y.z.string().nullable(),email:y.z.email(),avatar_url:y.z.url().nullable(),username:y.z.string()}),Hl=Bl.extend({user:Vl});Wc.extend({organization_id:y.z.uuid()}),Gc(Hl),y.z.object({organization_id:y.z.uuid(),user_id:y.z.uuid()}),y.z.object({role:y.z.enum([`owner`,`admin`,`member`,`billing_admin`]).optional()}).extend({organization_id:y.z.uuid(),user_id:y.z.uuid()});var Ul=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.per_page&&t.set(`per_page`,e.per_page.toString()),e.page&&t.set(`page`,e.page.toString());let n=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);return await K(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);await K(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/organizations/${e.organization_id}/members/${e.user_id}`,JSON.stringify({role:e.role}));return await K(t,200),t.json()}},Wl=class{constructor(e){this.client=e}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/agents/${e.agent_name}`);return await K(t,200),t.json()}};const Gl=y.z.object({id:y.z.uuid(),name:y.z.string(),created_at:y.z.date(),updated_at:y.z.date(),membership:Bl.nullable(),members_url:y.z.url(),invites_url:y.z.url(),avatar_url:y.z.url().nullable()}),Kl=y.z.object({name:y.z.string().regex(Yc)}),ql=y.z.object({name:y.z.string().max(100).optional(),avatar_file_id:y.z.string().nullable().optional(),avatar_url:y.z.string().url().nullable().optional()});var Jl=class{constructor(e){this.client=e,this.members=new Ul(e),this.agents=new Wl(e)}async list(){let e=await this.client.request(`GET`,`/api/organizations`);return await K(e,200),e.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e}`);return await K(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/organizations`,JSON.stringify(e));return await K(t,201),t.json()}async update(e,t){let n=await this.client.request(`PATCH`,`/api/organizations/${e}`,JSON.stringify(t));return await K(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e}`);await K(t,204)}};const Yl=y.default.object({id:y.default.uuid(),created_at:y.default.date(),updated_at:y.default.date(),email:y.default.string().email(),email_verified:y.default.boolean(),display_name:y.default.string(),username:y.default.string(),organization_id:y.default.uuid(),avatar_url:y.default.string().url().nullable()}),Xl=y.default.object({display_name:y.default.string().max(100).optional(),username:y.default.string().regex(Yc).optional(),avatar_file_id:y.default.string().nullable().optional()}),Zl=y.default.object({provider:y.default.enum([`github`,`google`]),provider_account_id:y.default.string()}),Ql=y.default.object({github:y.default.array(Zl),google:y.default.array(Zl)});var $l=class{constructor(e){this.client=e}async me(){return this.get(`me`)}async get(e){let t=await this.client.request(`GET`,`/api/users/${e}`);return await K(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/users/me`,JSON.stringify(e));return await K(t,200),t.json()}async accounts(){let e=await this.client.request(`GET`,`/api/users/me/accounts`);return await K(e,200),e.json()}async unlinkProvider(e,t){let n=await this.client.request(`DELETE`,`/api/users/me/accounts/${e}/${t}`);await K(n,204)}async delete(){let e=await this.client.request(`DELETE`,`/api/users/me`);await K(e,204)}};const eu=y.z.enum([`ai-sdk`]),tu=y.z.array(y.z.custom()),nu=y.z.enum([`user`,`assistant`,`system`]),ru=y.z.object({id:y.z.uuid(),created_at:y.z.string().datetime(),chat_id:y.z.uuid(),metadata:Jc}).extend({format:y.z.literal(`ai-sdk`),parts:tu,role:nu}),iu=y.z.discriminatedUnion(`format`,[ru]),au=Kc.extend({chat_id:y.z.uuid(),format:eu.default(`ai-sdk`).optional()}),ou=qc(iu),su=y.z.object({chat_id:y.z.uuid(),message_id:y.z.uuid()}),cu=y.z.object({id:y.z.uuid().optional(),role:nu,parts:tu,metadata:Jc.optional(),format:y.z.literal(`ai-sdk`).optional()}),lu=y.z.object({message_id:y.z.uuid(),metadata:Jc.optional(),role:nu.optional(),parts:tu.optional(),format:y.z.literal(`ai-sdk`).optional(),behavior:y.z.enum([`interrupt`,`enqueue`,`none`]).optional()}),uu=y.z.enum([`enqueue`,`interrupt`,`append`]),du=y.z.object({chat_id:y.z.uuid(),behavior:uu.optional(),messages:y.z.array(cu).min(1)}),fu=y.z.object({messages:y.z.array(iu)});var pu=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;t.set(`chat_id`,e.chat_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor),e.format&&t.set(`format`,e.format);let n=await this.client.request(`GET`,`/api/messages?${t.toString()}`);return await K(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/messages/${e}`);await K(t,204)}async get(e){let t=await this.client.request(`GET`,`/api/messages/${e}`);return await K(t,200),t.json()}async update(e){let t=await this.client.request(`PUT`,`/api/messages/${e.message_id}`,JSON.stringify(e));await K(t,200)}async send(e){let t=await this.client.request(`POST`,`/api/messages`,JSON.stringify(e));return await K(t,201),t.json()}};Kc.extend({chat_id:y.z.uuid()});const mu=y.z.object({id:y.z.uuid(),started_at:y.z.date(),agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid().nullable(),chat_id:y.z.uuid(),step_count:y.z.number().int().positive(),status:ml.nullable(),error:y.z.string().nullable()});qc(mu);var hu=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.cursor&&t.set(`cursor`,e.cursor),e.limit&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/runs?${t.toString()}`);return await K(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/runs/${e.run_id}`);return await K(t,200),t.json()}};const gu=y.z.enum([`streaming`,`idle`,`error`,`interrupted`]),_u=y.z.enum([`private`,`organization`,`public`]),vu=y.z.object({id:y.z.uuid(),created_at:y.z.iso.datetime(),updated_at:y.z.iso.datetime(),created_by:y.z.uuid().nullable(),organization_id:y.z.uuid(),title:y.z.string().nullable(),visibility:_u,metadata:Jc,archived:y.z.boolean(),status:gu,error:y.z.string().nullable(),agent_deployment_id:y.z.uuid().nullable(),agent:Ol}),yu=y.z.enum([`websocket`,`sse`]),bu=y.z.object({organization_id:y.z.uuid(),title:y.z.string().optional(),visibility:_u.default(`private`).optional(),metadata:Jc.optional(),agent_id:y.z.uuid(),agent_deployment_id:y.z.uuid().optional(),messages:y.z.array(cu).optional()}),xu=bu.extend({stream:y.z.literal(!0)}),Su=bu.extend({stream:y.z.literal(!1).optional()}),Cu=y.z.union([xu,Su]),wu=y.z.union([Kc.extend({organization_id:y.z.uuid()}),Kc.extend({agent_id:y.z.uuid()})]),Tu=vu.extend({messages:y.z.array(iu)}),Eu=qc(vu),Du=y.z.discriminatedUnion(`event`,[y.z.strictObject({event:y.z.literal(`chat.updated`),data:vu}),y.z.strictObject({event:y.z.literal(`message.created`),data:iu}),y.z.strictObject({event:y.z.literal(`message.updated`),data:iu}),y.z.strictObject({event:y.z.literal(`message.deleted`),data:y.z.object({id:y.z.uuid()})}),y.z.strictObject({event:y.z.literal(`message.chunk.added`),data:y.z.object({id:y.z.uuid(),chunk:y.z.custom()})})]),Ou=y.z.strictObject({event:y.z.literal(`chat.created`),data:Tu});var ku=class{constructor(e){this.client=e,this.runs=new hu(e),this.steps=new _l(e)}async create(e){let t={};e.stream&&(t.Accept=`text/event-stream`);let n=await this.client.request(`POST`,`/api/chats`,JSON.stringify(e),{headers:t});if(await K(n,201),e.stream){let e=n.headers.get(`Content-Type`);if(e!==`text/event-stream`)throw Error(`Expected text/event-stream, got ${e}`);if(!n.body)throw Error(`The stream endpoint did not return a body!`);let t=Xc(n,y.z.discriminatedUnion(`event`,[Du,Ou])),r=t.getReader(),{done:i,value:a}=await r.read();if(i)throw Error(`The stream ended before the chat.created event was received!`);if(a.event!==`chat.created`)throw Error(`Expected chat.created, got ${a.event}`);return r.releaseLock(),{...a.data,messages:a.data.messages,stream:t}}return n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e}`);return await K(t,200),t.json()}async list(e){let t=new URLSearchParams;`organization_id`in e&&e.organization_id?t.set(`organization_id`,e.organization_id):`agent_id`in e&&e.agent_id&&t.set(`agent_id`,e.agent_id),e.cursor&&t.set(`cursor`,e.cursor),e.limit&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/chats?${t.toString()}`);return await K(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/chats/${e}`);await K(t,204)}async stop(e){let t=await this.client.request(`POST`,`/api/chats/${e}/stop`);await K(t,200)}async stream(e,t={transport:`websocket`}){if(t?.transport===`websocket`)return this.streamWS(e,t?.signal);let n=await this.client.request(`GET`,`/api/chats/${e}/stream`,void 0,{abortSignal:t?.signal,headers:{Accept:`text/event-stream`}});return await K(n,200),Xc(n,Du)}streamWS(e,t){let n=this.client.websocket(`/api/chats/${e}/stream`),r=new ac,i=r.writable.getWriter(),a,o=new TextDecoder,s=!1,c=()=>{if(!s){s=!0,a?a.finally(()=>{i.close().catch(()=>{})}):i.close().catch(()=>{});try{n.close()}catch{}}};return t&&(t.aborted?c():t.addEventListener(`abort`,c,{once:!0})),n.addEventListener(`error`,()=>{c()}),n.addEventListener(`close`,()=>{c()}),n.addEventListener(`message`,e=>{if(s)return;let t;t=typeof e.data==`string`?e.data:o.decode(e.data),a=a?a.then(()=>{if(!s)return i.write(t).catch(()=>{})}):i.write(t).catch(()=>{})}),Zc(r.readable,Du)}};const Au=y.z.object({id:y.z.uuid(),organization_id:y.z.uuid(),role:zl,invited_by:y.z.uuid(),expires_at:y.z.date(),created_at:y.z.date(),updated_at:y.z.date(),reusable:y.z.boolean(),accepted_at:y.z.date().nullable(),email:y.z.string().email().nullable()}),ju=y.z.object({organization_id:y.z.uuid(),role:zl,email:y.z.string().email().optional(),reusable:y.z.boolean().optional()}),Mu=y.z.object({organization_id:y.z.uuid()}),Nu=y.z.object({organization_id:y.z.uuid(),invite_id:y.z.uuid()}),Pu=y.z.object({code:y.z.string()}),Fu=Pu.extend({invite_id:y.z.uuid()});var Iu=class{constructor(e){this.client=e}async create(e){let t=await this.client.request(`POST`,`/api/invites`,JSON.stringify(e));return await K(t,201),t.json()}async list(e){let t=await this.client.request(`GET`,`/api/invites?organization_id=${e.organization_id}`);return await K(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/invites/${e.invite_id}`);await K(t,204)}async accept(e){let t=await this.client.request(`POST`,`/api/invites/${e.invite_id}/accept`,JSON.stringify({code:e.code}));return await K(t,201),t.json()}},Lu=class{constructor(e){this.chats=new ku(this),this.runs=new hu(this),this.agents=new Ll(this),this.files=new Rl(this),this.organizations=new Jl(this),this.invites=new Iu(this),this.users=new $l(this),this.messages=new pu(this),this.baseURL=new URL(e?.baseURL??(globalThis.window===void 0?`https://blink.so`:window.location.origin)),this.fetch=e?.fetch,this.authToken=e?.authToken,this.auth=new ec(this,this.baseURL)}request(e,t,n,r){let i=new URL(t,this.baseURL),a=new Headers;if(this.authToken&&a.set(`Authorization`,`Bearer ${this.authToken}`),typeof n==`string`&&a.set(`Content-Type`,`application/json`),r?.headers)for(let[e,t]of Object.entries(r.headers))a.set(e,t);let o;if(r?.abortSignal&&r?.timeout)throw Error(`Cannot specify both abortSignal and timeout`);return r?.abortSignal&&(o=r.abortSignal),r?.timeout&&(o=AbortSignal.timeout(r.timeout)),(this.fetch??fetch)(i.toString(),{method:e,headers:a,body:n,signal:o})}websocket(e){let t=new URL(e,this.baseURL);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,new WebSocket(t.toString())}},Ru=W({"../../node_modules/@blink-sdk/compute-protocol/dist/schema-CZdQiIXB.cjs":(e=>{var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>function(){return t||(0,e[i(e)[0]])((t={exports:{}}).exports,t),t.exports},c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e));let u=G(`zod`);u=l(u);let d=(e,t)=>{let n=new Uint8Array(1+t.length);return n[0]=e,n.set(t,1),n},f=(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},p=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1)),m=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}({}),h=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}({}),g={[m.REQUEST]:u.z.string(),[m.PROXY_INIT]:u.z.object({method:u.z.string(),headers:u.z.record(u.z.string(),u.z.string()),url:u.z.string()}),[m.PROXY_BODY]:u.z.instanceof(Uint8Array),[m.PROXY_WEBSOCKET_MESSAGE]:u.z.object({type:u.z.enum([`text`,`binary`]),data:u.z.instanceof(Uint8Array)}),[m.PROXY_WEBSOCKET_CLOSE]:u.z.object({code:u.z.number().optional(),reason:u.z.string().optional()})},_={[h.RESPONSE]:u.z.string(),[h.NOTIFICATION]:u.z.string(),[h.PROXY_INIT]:u.z.object({status_code:u.z.number(),status_message:u.z.string(),headers:u.z.record(u.z.string(),u.z.string())}),[h.PROXY_DATA]:u.z.instanceof(Uint8Array),[h.PROXY_WEBSOCKET_MESSAGE]:u.z.instanceof(Uint8Array),[h.PROXY_WEBSOCKET_CLOSE]:u.z.object({code:u.z.number(),reason:u.z.string()})},v={[m.PROXY_INIT]:{method:u.z.string(),headers:u.z.record(u.z.string(),u.z.string()),url:u.z.string()}},y={process_execute:u.z.object({command:u.z.string(),args:u.z.array(u.z.string()),env:u.z.record(u.z.string(),u.z.string()).optional(),cwd:u.z.string().optional()}),process_send_input:u.z.object({pid:u.z.number(),data:u.z.string()}),process_wait:u.z.object({pid:u.z.number(),output_idle_timeout_ms:u.z.number().optional(),timeout_ms:u.z.number().optional()}),process_list:u.z.object({include_dead:u.z.boolean().optional()}),process_read_plain_output:u.z.object({pid:u.z.number(),start_line:u.z.number().optional(),end_line:u.z.number().optional()}),process_kill:u.z.object({pid:u.z.number(),signal:u.z.string().optional()}),set_env:u.z.object({env:u.z.record(u.z.string(),u.z.string())}),read_file:u.z.object({path:u.z.string(),line_start:u.z.number().optional(),line_end:u.z.number().optional()}),write_file:u.z.object({path:u.z.string(),content:u.z.string(),base64:u.z.boolean().optional(),mode:u.z.number().optional()}),read_directory:u.z.object({path:u.z.string()}),watch_directory:u.z.object({path:u.z.string()}),deploy_static_files:u.z.object({path:u.z.string()})},b=u.z.object({pid:u.z.number(),command:u.z.string(),args:u.z.array(u.z.string()),title:u.z.string().optional(),cwd:u.z.string(),env:u.z.record(u.z.string(),u.z.string()),exit_code:u.z.number().optional(),exit_signal:u.z.number().optional(),duration_ms:u.z.number().optional(),output_total_lines:u.z.number()}),x=b.extend({ansi_output:u.z.string(),plain_output:u.z.object({lines:u.z.array(u.z.string()),total_lines:u.z.number()})}),S={process_execute:u.z.object({pid:u.z.number()}),process_send_input:u.z.object({}),process_wait:x,process_list:u.z.object({processes:u.z.array(b)}),process_read_plain_output:u.z.object({lines:u.z.array(u.z.string()),total_lines:u.z.number(),duration_ms:u.z.number(),exit_code:u.z.number().optional(),exit_signal:u.z.number().optional()}),process_kill:u.z.object({}),set_env:u.z.object({}),read_file:u.z.object({total_lines:u.z.number(),lines_read:u.z.number(),start_line:u.z.number(),content:u.z.string(),mime_type:u.z.string()}),write_file:u.z.object({}),read_directory:u.z.object({entries:u.z.array(u.z.object({name:u.z.string(),type:u.z.enum([`file`,`directory`,`symlink`])}))}),watch_directory:u.z.object({}),deploy_static_files:u.z.object({deployment_id:u.z.string()})},C=u.z.object({type:u.z.enum([`create`,`update`,`delete`]),path:u.z.string()}),w=u.z.object({type:u.z.enum([`context`,`added`,`deleted`]),content:u.z.string(),oldLineNumber:u.z.number().optional(),newLineNumber:u.z.number().optional()}),T=u.z.object({oldStart:u.z.number(),oldLines:u.z.number(),newStart:u.z.number(),newLines:u.z.number(),lines:u.z.array(w)}),E=u.z.object({path:u.z.string(),status:u.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:u.z.string().optional(),insertions:u.z.number(),deletions:u.z.number(),chunks:u.z.array(T)}),D=u.z.object({totalFiles:u.z.number(),totalInsertions:u.z.number(),totalDeletions:u.z.number(),netChange:u.z.number(),startHash:u.z.string().optional(),currentHash:u.z.string().optional(),timespan:u.z.number(),files:u.z.array(E)}),O=u.z.object({path:u.z.string(),status:u.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:u.z.boolean()}),k=u.z.object({hash:u.z.string(),shortHash:u.z.string(),message:u.z.string(),author:u.z.string(),email:u.z.string(),date:u.z.date(),timestamp:u.z.date(),filesChanged:u.z.number(),insertions:u.z.number(),deletions:u.z.number(),commitDiff:u.z.array(E).optional()}),A=u.z.object({files:u.z.array(O),branch:u.z.string(),ahead:u.z.number(),behind:u.z.number(),timestamp:u.z.date(),sessionDiff:D.optional(),workingDirectoryDiff:D.optional(),newCommits:u.z.array(k),currentCommit:u.z.object({hash:u.z.string(),shortHash:u.z.string(),message:u.z.string(),author:u.z.string(),date:u.z.date()}).optional(),diffSkipped:u.z.boolean().optional(),payloadTruncated:u.z.boolean().optional(),estimatedSizeKB:u.z.number().optional()}),j=u.z.object({debounceDelay:u.z.number().optional(),gitStatusInterval:u.z.number().optional(),ignoreDotfiles:u.z.boolean().optional(),ignored:u.z.array(u.z.string()).optional(),watchGit:u.z.boolean().optional(),includeDiffs:u.z.boolean().optional(),maxDiffFiles:u.z.number().optional(),maxPayloadSizeKB:u.z.number().optional(),truncateLargeDiffs:u.z.boolean().optional()}),M={process_status:u.z.object({status:b}),process_output:u.z.object({pid:u.z.number(),output:u.z.string()}),file_change:u.z.object({changes:u.z.array(C)}),git_status:A};Object.defineProperty(e,`ClientMessageSchema`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`ClientMessageType`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,`DiffChunkSchema`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(e,`DiffLineSchema`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`DiffSummarySchema`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`FileChangeEventSchema`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`FileDiffSchema`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`GitCommitEventSchema`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`GitFileStatusSchema`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,`GitStatusEventSchema`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(e,`NotificationSchema`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(e,`ProcessStatusSchema`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`ProcessWaitSchema`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(e,`ProxySchema`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`RequestSchema`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`ResponseSchema`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`ServerMessageSchema`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`ServerMessageType`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(e,`WatchOptionsSchema`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,`__commonJS`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,`__toESM`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`createMessagePayload`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`createWebSocketMessagePayload`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,`parseWebSocketMessagePayload`,{enumerable:!0,get:function(){return p}})})}),zu=W({"../../node_modules/ws/lib/constants.js":((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:()=>{}}})}),Bu=W({"../../node_modules/ws/lib/buffer-util.js":((e,t)=>{let{EMPTY_BUFFER:n}=zu(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=G(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})}),Vu=W({"../../node_modules/ws/lib/limiter.js":((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])}}}})}),Hu=W({"../../node_modules/ws/lib/permessage-deflate.js":((e,t)=>{let n=G(`zlib`),r=Bu(),i=Vu(),{kStatusCode:a}=zu(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!p){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;p=new i(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})}),Uu=W({"../../node_modules/ws/lib/validation.js":((e,t)=>{let{isUtf8:n}=G(`buffer`),{hasBlob:r}=zu(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=G(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})}),Wu=W({"../../node_modules/ws/lib/receiver.js":((e,t)=>{let{Writable:n}=G(`stream`),r=Hu(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=zu(),{concat:c,toArrayBuffer:l,unmask:u}=Bu(),{isValidStatusCode:d,isValidUTF8:f}=Uu(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let t=this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`);e(t);return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(!this._fragmented){let t=this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let t=this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`);e(t);return}if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`);e(t);return}}else{let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){let t=this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`);e(t);return}}else if(this._masked){let t=this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`);e(t);return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){let t=this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`);e(t);return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);e(t);return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let e=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);t(e);return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){let t=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);e(t);return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){let e=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);t(e);return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})}),Gu=W({"../../node_modules/ws/lib/sender.js":((e,t)=>{let{Duplex:n}=G(`stream`),{randomFillSync:r}=G(`crypto`),i=Hu(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=zu(),{isBlob:c,isValidStatusCode:l}=Uu(),{mask:u,toBuffer:d}=Bu(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})}),Ku=W({"../../node_modules/ws/lib/event-target.js":((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=zu(),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)}})}),qu=W({"../../node_modules/ws/lib/extension.js":((e,t)=>{let{tokenChars:n}=Uu();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}})}),Ju=W({"../../node_modules/ws/lib/websocket.js":((e,t)=>{let n=G(`events`),r=G(`https`),i=G(`http`),a=G(`net`),o=G(`tls`),{randomBytes:s,createHash:c}=G(`crypto`),{Duplex:l,Readable:u}=G(`stream`),{URL:d}=G(`url`),f=Hu(),p=Wu(),m=Gu(),{isBlob:h}=Uu(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=zu(),{EventTarget:{addEventListener:w,removeEventListener:T}}=Ku(),{format:E,parse:D}=qu(),{toBuffer:O}=Bu(),k=Symbol(`kAborted`),A=[8,13],j=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),ee(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,R),i.on(`drain`,ne),i.on(`error`,z),i.on(`message`,B),i.on(`ping`,ie),i.on(`pong`,ae),a.onerror=se,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,V),t.on(`data`,le),t.on(`end`,ue),t.on(`error`,de),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(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())}),ce(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){L(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||_,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){L(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||_,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){L(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||_,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){I(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),N.prototype.addEventListener=w,N.prototype.removeEventListener=T,t.exports=N;function ee(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:A[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!A.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${A.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;P(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),_=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?te:F),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=E({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!M.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{I(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[k]||(x=e._req=null,P(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){I(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{let t=SyntaxError(`Invalid URL: ${i}`);P(e,t);return}ee(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||I(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){I(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+v).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){I(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){I(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){I(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=D(u)}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){I(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{I(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function P(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function F(e){return e.path=e.socketPath,a.connect(e)}function te(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function I(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,I),t.setHeader?(t[k]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(P,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function L(e,t,n){if(t){let n=h(t)?t.size:O(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${j[e.readyState]})`);process.nextTick(n,t)}}function R(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,le),process.nextTick(oe,n._socket),e===1005?n.close():n.close(e,t))}function ne(){let e=this[S];e.isPaused||e._socket.resume()}function z(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,le),process.nextTick(oe,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function re(){this[S].emitClose()}function B(e,t){this[S].emit(`message`,e,t)}function ie(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function ae(e){this[S].emit(`pong`,e)}function oe(e){e.resume()}function se(e){let t=this[S];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,ce(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ce(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function V(){let e=this[S];this.removeListener(`close`,V),this.removeListener(`data`,le),this.removeListener(`end`,ue),e._readyState=N.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,re),e._receiver.on(`finish`,re))}function le(e){this[S]._receiver.write(e)||this.pause()}function ue(){let e=this[S];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function de(){let e=this[S];this.removeListener(`error`,de),this.on(`error`,C),e&&(e._readyState=N.CLOSING,this.destroy())}})}),Yu=W({"../../node_modules/ws/lib/stream.js":((e,t)=>{Ju();let{Duplex:n}=G(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})}),Xu=W({"../../node_modules/ws/lib/subprotocol.js":((e,t)=>{let{tokenChars:n}=Uu();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}})}),Zu=W({"../../node_modules/ws/lib/websocket-server.js":((e,t)=>{let n=G(`events`),r=G(`http`),{Duplex:i}=G(`stream`),{createHash:a}=G(`crypto`),o=qu(),s=Hu(),c=Xu(),l=Ju(),{GUID:u,kWebSocket:d}=zu(),f=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=p(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(m,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,h);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){_(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){_(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!f.test(i)){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){g(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{_(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let p=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&p!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(p);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{_(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return g(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return g(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[d])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return g(i,503);let f=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+u).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(f.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});f.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,f,r),i.write(f.concat(`\r
|
|
22
22
|
`).join(`\r
|
|
23
23
|
`)),i.removeListener(`error`,h),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(m,this)})),l(p,r)}};function p(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function m(e){e._state=2,e.emit(`close`)}function h(){this.destroy()}function g(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
|
|
24
24
|
`)+`\r
|
|
25
25
|
\r
|
|
26
|
-
`+n)}function _(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,_),e.emit(`wsClientError`,r,n,t)}else g(n,r,i,a)}})}),Wu=W({"../../node_modules/ws/index.js":((e,t)=>{let n=Bu();n.createWebSocketStream=Vu(),n.Server=Uu(),n.Receiver=Iu(),n.Sender=Lu(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})}),Gu=W({"../../node_modules/@blink-sdk/compute-protocol/dist/server-BAzD0QDI.cjs":(e=>{var t,n,r,i;let a=Au(),o=G(`node:fs/promises`);o=a.__toESM(o);let s=G(`module`);s=a.__toESM(s);let c=G(`fs/promises`);c=a.__toESM(c);let l=G(`child_process`);l=a.__toESM(l);let u=Wu();u=a.__toESM(u);let d=G(`node:fs`);d=a.__toESM(d);var f=class{constructor(){this.listeners=[]}get event(){return e=>(this.listeners.push(e),{dispose:()=>{this.listeners=this.listeners.filter(t=>t!==e)}})}emit(e){for(let t=this.listeners.length-1;t>=0;t--)this.listeners[t]?.(e)}dispose(){this.listeners=[]}};let p=function(e){return e[e.DATA=0]=`DATA`,e[e.CLOSE=1]=`CLOSE`,e[e.ERROR=2]=`ERROR`,e}({}),m=function(e){return e[e.NEW=1]=`NEW`,e}({});var h=(t=class{static acquire(e){for(let t of this.COMMON_SIZES)if(t>=e){let e=this.pools.get(t);if(e&&e.length>0)return e.pop();break}return new Uint8Array(e)}static release(e){let t=e.length;for(let n of this.COMMON_SIZES)if(n===t){let t=this.pools.get(n);t&&t.length<this.MAX_POOL_SIZE&&t.push(e);break}}},t.MAX_POOL_SIZE=100,t.COMMON_SIZES=[64,256,1024,4096,16384],t.pools=new Map,(()=>{for(let e of t.COMMON_SIZES)t.pools.set(e,[])})(),t),g=(n=class e{static encode(e){let t=e.payload.length;if(t>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${t} > ${this.MAX_FRAME_SIZE}`);let n=this.HEADER_SIZE+t,r=h.acquire(n),i=e.streamId<<8|e.type<<4|e.flags&15;return r[0]=i>>>24&255,r[1]=i>>>16&255,r[2]=i>>>8&255,r[3]=i&255,t>0&&r.set(e.payload,this.HEADER_SIZE),r.length===n?r:r.subarray(0,n)}static encodeTyped(t,n,r,i,a){let o=1+a.length;if(o>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${o} > ${this.MAX_FRAME_SIZE}`);let s=this.HEADER_SIZE+o,c=h.acquire(s),l=t<<8|n<<4|r&15;return c[0]=l>>>24&255,c[1]=l>>>16&255,c[2]=l>>>8&255,c[3]=l&255,c[e.HEADER_SIZE]=i&255,a.length>0&&c.set(a,e.HEADER_SIZE+1),c.length===s?c:c.subarray(0,s)}static decode(t){if(t.length<e.HEADER_SIZE)throw Error(`Invalid frame: too short (${t.length} < ${e.HEADER_SIZE})`);let n=t[0]<<24|t[1]<<16|t[2]<<8|t[3],r=n>>>8,i=n&255,a=i>>>4,o=i&15,s=t.length>e.HEADER_SIZE?t.subarray(e.HEADER_SIZE):new Uint8Array;return{streamId:r,type:a,flags:o,payload:s}}static releaseBuffer(e){h.release(e)}static getMaxPayloadSize(){return e.MAX_FRAME_SIZE}},n.HEADER_SIZE=4,n.MAX_FRAME_SIZE=1024*1024-n.HEADER_SIZE,n),_=class{constructor(e,t,n){this._disposed=!1,this.send=t,this.sendTypedCb=n,this._id=e}get id(){return this._id}get onData(){return this._onData||=new f,this._onData.event}get onClose(){return this._onClose||=new f,this._onClose.event}get onError(){return this._onError||=new f,this._onError.event}write(e,t=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let n=g.getMaxPayloadSize();if(e.length<=n){this.send({streamId:this.id,type:p.DATA,flags:t?m.NEW:0,payload:e});return}let r=0,i=!0;for(;r<e.length;){let a=e.length-r,o=a>n?n:a,s=e.subarray(r,r+o);this.send({streamId:this.id,type:p.DATA,flags:t&&i?m.NEW:0,payload:s}),r+=o,i=!1}}writeTyped(e,t,n=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);if(!this.sendTypedCb){let r=new Uint8Array(1+t.length);r[0]=e&255,t.length&&r.set(t,1),this.write(r,n);return}let r=g.getMaxPayloadSize()-1;if(t.length<=r){this.sendTypedCb(this.id,n?m.NEW:0,e,t);return}let i=0,a=!0;for(;i<t.length;){let o=t.length-i,s=o>r?r:o,c=t.subarray(i,i+s);this.sendTypedCb(this.id,n&&a?m.NEW:0,e,c),i+=s,a=!1}}close(){this._disposed||(this.send({streamId:this.id,type:p.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(e){this._disposed||this.send({streamId:this.id,type:p.ERROR,flags:0,payload:new TextEncoder().encode(e)})}_handleFrame(e){if(!this._disposed)switch(e.type){case p.DATA:this._onData?.emit(e.payload);break;case p.CLOSE:this._onClose?.emit(),this._dispose();break;case p.ERROR:let t=new TextDecoder().decode(e.payload);this._onError?.emit(t),this._dispose();break}}_dispose(){this._disposed||(this._disposed=!0,this._onData?.dispose(),this._onClose?.dispose(),this._onError?.dispose(),this._onData=void 0,this._onClose=void 0,this._onError=void 0)}_reset(e,t,n){this._dispose(),this._id=e,this.send=t,this.sendTypedCb=n,this._disposed=!1}get createdByClient(){return this.id%2==1}get disposed(){return this._disposed}},v=(r=class{static acquire(e,t,n){let r=this.pool.pop();return r?(r._reset(e,t,n),r):new _(e,t,n)}static release(e){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(e)}},r.MAX_POOL_SIZE=200,r.pool=[],r),y=class{constructor(e){this._onNextStreamIDChange=new f,this.onNextStreamIDChange=this._onNextStreamIDChange.event,this._onStream=new f,this.onStream=this._onStream.event,this.streams=[],this.streamCount=0,this.nextStreamId=1,this.nextStreamId=e.initialNextStreamID??(e.isClient?1:2),this.send=e.send,this.releaseAfterSend=!!e.releaseAfterSend}getStream(e){return this.streams[e]}createStream(e){e===void 0&&(e=this.nextStreamId,this.nextStreamId+=2,this._onNextStreamIDChange.emit(this.nextStreamId));let t=this.streams[e];if(t&&!t.disposed)throw Error(`Stream ${e} already exists`);let n=v.acquire(e,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r));return this.streams[e]=n,this.streamCount++,n}sendFrame(e){let t=g.encode(e);try{this.send(t)}finally{this.releaseAfterSend&&g.releaseBuffer(t)}}sendFrameTyped(e,t,n,r){let i=g.encodeTyped(e,p.DATA,n,t,r);try{this.send(i)}finally{this.releaseAfterSend&&g.releaseBuffer(i)}}handleMessage(e){this.handleFrame(g.decode(e))}handleFrame(e){let t=this.streams[e.streamId];(!t||t.disposed)&&(t=v.acquire(e.streamId,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r)),this.streams[e.streamId]=t,this.streamCount++,this._onStream.emit(t)),t._handleFrame(e),(e.type===p.CLOSE||e.type===p.ERROR)&&(this.streams[e.streamId]=void 0,this.streamCount--,v.release(t))}get activeStreamCount(){return this.streamCount}dispose(){for(let e of this.streams)e&&!e.disposed&&(e.close(),v.release(e));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}},b=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},x=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},S=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new b;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new x;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new b;return n}},C=class extends S{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},w=class extends C{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},T=class extends S{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new b;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function E(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new T(t):new w(t)}catch(t){if(t instanceof TypeError)return new T(e.getReader());throw t}}var D=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new b;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new b;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new b;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new b;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}},O=class extends D{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new b;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof b)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new b}return r}async ignore(e){let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},k=class extends D{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new b;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function A(e,t){let n=E(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new O(n,r)}function j(e,t){return new k(e,t)}let M={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},N={};for(let[e,t]of Object.entries(M))N[t]=Number.parseInt(e);function ee(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?P(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return F(e);case`ascii`:return te(e);case`latin1`:case`iso-8859-1`:return I(e);case`windows-1252`:return L(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function P(e){let t=``,n=0;for(;n<e.length;){let r=e[n++];if(r<128)t+=String.fromCharCode(r);else if(r<224){let i=e[n++]&63;t+=String.fromCharCode((r&31)<<6|i)}else if(r<240){let i=e[n++]&63,a=e[n++]&63;t+=String.fromCharCode((r&15)<<12|i<<6|a)}else{let i=e[n++]&63,a=e[n++]&63,o=e[n++]&63,s=(r&7)<<18|i<<12|a<<6|o;s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(s&1023))}}return t}function F(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function te(e){return String.fromCharCode(...e.map(e=>e&127))}function I(e){return String.fromCharCode(...e)}function L(e){let t=``;for(let n of e)n>=128&&n<=159&&M[n]?t+=M[n]:t+=String.fromCharCode(n);return t}function R(e){return new DataView(e.buffer,e.byteOffset)}let ne={len:1,get(e,t){return R(e).getUint8(t)},put(e,t,n){return R(e).setUint8(t,n),t+1}},z={len:2,get(e,t){return R(e).getUint16(t,!0)},put(e,t,n){return R(e).setUint16(t,n,!0),t+2}},re={len:2,get(e,t){return R(e).getUint16(t)},put(e,t,n){return R(e).setUint16(t,n),t+2}},B={len:4,get(e,t){return R(e).getUint32(t,!0)},put(e,t,n){return R(e).setUint32(t,n,!0),t+4}},ie={len:4,get(e,t){return R(e).getUint32(t)},put(e,t,n){return R(e).setUint32(t,n),t+4}},ae={len:4,get(e,t){return R(e).getInt32(t)},put(e,t,n){return R(e).setInt32(t,n),t+4}},oe={len:8,get(e,t){return R(e).getBigUint64(t,!0)},put(e,t,n){return R(e).setBigUint64(t,n,!0),t+8}};var se=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return ee(n,this.encoding)}},ce=(0,s.createRequire)(`/`);try{ce(`worker_threads`).Worker}catch{}var V=Uint8Array,le=Uint16Array,ue=Int32Array,de=new V([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fe=new V([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),pe=new V([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),me=function(e,t){for(var n=new le(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new ue(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},he=me(de,2),ge=he.b,_e=he.r;ge[28]=258,_e[258]=28;var ve=me(fe,0),ye=ve.b;ve.r;for(var be=new le(32768),H=0;H<32768;++H){var xe=(H&43690)>>1|(H&21845)<<1;xe=(xe&52428)>>2|(xe&13107)<<2,xe=(xe&61680)>>4|(xe&3855)<<4,be[H]=((xe&65280)>>8|(xe&255)<<8)>>1}for(var Se=(function(e,t,n){for(var r=e.length,i=0,a=new le(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new le(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new le(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[be[d]>>c]=l}else for(s=new le(r),i=0;i<r;++i)e[i]&&(s[i]=be[o[e[i]-1]++]>>15-e[i]);return s}),Ce=new V(288),H=0;H<144;++H)Ce[H]=8;for(var H=144;H<256;++H)Ce[H]=9;for(var H=256;H<280;++H)Ce[H]=7;for(var H=280;H<288;++H)Ce[H]=8;for(var we=new V(32),H=0;H<32;++H)we[H]=5;var Te=Se(Ce,9,1),Ee=Se(we,5,1),De=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Oe=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},ke=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Ae=function(e){return(e+7)/8|0},je=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new V(e.subarray(t,n))},Me=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],U=function(e,t,n){var r=Error(t||Me[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,U),!n)throw r;return r},Ne=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new V(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new V(i*3));var l=function(e){var t=n.length;if(e>t){var r=new V(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=Oe(e,d,1);var v=Oe(e,d+1,3);if(d+=3,v)if(v==1)p=Te,m=Ee,h=9,g=5;else if(v==2){var y=Oe(e,d,31)+257,b=Oe(e,d+10,15)+4,x=y+Oe(e,d+5,31)+1;d+=14;for(var S=new V(x),C=new V(19),w=0;w<b;++w)C[pe[w]]=Oe(e,d+w*3,7);d+=b*3;for(var T=De(C),E=(1<<T)-1,D=Se(C,T,1),w=0;w<x;){var O=D[Oe(e,d,E)];d+=O&15;var k=O>>4;if(k<16)S[w++]=k;else{var A=0,j=0;for(k==16?(j=3+Oe(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+Oe(e,d,7),d+=3):k==18&&(j=11+Oe(e,d,127),d+=7);j--;)S[w++]=A}}var M=S.subarray(0,y),N=S.subarray(y);h=De(M),g=De(N),p=Se(M,h,1),m=Se(N,g,1)}else U(1);else{var k=Ae(d)+4,ee=e[k-4]|e[k-3]<<8,P=k+ee;if(P>i){c&&U(0);break}s&&l(f+ee),n.set(e.subarray(k,P),f),t.b=f+=ee,t.p=d=P*8,t.f=u;continue}if(d>_){c&&U(0);break}}s&&l(f+131072);for(var F=(1<<h)-1,te=(1<<g)-1,I=d;;I=d){var A=p[ke(e,d)&F],L=A>>4;if(d+=A&15,d>_){c&&U(0);break}if(A||U(2),L<256)n[f++]=L;else if(L==256){I=d,p=null;break}else{var R=L-254;if(L>264){var w=L-257,ne=de[w];R=Oe(e,d,(1<<ne)-1)+ge[w],d+=ne}var z=m[ke(e,d)&te],re=z>>4;z||U(3),d+=z&15;var N=ye[re];if(re>3){var ne=fe[re];N+=ke(e,d)&(1<<ne)-1,d+=ne}if(d>_){c&&U(0);break}s&&l(f+131072);var B=f+R;if(f<N){var ie=a-N,ae=Math.min(N,B);for(ie+f<0&&U(3);f<ae;++f)n[f]=r[ie+f]}for(;f<B;++f)n[f]=n[f-N]}}t.l=p,t.p=I,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?je(n,0,f):n.subarray(0,f)},Pe=new V(0),Fe=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&U(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},Ie=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},Le=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&U(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&U(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function Re(e,t){return Ne(e,{i:2},t&&t.out,t&&t.dictionary)}function ze(e,t){var n=Fe(e);return n+8>e.length&&U(6,`invalid gzip data`),Ne(e.subarray(n,-8),{i:2},t&&t.out||new V(Ie(e)),t&&t.dictionary)}function Be(e,t){return Ne(e.subarray(Le(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function Ve(e,t){return e[0]==31&&e[1]==139&&e[2]==8?ze(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?Re(e,t):Be(e,t)}var He=typeof TextDecoder<`u`&&new TextDecoder;try{He.decode(Pe,{stream:!0})}catch{}var Ue=a.__commonJS({"../../node_modules/ms/index.js":((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})}),We=a.__commonJS({"../../node_modules/debug/src/common.js":((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Ue(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})}),Ge=a.__commonJS({"../../node_modules/debug/src/browser.js":((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=We()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),Ke=a.__commonJS({"../../node_modules/has-flag/index.js":((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})}),qe=a.__commonJS({"../../node_modules/supports-color/index.js":((e,t)=>{let n=G(`os`),r=G(`tty`),i=Ke(),{env:a}=process,o;i(`no-color`)||i(`no-colors`)||i(`color=false`)||i(`color=never`)?o=0:(i(`color`)||i(`colors`)||i(`color=true`)||i(`color=always`))&&(o=1),`FORCE_COLOR`in a&&(o=a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(parseInt(a.FORCE_COLOR,10),3));function s(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(e,t){if(o===0)return 0;if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2;if(e&&!t&&o===void 0)return 0;let r=o||0;if(a.TERM===`dumb`)return r;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in a)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:r;if(`TEAMCITY_VERSION`in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in a){let e=parseInt((a.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(a.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||`COLORTERM`in a?1:r}function l(e){let t=c(e,e&&e.isTTY);return s(t)}t.exports={supportsColor:l,stdout:s(c(!0,r.isatty(1))),stderr:s(c(!0,r.isatty(2)))}})}),Je=a.__commonJS({"../../node_modules/debug/src/node.js":((e,t)=>{let n=G(`tty`),r=G(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=qe();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
26
|
+
`+n)}function _(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,_),e.emit(`wsClientError`,r,n,t)}else g(n,r,i,a)}})}),Qu=W({"../../node_modules/ws/index.js":((e,t)=>{let n=Ju();n.createWebSocketStream=Yu(),n.Server=Zu(),n.Receiver=Wu(),n.Sender=Gu(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})}),$u=W({"../../node_modules/@blink-sdk/compute-protocol/dist/server-BAzD0QDI.cjs":(e=>{var t,n,r,i;let a=Ru(),o=G(`node:fs/promises`);o=a.__toESM(o);let s=G(`module`);s=a.__toESM(s);let c=G(`fs/promises`);c=a.__toESM(c);let l=G(`child_process`);l=a.__toESM(l);let u=Qu();u=a.__toESM(u);let d=G(`node:fs`);d=a.__toESM(d);var f=class{constructor(){this.listeners=[]}get event(){return e=>(this.listeners.push(e),{dispose:()=>{this.listeners=this.listeners.filter(t=>t!==e)}})}emit(e){for(let t=this.listeners.length-1;t>=0;t--)this.listeners[t]?.(e)}dispose(){this.listeners=[]}};let p=function(e){return e[e.DATA=0]=`DATA`,e[e.CLOSE=1]=`CLOSE`,e[e.ERROR=2]=`ERROR`,e}({}),m=function(e){return e[e.NEW=1]=`NEW`,e}({});var h=(t=class{static acquire(e){for(let t of this.COMMON_SIZES)if(t>=e){let e=this.pools.get(t);if(e&&e.length>0)return e.pop();break}return new Uint8Array(e)}static release(e){let t=e.length;for(let n of this.COMMON_SIZES)if(n===t){let t=this.pools.get(n);t&&t.length<this.MAX_POOL_SIZE&&t.push(e);break}}},t.MAX_POOL_SIZE=100,t.COMMON_SIZES=[64,256,1024,4096,16384],t.pools=new Map,(()=>{for(let e of t.COMMON_SIZES)t.pools.set(e,[])})(),t),g=(n=class e{static encode(e){let t=e.payload.length;if(t>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${t} > ${this.MAX_FRAME_SIZE}`);let n=this.HEADER_SIZE+t,r=h.acquire(n),i=e.streamId<<8|e.type<<4|e.flags&15;return r[0]=i>>>24&255,r[1]=i>>>16&255,r[2]=i>>>8&255,r[3]=i&255,t>0&&r.set(e.payload,this.HEADER_SIZE),r.length===n?r:r.subarray(0,n)}static encodeTyped(t,n,r,i,a){let o=1+a.length;if(o>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${o} > ${this.MAX_FRAME_SIZE}`);let s=this.HEADER_SIZE+o,c=h.acquire(s),l=t<<8|n<<4|r&15;return c[0]=l>>>24&255,c[1]=l>>>16&255,c[2]=l>>>8&255,c[3]=l&255,c[e.HEADER_SIZE]=i&255,a.length>0&&c.set(a,e.HEADER_SIZE+1),c.length===s?c:c.subarray(0,s)}static decode(t){if(t.length<e.HEADER_SIZE)throw Error(`Invalid frame: too short (${t.length} < ${e.HEADER_SIZE})`);let n=t[0]<<24|t[1]<<16|t[2]<<8|t[3],r=n>>>8,i=n&255,a=i>>>4,o=i&15,s=t.length>e.HEADER_SIZE?t.subarray(e.HEADER_SIZE):new Uint8Array;return{streamId:r,type:a,flags:o,payload:s}}static releaseBuffer(e){h.release(e)}static getMaxPayloadSize(){return e.MAX_FRAME_SIZE}},n.HEADER_SIZE=4,n.MAX_FRAME_SIZE=1024*1024-n.HEADER_SIZE,n),_=class{constructor(e,t,n){this._disposed=!1,this.send=t,this.sendTypedCb=n,this._id=e}get id(){return this._id}get onData(){return this._onData||=new f,this._onData.event}get onClose(){return this._onClose||=new f,this._onClose.event}get onError(){return this._onError||=new f,this._onError.event}write(e,t=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let n=g.getMaxPayloadSize();if(e.length<=n){this.send({streamId:this.id,type:p.DATA,flags:t?m.NEW:0,payload:e});return}let r=0,i=!0;for(;r<e.length;){let a=e.length-r,o=a>n?n:a,s=e.subarray(r,r+o);this.send({streamId:this.id,type:p.DATA,flags:t&&i?m.NEW:0,payload:s}),r+=o,i=!1}}writeTyped(e,t,n=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);if(!this.sendTypedCb){let r=new Uint8Array(1+t.length);r[0]=e&255,t.length&&r.set(t,1),this.write(r,n);return}let r=g.getMaxPayloadSize()-1;if(t.length<=r){this.sendTypedCb(this.id,n?m.NEW:0,e,t);return}let i=0,a=!0;for(;i<t.length;){let o=t.length-i,s=o>r?r:o,c=t.subarray(i,i+s);this.sendTypedCb(this.id,n&&a?m.NEW:0,e,c),i+=s,a=!1}}close(){this._disposed||(this.send({streamId:this.id,type:p.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(e){this._disposed||this.send({streamId:this.id,type:p.ERROR,flags:0,payload:new TextEncoder().encode(e)})}_handleFrame(e){if(!this._disposed)switch(e.type){case p.DATA:this._onData?.emit(e.payload);break;case p.CLOSE:this._onClose?.emit(),this._dispose();break;case p.ERROR:let t=new TextDecoder().decode(e.payload);this._onError?.emit(t),this._dispose();break}}_dispose(){this._disposed||(this._disposed=!0,this._onData?.dispose(),this._onClose?.dispose(),this._onError?.dispose(),this._onData=void 0,this._onClose=void 0,this._onError=void 0)}_reset(e,t,n){this._dispose(),this._id=e,this.send=t,this.sendTypedCb=n,this._disposed=!1}get createdByClient(){return this.id%2==1}get disposed(){return this._disposed}},v=(r=class{static acquire(e,t,n){let r=this.pool.pop();return r?(r._reset(e,t,n),r):new _(e,t,n)}static release(e){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(e)}},r.MAX_POOL_SIZE=200,r.pool=[],r),y=class{constructor(e){this._onNextStreamIDChange=new f,this.onNextStreamIDChange=this._onNextStreamIDChange.event,this._onStream=new f,this.onStream=this._onStream.event,this.streams=[],this.streamCount=0,this.nextStreamId=1,this.nextStreamId=e.initialNextStreamID??(e.isClient?1:2),this.send=e.send,this.releaseAfterSend=!!e.releaseAfterSend}getStream(e){return this.streams[e]}createStream(e){e===void 0&&(e=this.nextStreamId,this.nextStreamId+=2,this._onNextStreamIDChange.emit(this.nextStreamId));let t=this.streams[e];if(t&&!t.disposed)throw Error(`Stream ${e} already exists`);let n=v.acquire(e,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r));return this.streams[e]=n,this.streamCount++,n}sendFrame(e){let t=g.encode(e);try{this.send(t)}finally{this.releaseAfterSend&&g.releaseBuffer(t)}}sendFrameTyped(e,t,n,r){let i=g.encodeTyped(e,p.DATA,n,t,r);try{this.send(i)}finally{this.releaseAfterSend&&g.releaseBuffer(i)}}handleMessage(e){this.handleFrame(g.decode(e))}handleFrame(e){let t=this.streams[e.streamId];(!t||t.disposed)&&(t=v.acquire(e.streamId,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r)),this.streams[e.streamId]=t,this.streamCount++,this._onStream.emit(t)),t._handleFrame(e),(e.type===p.CLOSE||e.type===p.ERROR)&&(this.streams[e.streamId]=void 0,this.streamCount--,v.release(t))}get activeStreamCount(){return this.streamCount}dispose(){for(let e of this.streams)e&&!e.disposed&&(e.close(),v.release(e));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}},b=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},x=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},S=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new b;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new x;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new b;return n}},C=class extends S{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},w=class extends C{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},T=class extends S{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new b;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function E(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new T(t):new w(t)}catch(t){if(t instanceof TypeError)return new T(e.getReader());throw t}}var D=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new b;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new b;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new b;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new b;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}},O=class extends D{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new b;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof b)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new b}return r}async ignore(e){let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},k=class extends D{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new b;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function A(e,t){let n=E(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new O(n,r)}function j(e,t){return new k(e,t)}let M={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},N={};for(let[e,t]of Object.entries(M))N[t]=Number.parseInt(e);function ee(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?P(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return F(e);case`ascii`:return te(e);case`latin1`:case`iso-8859-1`:return I(e);case`windows-1252`:return L(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function P(e){let t=``,n=0;for(;n<e.length;){let r=e[n++];if(r<128)t+=String.fromCharCode(r);else if(r<224){let i=e[n++]&63;t+=String.fromCharCode((r&31)<<6|i)}else if(r<240){let i=e[n++]&63,a=e[n++]&63;t+=String.fromCharCode((r&15)<<12|i<<6|a)}else{let i=e[n++]&63,a=e[n++]&63,o=e[n++]&63,s=(r&7)<<18|i<<12|a<<6|o;s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(s&1023))}}return t}function F(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function te(e){return String.fromCharCode(...e.map(e=>e&127))}function I(e){return String.fromCharCode(...e)}function L(e){let t=``;for(let n of e)n>=128&&n<=159&&M[n]?t+=M[n]:t+=String.fromCharCode(n);return t}function R(e){return new DataView(e.buffer,e.byteOffset)}let ne={len:1,get(e,t){return R(e).getUint8(t)},put(e,t,n){return R(e).setUint8(t,n),t+1}},z={len:2,get(e,t){return R(e).getUint16(t,!0)},put(e,t,n){return R(e).setUint16(t,n,!0),t+2}},re={len:2,get(e,t){return R(e).getUint16(t)},put(e,t,n){return R(e).setUint16(t,n),t+2}},B={len:4,get(e,t){return R(e).getUint32(t,!0)},put(e,t,n){return R(e).setUint32(t,n,!0),t+4}},ie={len:4,get(e,t){return R(e).getUint32(t)},put(e,t,n){return R(e).setUint32(t,n),t+4}},ae={len:4,get(e,t){return R(e).getInt32(t)},put(e,t,n){return R(e).setInt32(t,n),t+4}},oe={len:8,get(e,t){return R(e).getBigUint64(t,!0)},put(e,t,n){return R(e).setBigUint64(t,n,!0),t+8}};var se=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return ee(n,this.encoding)}},ce=(0,s.createRequire)(`/`);try{ce(`worker_threads`).Worker}catch{}var V=Uint8Array,le=Uint16Array,ue=Int32Array,de=new V([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fe=new V([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),pe=new V([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),me=function(e,t){for(var n=new le(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new ue(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},he=me(de,2),ge=he.b,_e=he.r;ge[28]=258,_e[258]=28;var ve=me(fe,0),ye=ve.b;ve.r;for(var be=new le(32768),H=0;H<32768;++H){var xe=(H&43690)>>1|(H&21845)<<1;xe=(xe&52428)>>2|(xe&13107)<<2,xe=(xe&61680)>>4|(xe&3855)<<4,be[H]=((xe&65280)>>8|(xe&255)<<8)>>1}for(var Se=(function(e,t,n){for(var r=e.length,i=0,a=new le(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new le(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new le(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[be[d]>>c]=l}else for(s=new le(r),i=0;i<r;++i)e[i]&&(s[i]=be[o[e[i]-1]++]>>15-e[i]);return s}),Ce=new V(288),H=0;H<144;++H)Ce[H]=8;for(var H=144;H<256;++H)Ce[H]=9;for(var H=256;H<280;++H)Ce[H]=7;for(var H=280;H<288;++H)Ce[H]=8;for(var we=new V(32),H=0;H<32;++H)we[H]=5;var Te=Se(Ce,9,1),Ee=Se(we,5,1),De=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Oe=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},ke=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Ae=function(e){return(e+7)/8|0},je=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new V(e.subarray(t,n))},Me=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],U=function(e,t,n){var r=Error(t||Me[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,U),!n)throw r;return r},Ne=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new V(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new V(i*3));var l=function(e){var t=n.length;if(e>t){var r=new V(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=Oe(e,d,1);var v=Oe(e,d+1,3);if(d+=3,v)if(v==1)p=Te,m=Ee,h=9,g=5;else if(v==2){var y=Oe(e,d,31)+257,b=Oe(e,d+10,15)+4,x=y+Oe(e,d+5,31)+1;d+=14;for(var S=new V(x),C=new V(19),w=0;w<b;++w)C[pe[w]]=Oe(e,d+w*3,7);d+=b*3;for(var T=De(C),E=(1<<T)-1,D=Se(C,T,1),w=0;w<x;){var O=D[Oe(e,d,E)];d+=O&15;var k=O>>4;if(k<16)S[w++]=k;else{var A=0,j=0;for(k==16?(j=3+Oe(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+Oe(e,d,7),d+=3):k==18&&(j=11+Oe(e,d,127),d+=7);j--;)S[w++]=A}}var M=S.subarray(0,y),N=S.subarray(y);h=De(M),g=De(N),p=Se(M,h,1),m=Se(N,g,1)}else U(1);else{var k=Ae(d)+4,ee=e[k-4]|e[k-3]<<8,P=k+ee;if(P>i){c&&U(0);break}s&&l(f+ee),n.set(e.subarray(k,P),f),t.b=f+=ee,t.p=d=P*8,t.f=u;continue}if(d>_){c&&U(0);break}}s&&l(f+131072);for(var F=(1<<h)-1,te=(1<<g)-1,I=d;;I=d){var A=p[ke(e,d)&F],L=A>>4;if(d+=A&15,d>_){c&&U(0);break}if(A||U(2),L<256)n[f++]=L;else if(L==256){I=d,p=null;break}else{var R=L-254;if(L>264){var w=L-257,ne=de[w];R=Oe(e,d,(1<<ne)-1)+ge[w],d+=ne}var z=m[ke(e,d)&te],re=z>>4;z||U(3),d+=z&15;var N=ye[re];if(re>3){var ne=fe[re];N+=ke(e,d)&(1<<ne)-1,d+=ne}if(d>_){c&&U(0);break}s&&l(f+131072);var B=f+R;if(f<N){var ie=a-N,ae=Math.min(N,B);for(ie+f<0&&U(3);f<ae;++f)n[f]=r[ie+f]}for(;f<B;++f)n[f]=n[f-N]}}t.l=p,t.p=I,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?je(n,0,f):n.subarray(0,f)},Pe=new V(0),Fe=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&U(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},Ie=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},Le=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&U(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&U(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function Re(e,t){return Ne(e,{i:2},t&&t.out,t&&t.dictionary)}function ze(e,t){var n=Fe(e);return n+8>e.length&&U(6,`invalid gzip data`),Ne(e.subarray(n,-8),{i:2},t&&t.out||new V(Ie(e)),t&&t.dictionary)}function Be(e,t){return Ne(e.subarray(Le(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function Ve(e,t){return e[0]==31&&e[1]==139&&e[2]==8?ze(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?Re(e,t):Be(e,t)}var He=typeof TextDecoder<`u`&&new TextDecoder;try{He.decode(Pe,{stream:!0})}catch{}var Ue=a.__commonJS({"../../node_modules/ms/index.js":((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})}),We=a.__commonJS({"../../node_modules/debug/src/common.js":((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Ue(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})}),Ge=a.__commonJS({"../../node_modules/debug/src/browser.js":((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=We()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),Ke=a.__commonJS({"../../node_modules/has-flag/index.js":((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})}),qe=a.__commonJS({"../../node_modules/supports-color/index.js":((e,t)=>{let n=G(`os`),r=G(`tty`),i=Ke(),{env:a}=process,o;i(`no-color`)||i(`no-colors`)||i(`color=false`)||i(`color=never`)?o=0:(i(`color`)||i(`colors`)||i(`color=true`)||i(`color=always`))&&(o=1),`FORCE_COLOR`in a&&(o=a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(parseInt(a.FORCE_COLOR,10),3));function s(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(e,t){if(o===0)return 0;if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2;if(e&&!t&&o===void 0)return 0;let r=o||0;if(a.TERM===`dumb`)return r;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in a)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:r;if(`TEAMCITY_VERSION`in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in a){let e=parseInt((a.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(a.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||`COLORTERM`in a?1:r}function l(e){let t=c(e,e&&e.isTTY);return s(t)}t.exports={supportsColor:l,stdout:s(c(!0,r.isatty(1))),stderr:s(c(!0,r.isatty(2)))}})}),Je=a.__commonJS({"../../node_modules/debug/src/node.js":((e,t)=>{let n=G(`tty`),r=G(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=qe();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
27
27
|
`).join(`
|
|
28
28
|
`+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=o()+n+` `+e[0]}function o(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function s(...t){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...t)+`
|
|
29
29
|
`)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=We()(e);let{formatters:d}=t.exports;d.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split(`
|
|
@@ -36,143 +36,143 @@ Error message: ${rc(t)}`,cause:t}),this[_c]=!0,this.value=e}static isInstance(e)
|
|
|
36
36
|
`));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
|
|
37
37
|
`);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})}),Nt=a.__commonJS({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=jt(),a=Et(),o=Dt(),s=Mt(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})}),Pt=a.__commonJS({"../../node_modules/tar-stream/constants.js":((e,t)=>{let n={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=G(`fs`).constants||n}catch{t.exports=n}})}),Ft=a.__commonJS({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=jt(),a=Dt(),o=Pt(),s=Mt(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})}),It=a.__commonJS({"../../node_modules/tar-stream/index.js":(e=>{e.extract=Nt(),e.pack=Ft()})}),Lt=a.__toESM(It(),1);let Rt=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await o.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=Lt.pack(),i=async(e,t=``)=>{let n=await o.readdir(e,{withFileTypes:!0});for(let a of n){let n=`${e}/${a.name}`,s=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){r.entry({name:`${s}/`,type:`directory`}),await i(n,s);continue}if(a.isSymbolicLink?.()){let e=await o.readlink(n);r.entry({name:s,type:`symlink`,linkname:e});continue}if(a.isFile()){let e=await o.stat(n);await new Promise((t,i)=>{let a=(0,d.createReadStream)(n),o=r.entry({name:s,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&i(e)});a.on(`error`,i),a.on(`data`,e=>o.write(e)),a.on(`end`,()=>{o.end(),t()})});continue}}};(async()=>{try{await i(e),r.finalize()}catch(e){r.destroy(e)}})();let a=r,s=0,c=!1;return new ReadableStream({start(e){a.on(`data`,t=>{if(!c){if(s+=t.length,s>n){c=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${s} bytes.`));try{a.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),a.once(`error`,t=>{c||(c=!0,e.error(t instanceof Error?t:Error(String(t))))}),a.once(`end`,()=>{c||(c=!0,e.close())})},cancel(){try{a.destroy()}catch{}}})},zt=(e,t)=>e.length<=t?e:e.slice(e.length-t),Bt=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var Vt=class{constructor(e){this.decoder=new TextDecoder,this.encoder=new TextEncoder,this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new y({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new Ct({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=g.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case a.ClientMessageType.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case a.ClientMessageType.PROXY_INIT:{let t=a.ClientMessageSchema[a.ClientMessageType.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new u.WebSocket(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped(a.ServerMessageType.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(a.ServerMessageType.PROXY_WEBSOCKET_MESSAGE,a.createWebSocketMessagePayload(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(a.ServerMessageType.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case a.ClientMessageType.PROXY_WEBSOCKET_MESSAGE:{let e=a.parseWebSocketMessagePayload(n,this.decoder);r.send(e);break}case a.ClientMessageType.PROXY_WEBSOCKET_CLOSE:{let e=a.ClientMessageSchema[a.ClientMessageType.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case a.ClientMessageType.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r},o;o=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let s={};o.headers.forEach((e,t)=>{s[t]=e});let c={headers:s,status_code:o.status,status_message:o.statusText};e.writeTyped(a.ServerMessageType.PROXY_INIT,this.encoder.encode(JSON.stringify(c)));let l=o.headers.get(`content-length`),u=l?parseInt(l):0,d=g.getMaxPayloadSize()-1;if(u>=d){if(!o.body){e.close();return}let t=o.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(d,r.length-t),i=r.subarray(t,t+n);e.writeTyped(a.ServerMessageType.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else o.body&&await o.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(a.ServerMessageType.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=a.RequestSchema[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{let n=this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=Bt(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await Rt(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await c.readFile(t.payload.path),r=await ht(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
|
|
38
38
|
`),a=(t.payload.line_start??1)-1,o=t.payload.line_end??i.length,s=i.slice(a,o);this.sendResponse(e,{id:t.id,payload:{content:s.join(`
|
|
39
|
-
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await c.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await c.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await c.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await c.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(a.ServerMessageType.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([a.ServerMessageType.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=zt(this.processManager.readANSIOutput(i.pid),64e3),f=Bt(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};Object.defineProperty(e,`Multiplexer`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`Server`,{enumerable:!0,get:function(){return Vt}})})}),Ku=W({"../../node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{Au(),e.Server=Gu().Server})}),qu=class{constructor(e){this.client=e}listen(e){let t,n,r=!1,i=1e4,a=250,o=()=>{n&&=(clearTimeout(n),void 0)},s=()=>{if(r)return;o();let e=a*.2*Math.random(),t=Math.min(i,Math.floor(a+e));n=setTimeout(()=>{f()},t),a=Math.min(i,Math.floor(a*1.5))},c=()=>{a=250},{Server:l}=Ku(),u=new l({send:e=>{let n=t;!n||n.readyState!==WebSocket.OPEN||n.send(e)},fetchProxyRequest(t,n){return e.onRequest(new Request(t,{...n,duplex:n.body?`half`:void 0}))}}),d=t=>{t.binaryType=`arraybuffer`,t.addEventListener(`open`,()=>{r||(c(),e.onConnect?.())}),t.addEventListener(`close`,()=>{r||(e.onDisconnect?.(),s())}),t.addEventListener(`error`,n=>{try{e.onError?.(n)}catch{}try{t.close()}catch{}}),t.addEventListener(`message`,e=>{if(typeof e.data==`string`){console.warn(`Message skipped because it is not a buffer.`);return}try{u.handleMessage(new Uint8Array(e.data))}catch(e){console.error(`message handler error`,e);try{t.close(1011)}catch{}}})},f=()=>{if(!r)try{let n=this.client.websocket(`/api/devhook/${e.id}`);t=n,d(n)}catch(t){try{e.onError?.(t)}catch{}s()}};return f(),{dispose:()=>{if(r)return;r=!0,o();let e=t;t=void 0;try{e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3)}catch{}}}}};let Ju=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}({}),Yu=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}({});Ju.REQUEST,y.z.string(),Ju.PROXY_INIT,y.z.object({method:y.z.string(),headers:y.z.record(y.z.string(),y.z.string()),url:y.z.string()}),Ju.PROXY_BODY,y.z.instanceof(Uint8Array),Ju.PROXY_WEBSOCKET_MESSAGE,y.z.object({type:y.z.enum([`text`,`binary`]),data:y.z.instanceof(Uint8Array)}),Ju.PROXY_WEBSOCKET_CLOSE,y.z.object({code:y.z.number().optional(),reason:y.z.string().optional()}),Yu.RESPONSE,y.z.string(),Yu.NOTIFICATION,y.z.string(),Yu.PROXY_INIT,y.z.object({status_code:y.z.number(),status_message:y.z.string(),headers:y.z.record(y.z.string(),y.z.string())}),Yu.PROXY_DATA,y.z.instanceof(Uint8Array),Yu.PROXY_WEBSOCKET_MESSAGE,y.z.instanceof(Uint8Array),Yu.PROXY_WEBSOCKET_CLOSE,y.z.object({code:y.z.number(),reason:y.z.string()}),Ju.PROXY_INIT,y.z.string(),y.z.record(y.z.string(),y.z.string()),y.z.string(),y.z.object({command:y.z.string(),args:y.z.array(y.z.string()),env:y.z.record(y.z.string(),y.z.string()).optional(),cwd:y.z.string().optional()}),y.z.object({pid:y.z.number(),data:y.z.string()}),y.z.object({pid:y.z.number(),output_idle_timeout_ms:y.z.number().optional(),timeout_ms:y.z.number().optional()}),y.z.object({include_dead:y.z.boolean().optional()}),y.z.object({pid:y.z.number(),start_line:y.z.number().optional(),end_line:y.z.number().optional()}),y.z.object({pid:y.z.number(),signal:y.z.string().optional()}),y.z.object({env:y.z.record(y.z.string(),y.z.string())}),y.z.object({path:y.z.string(),line_start:y.z.number().optional(),line_end:y.z.number().optional()}),y.z.object({path:y.z.string(),content:y.z.string(),base64:y.z.boolean().optional(),mode:y.z.number().optional()}),y.z.object({path:y.z.string()}),y.z.object({path:y.z.string()}),y.z.object({path:y.z.string()});const Xu=y.z.object({pid:y.z.number(),command:y.z.string(),args:y.z.array(y.z.string()),title:y.z.string().optional(),cwd:y.z.string(),env:y.z.record(y.z.string(),y.z.string()),exit_code:y.z.number().optional(),exit_signal:y.z.number().optional(),duration_ms:y.z.number().optional(),output_total_lines:y.z.number()});Xu.extend({ansi_output:y.z.string(),plain_output:y.z.object({lines:y.z.array(y.z.string()),total_lines:y.z.number()})}),y.z.object({pid:y.z.number()}),y.z.object({}),y.z.object({processes:y.z.array(Xu)}),y.z.object({lines:y.z.array(y.z.string()),total_lines:y.z.number(),duration_ms:y.z.number(),exit_code:y.z.number().optional(),exit_signal:y.z.number().optional()}),y.z.object({}),y.z.object({}),y.z.object({total_lines:y.z.number(),lines_read:y.z.number(),start_line:y.z.number(),content:y.z.string(),mime_type:y.z.string()}),y.z.object({}),y.z.object({entries:y.z.array(y.z.object({name:y.z.string(),type:y.z.enum([`file`,`directory`,`symlink`])}))}),y.z.object({}),y.z.object({deployment_id:y.z.string()});const Zu=y.z.object({type:y.z.enum([`create`,`update`,`delete`]),path:y.z.string()}),Qu=y.z.object({type:y.z.enum([`context`,`added`,`deleted`]),content:y.z.string(),oldLineNumber:y.z.number().optional(),newLineNumber:y.z.number().optional()}),$u=y.z.object({oldStart:y.z.number(),oldLines:y.z.number(),newStart:y.z.number(),newLines:y.z.number(),lines:y.z.array(Qu)}),ed=y.z.object({path:y.z.string(),status:y.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:y.z.string().optional(),insertions:y.z.number(),deletions:y.z.number(),chunks:y.z.array($u)}),td=y.z.object({totalFiles:y.z.number(),totalInsertions:y.z.number(),totalDeletions:y.z.number(),netChange:y.z.number(),startHash:y.z.string().optional(),currentHash:y.z.string().optional(),timespan:y.z.number(),files:y.z.array(ed)}),nd=y.z.object({path:y.z.string(),status:y.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:y.z.boolean()}),rd=y.z.object({hash:y.z.string(),shortHash:y.z.string(),message:y.z.string(),author:y.z.string(),email:y.z.string(),date:y.z.date(),timestamp:y.z.date(),filesChanged:y.z.number(),insertions:y.z.number(),deletions:y.z.number(),commitDiff:y.z.array(ed).optional()});y.z.object({files:y.z.array(nd),branch:y.z.string(),ahead:y.z.number(),behind:y.z.number(),timestamp:y.z.date(),sessionDiff:td.optional(),workingDirectoryDiff:td.optional(),newCommits:y.z.array(rd),currentCommit:y.z.object({hash:y.z.string(),shortHash:y.z.string(),message:y.z.string(),author:y.z.string(),date:y.z.date()}).optional(),diffSkipped:y.z.boolean().optional(),payloadTruncated:y.z.boolean().optional(),estimatedSizeKB:y.z.number().optional()}),y.z.object({debounceDelay:y.z.number().optional(),gitStatusInterval:y.z.number().optional(),ignoreDotfiles:y.z.boolean().optional(),ignored:y.z.array(y.z.string()).optional(),watchGit:y.z.boolean().optional(),includeDiffs:y.z.boolean().optional(),maxDiffFiles:y.z.number().optional(),maxPayloadSizeKB:y.z.number().optional(),truncateLargeDiffs:y.z.boolean().optional()}),y.z.object({status:Xu}),y.z.object({pid:y.z.number(),output:y.z.string()}),y.z.object({changes:y.z.array(Zu)});var id=class{constructor({send:e,jwt:t,requestTimeoutMS:n}){this.notificationCallbacks=new Map,this.disposables=[],this.requestHandlers=new Map,this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}};y.z.object({}),y.z.object({id:y.z.string(),token:y.z.string()});var ad=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await K(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new id({send:e=>t.send(e)})}},od=class{constructor(e){this.client=e,this.compute=new ad(this.client)}},sd=class extends ku{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new qu(this),this.tools=new od(this)}},cd=e.__commonJSMin((e=>{e.__esModule=!0;function t(e){return i(e)===`boolean`}function n(e){return i(e)===`object`}function r(e){return i(e)===`string`}function i(e){return typeof e}function a(e){var i=e.meta,a=e.path,o=e.xdg;return{XDGAppPaths:new(function(){function e(s){s===void 0&&(s={});function c(t){return t===void 0&&(t={}),new e(t)}var l=n(s)?s:{name:s},u=l.suffix??``,d=l.isolated??!0,f=[l.name,i.pkgMainFilename(),i.mainFilename()],p=a.parse((f.find(function(e){return r(e)})??`$eval`)+u).name;c.$name=function(){return p},c.$isolated=function(){return d};function m(e){return e??={isolated:d},t(e)?e:e.isolated??d}function h(e){return m(e)?p:``}return c.cache=function(e){return a.join(o.cache(),h(e))},c.config=function(e){return a.join(o.config(),h(e))},c.data=function(e){return a.join(o.data(),h(e))},c.runtime=function(e){return o.runtime()?a.join(o.runtime(),h(e)):void 0},c.state=function(e){return a.join(o.state(),h(e))},c.configDirs=function(e){return o.configDirs().map(function(t){return a.join(t,h(e))})},c.dataDirs=function(e){return o.dataDirs().map(function(t){return a.join(t,h(e))})},c}return e}())}}e.Adapt=a})),ld=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){var n=e.env,r=e.osPaths,i=e.path,a=/^darwin$/i.test(e.process.platform),o=/^win/i.test(e.process.platform);function s(){return r.home()||r.temp()}function c(e,t){return e||i.join.apply(i,t)}var l=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`.local`,`share`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`.local`,`state`])}}},u=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`Library`,`Caches`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`Library`,`Preferences`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`Library`,`Application Support`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`Library`,`State`])}}},d=function(){function e(){return c(n.get(`APPDATA`),[s(),`AppData`,`Roaming`])}function t(){return c(n.get(`LOCALAPPDATA`),[s(),`AppData`,`Local`])}return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[t(),`xdg.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[e(),`xdg.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[e(),`xdg.data`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[t(),`xdg.state`])}}};return{XDG:new(function(){function e(){function r(){return new e}var s=a?u():o?d():l();return r.cache=s.cache,r.config=s.config,r.data=s.data,r.runtime=s.runtime,r.state=s.state,r.configDirs=function(){var e=n.get(`XDG_CONFIG_DIRS`);return t([s.config()],e?e.split(i.delimiter):[])},r.dataDirs=function(){var e=n.get(`XDG_DATA_DIRS`);return t([s.data()],e?e.split(i.delimiter):[])},r}return e}())}}e.Adapt=n})),ud=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){return!e}function r(e){var r=e.env,i=e.os,a=e.path,o=/^win/i.test(e.process.platform);function s(t){return t?e.path.normalize(e.path.join(t,`.`)):void 0}function c(){return o?function(){var e=[typeof i.homedir==`function`?i.homedir():void 0,r.get(`USERPROFILE`),r.get(`HOME`),r.get(`HOMEDRIVE`)||r.get(`HOMEPATH`)?a.join(r.get(`HOMEDRIVE`)||``,r.get(`HOMEPATH`)||``):void 0];return s(e.find(function(e){return!n(e)}))}():function(){return s((typeof i.homedir==`function`?i.homedir():void 0)||r.get(`HOME`))}()}function l(){function e(e,n){return e?a.join.apply(a,t([e],n)):void 0}function l(){var e=`/tmp`,t=[typeof i.tmpdir==`function`?i.tmpdir():void 0,r.get(`TMPDIR`),r.get(`TEMP`),r.get(`TMP`)];return s(t.find(function(e){return!n(e)}))||e}function u(){var t=`C:\\Temp`,a=[typeof i.tmpdir==`function`?i.tmpdir:function(){},function(){return r.get(`TEMP`)},function(){return r.get(`TMP`)},function(){return e(r.get(`LOCALAPPDATA`),[`Temp`])},function(){return e(c(),[`AppData`,`Local`,`Temp`])},function(){return e(r.get(`ALLUSERSPROFILE`),[`Temp`])},function(){return e(r.get(`SystemRoot`),[`Temp`])},function(){return e(r.get(`windir`),[`Temp`])},function(){return e(r.get(`SystemDrive`),[`\\`,`Temp`])}].find(function(e){return e&&!n(e())});return a&&s(a())||t}return o?u():l()}return{OSPaths:new(function(){function e(){function t(){return new e}return t.home=c,t.temp=l,t}return e}())}}e.Adapt=r})),dd=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};e.__esModule=!0;var i=r(require(`os`)),a=r(require(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:i,path:a,process}})),fd=e.__commonJSMin(((e,t)=>{var n=ud(),r=dd();t.exports=n.Adapt(r.adapter).OSPaths})),pd=e.__export({default:()=>gd}),md,hd,gd,_d=e.__esmMin((()=>{md=e.__toESM(fd()),hd=md.default,gd=hd})),vd=e.__commonJSMin((t=>{var n=t&&t.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=t&&t.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=t&&t.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};t.__esModule=!0;var o=i(require(`path`));t.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:a((_d(),e.__toCommonJS(pd))).default,path:o,process}})),yd=e.__commonJSMin(((e,t)=>{var n=ld(),r=vd();t.exports=n.Adapt(r.adapter).XDG})),bd=e.__export({default:()=>Sd}),xd,Sd,Cd=e.__esmMin((()=>{xd=e.__toESM(yd()),e.__reExport(bd,e.__toESM(yd())),Sd=xd.default})),wd=e.__commonJSMin((t=>{var n=t&&t.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=t&&t.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=t&&t.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};t.__esModule=!0;var o=i(require(`path`)),s=a((Cd(),e.__toCommonJS(bd)));t.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=(typeof require<`u`&&require!==null&&require.main?require.main:{filename:void 0}).filename;return(e===process.execArgv[0]?void 0:e)||(process._eval===void 0?process.argv[1]:void 0)},pkgMainFilename:function(){return process.pkg?process.execPath:void 0}},path:o,process,xdg:s.default}})),Td=e.__commonJSMin(((e,t)=>{var n=cd(),r=wd();t.exports=n.Adapt(r.adapter).XDGAppPaths})),Ed=e.__toESM(Td()),Dd=Ed.default;const Od=10,kd=(e=0)=>t=>`\u001B[${t+e}m`,Ad=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,jd=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,q={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Md=Object.keys(q.modifier),Nd=Object.keys(q.color),Pd=Object.keys(q.bgColor),Fd=[...Nd,...Pd];function Id(){let e=new Map;for(let[t,n]of Object.entries(q)){for(let[t,r]of Object.entries(n))q[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=q[t],e.set(r[0],r[1]);Object.defineProperty(q,t,{value:n,enumerable:!1})}return Object.defineProperty(q,`codes`,{value:e,enumerable:!1}),q.color.close=`\x1B[39m`,q.bgColor.close=`\x1B[49m`,q.color.ansi=kd(),q.color.ansi256=Ad(),q.color.ansi16m=jd(),q.bgColor.ansi=kd(10),q.bgColor.ansi256=Ad(10),q.bgColor.ansi16m=jd(10),Object.defineProperties(q,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>q.rgbToAnsi256(...q.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>q.ansi256ToAnsi(q.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>q.ansi256ToAnsi(q.hexToAnsi256(e)),enumerable:!1}}),q}const Ld=Id();var Rd=Ld;function zd(e,t=globalThis.Deno?globalThis.Deno.args:x.default.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}const{env:J}=x.default;let Bd;zd(`no-color`)||zd(`no-colors`)||zd(`color=false`)||zd(`color=never`)?Bd=0:(zd(`color`)||zd(`colors`)||zd(`color=true`)||zd(`color=always`))&&(Bd=1);function Vd(){if(`FORCE_COLOR`in J)return J.FORCE_COLOR===`true`?1:J.FORCE_COLOR===`false`?0:J.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(J.FORCE_COLOR,10),3)}function Hd(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Ud(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=Vd();r!==void 0&&(Bd=r);let i=n?Bd:r;if(i===0)return 0;if(n){if(zd(`color=16m`)||zd(`color=full`)||zd(`color=truecolor`))return 3;if(zd(`color=256`))return 2}if(`TF_BUILD`in J&&`AGENT_NAME`in J)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(J.TERM===`dumb`)return a;if(x.default.platform===`win32`){let e=S.default.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in J)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in J)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in J)||J.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in J)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(J.TEAMCITY_VERSION)?1:0;if(J.COLORTERM===`truecolor`||J.TERM===`xterm-kitty`||J.TERM===`xterm-ghostty`||J.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in J){let e=Number.parseInt((J.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(J.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(J.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(J.TERM)||`COLORTERM`in J?1:a}function Wd(e,t={}){let n=Ud(e,{streamIsTTY:e&&e.isTTY,...t});return Hd(n)}const Gd={stdout:Wd({isTTY:C.default.isatty(1)}),stderr:Wd({isTTY:C.default.isatty(2)})};var Kd=Gd;function qd(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function Jd(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
39
|
+
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await c.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await c.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await c.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await c.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(a.ServerMessageType.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([a.ServerMessageType.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=zt(this.processManager.readANSIOutput(i.pid),64e3),f=Bt(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}};Object.defineProperty(e,`Multiplexer`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`Server`,{enumerable:!0,get:function(){return Vt}})})}),ed=W({"../../node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{Ru(),e.Server=$u().Server})}),td=class{constructor(e){this.client=e}listen(e){let t,n,r=!1,i=1e4,a=250,o=()=>{n&&=(clearTimeout(n),void 0)},s=()=>{if(r)return;o();let e=a*.2*Math.random(),t=Math.min(i,Math.floor(a+e));n=setTimeout(()=>{f()},t),a=Math.min(i,Math.floor(a*1.5))},c=()=>{a=250},{Server:l}=ed(),u=new l({send:e=>{let n=t;!n||n.readyState!==WebSocket.OPEN||n.send(e)},fetchProxyRequest(t,n){return e.onRequest(new Request(t,{...n,duplex:n.body?`half`:void 0}))}}),d=t=>{t.binaryType=`arraybuffer`,t.addEventListener(`open`,()=>{r||(c(),e.onConnect?.())}),t.addEventListener(`close`,()=>{r||(e.onDisconnect?.(),s())}),t.addEventListener(`error`,n=>{try{e.onError?.(n)}catch{}try{t.close()}catch{}}),t.addEventListener(`message`,e=>{if(typeof e.data==`string`){console.warn(`Message skipped because it is not a buffer.`);return}try{u.handleMessage(new Uint8Array(e.data))}catch(e){console.error(`message handler error`,e);try{t.close(1011)}catch{}}})},f=()=>{if(!r)try{let n=this.client.websocket(`/api/devhook/${e.id}`);t=n,d(n)}catch(t){try{e.onError?.(t)}catch{}s()}};return f(),{dispose:()=>{if(r)return;r=!0,o();let e=t;t=void 0;try{e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3)}catch{}}}}};let nd=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}({}),rd=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}({});nd.REQUEST,y.z.string(),nd.PROXY_INIT,y.z.object({method:y.z.string(),headers:y.z.record(y.z.string(),y.z.string()),url:y.z.string()}),nd.PROXY_BODY,y.z.instanceof(Uint8Array),nd.PROXY_WEBSOCKET_MESSAGE,y.z.object({type:y.z.enum([`text`,`binary`]),data:y.z.instanceof(Uint8Array)}),nd.PROXY_WEBSOCKET_CLOSE,y.z.object({code:y.z.number().optional(),reason:y.z.string().optional()}),rd.RESPONSE,y.z.string(),rd.NOTIFICATION,y.z.string(),rd.PROXY_INIT,y.z.object({status_code:y.z.number(),status_message:y.z.string(),headers:y.z.record(y.z.string(),y.z.string())}),rd.PROXY_DATA,y.z.instanceof(Uint8Array),rd.PROXY_WEBSOCKET_MESSAGE,y.z.instanceof(Uint8Array),rd.PROXY_WEBSOCKET_CLOSE,y.z.object({code:y.z.number(),reason:y.z.string()}),nd.PROXY_INIT,y.z.string(),y.z.record(y.z.string(),y.z.string()),y.z.string(),y.z.object({command:y.z.string(),args:y.z.array(y.z.string()),env:y.z.record(y.z.string(),y.z.string()).optional(),cwd:y.z.string().optional()}),y.z.object({pid:y.z.number(),data:y.z.string()}),y.z.object({pid:y.z.number(),output_idle_timeout_ms:y.z.number().optional(),timeout_ms:y.z.number().optional()}),y.z.object({include_dead:y.z.boolean().optional()}),y.z.object({pid:y.z.number(),start_line:y.z.number().optional(),end_line:y.z.number().optional()}),y.z.object({pid:y.z.number(),signal:y.z.string().optional()}),y.z.object({env:y.z.record(y.z.string(),y.z.string())}),y.z.object({path:y.z.string(),line_start:y.z.number().optional(),line_end:y.z.number().optional()}),y.z.object({path:y.z.string(),content:y.z.string(),base64:y.z.boolean().optional(),mode:y.z.number().optional()}),y.z.object({path:y.z.string()}),y.z.object({path:y.z.string()}),y.z.object({path:y.z.string()});const id=y.z.object({pid:y.z.number(),command:y.z.string(),args:y.z.array(y.z.string()),title:y.z.string().optional(),cwd:y.z.string(),env:y.z.record(y.z.string(),y.z.string()),exit_code:y.z.number().optional(),exit_signal:y.z.number().optional(),duration_ms:y.z.number().optional(),output_total_lines:y.z.number()});id.extend({ansi_output:y.z.string(),plain_output:y.z.object({lines:y.z.array(y.z.string()),total_lines:y.z.number()})}),y.z.object({pid:y.z.number()}),y.z.object({}),y.z.object({processes:y.z.array(id)}),y.z.object({lines:y.z.array(y.z.string()),total_lines:y.z.number(),duration_ms:y.z.number(),exit_code:y.z.number().optional(),exit_signal:y.z.number().optional()}),y.z.object({}),y.z.object({}),y.z.object({total_lines:y.z.number(),lines_read:y.z.number(),start_line:y.z.number(),content:y.z.string(),mime_type:y.z.string()}),y.z.object({}),y.z.object({entries:y.z.array(y.z.object({name:y.z.string(),type:y.z.enum([`file`,`directory`,`symlink`])}))}),y.z.object({}),y.z.object({deployment_id:y.z.string()});const ad=y.z.object({type:y.z.enum([`create`,`update`,`delete`]),path:y.z.string()}),od=y.z.object({type:y.z.enum([`context`,`added`,`deleted`]),content:y.z.string(),oldLineNumber:y.z.number().optional(),newLineNumber:y.z.number().optional()}),sd=y.z.object({oldStart:y.z.number(),oldLines:y.z.number(),newStart:y.z.number(),newLines:y.z.number(),lines:y.z.array(od)}),cd=y.z.object({path:y.z.string(),status:y.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:y.z.string().optional(),insertions:y.z.number(),deletions:y.z.number(),chunks:y.z.array(sd)}),ld=y.z.object({totalFiles:y.z.number(),totalInsertions:y.z.number(),totalDeletions:y.z.number(),netChange:y.z.number(),startHash:y.z.string().optional(),currentHash:y.z.string().optional(),timespan:y.z.number(),files:y.z.array(cd)}),ud=y.z.object({path:y.z.string(),status:y.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:y.z.boolean()}),dd=y.z.object({hash:y.z.string(),shortHash:y.z.string(),message:y.z.string(),author:y.z.string(),email:y.z.string(),date:y.z.date(),timestamp:y.z.date(),filesChanged:y.z.number(),insertions:y.z.number(),deletions:y.z.number(),commitDiff:y.z.array(cd).optional()});y.z.object({files:y.z.array(ud),branch:y.z.string(),ahead:y.z.number(),behind:y.z.number(),timestamp:y.z.date(),sessionDiff:ld.optional(),workingDirectoryDiff:ld.optional(),newCommits:y.z.array(dd),currentCommit:y.z.object({hash:y.z.string(),shortHash:y.z.string(),message:y.z.string(),author:y.z.string(),date:y.z.date()}).optional(),diffSkipped:y.z.boolean().optional(),payloadTruncated:y.z.boolean().optional(),estimatedSizeKB:y.z.number().optional()}),y.z.object({debounceDelay:y.z.number().optional(),gitStatusInterval:y.z.number().optional(),ignoreDotfiles:y.z.boolean().optional(),ignored:y.z.array(y.z.string()).optional(),watchGit:y.z.boolean().optional(),includeDiffs:y.z.boolean().optional(),maxDiffFiles:y.z.number().optional(),maxPayloadSizeKB:y.z.number().optional(),truncateLargeDiffs:y.z.boolean().optional()}),y.z.object({status:id}),y.z.object({pid:y.z.number(),output:y.z.string()}),y.z.object({changes:y.z.array(ad)});var fd=class{constructor({send:e,jwt:t,requestTimeoutMS:n}){this.notificationCallbacks=new Map,this.disposables=[],this.requestHandlers=new Map,this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}};y.z.object({}),y.z.object({id:y.z.string(),token:y.z.string()});var pd=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await K(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new fd({send:e=>t.send(e)})}},md=class{constructor(e){this.client=e,this.compute=new pd(this.client)}},hd=class extends Lu{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new td(this),this.tools=new md(this)}},gd=e.__commonJSMin((e=>{e.__esModule=!0;function t(e){return i(e)===`boolean`}function n(e){return i(e)===`object`}function r(e){return i(e)===`string`}function i(e){return typeof e}function a(e){var i=e.meta,a=e.path,o=e.xdg;return{XDGAppPaths:new(function(){function e(s){s===void 0&&(s={});function c(t){return t===void 0&&(t={}),new e(t)}var l=n(s)?s:{name:s},u=l.suffix??``,d=l.isolated??!0,f=[l.name,i.pkgMainFilename(),i.mainFilename()],p=a.parse((f.find(function(e){return r(e)})??`$eval`)+u).name;c.$name=function(){return p},c.$isolated=function(){return d};function m(e){return e??={isolated:d},t(e)?e:e.isolated??d}function h(e){return m(e)?p:``}return c.cache=function(e){return a.join(o.cache(),h(e))},c.config=function(e){return a.join(o.config(),h(e))},c.data=function(e){return a.join(o.data(),h(e))},c.runtime=function(e){return o.runtime()?a.join(o.runtime(),h(e)):void 0},c.state=function(e){return a.join(o.state(),h(e))},c.configDirs=function(e){return o.configDirs().map(function(t){return a.join(t,h(e))})},c.dataDirs=function(e){return o.dataDirs().map(function(t){return a.join(t,h(e))})},c}return e}())}}e.Adapt=a})),_d=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){var n=e.env,r=e.osPaths,i=e.path,a=/^darwin$/i.test(e.process.platform),o=/^win/i.test(e.process.platform);function s(){return r.home()||r.temp()}function c(e,t){return e||i.join.apply(i,t)}var l=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`.local`,`share`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`.local`,`state`])}}},u=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`Library`,`Caches`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`Library`,`Preferences`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`Library`,`Application Support`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`Library`,`State`])}}},d=function(){function e(){return c(n.get(`APPDATA`),[s(),`AppData`,`Roaming`])}function t(){return c(n.get(`LOCALAPPDATA`),[s(),`AppData`,`Local`])}return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[t(),`xdg.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[e(),`xdg.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[e(),`xdg.data`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[t(),`xdg.state`])}}};return{XDG:new(function(){function e(){function r(){return new e}var s=a?u():o?d():l();return r.cache=s.cache,r.config=s.config,r.data=s.data,r.runtime=s.runtime,r.state=s.state,r.configDirs=function(){var e=n.get(`XDG_CONFIG_DIRS`);return t([s.config()],e?e.split(i.delimiter):[])},r.dataDirs=function(){var e=n.get(`XDG_DATA_DIRS`);return t([s.data()],e?e.split(i.delimiter):[])},r}return e}())}}e.Adapt=n})),vd=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!0;function n(e){return!e}function r(e){var r=e.env,i=e.os,a=e.path,o=/^win/i.test(e.process.platform);function s(t){return t?e.path.normalize(e.path.join(t,`.`)):void 0}function c(){return o?function(){var e=[typeof i.homedir==`function`?i.homedir():void 0,r.get(`USERPROFILE`),r.get(`HOME`),r.get(`HOMEDRIVE`)||r.get(`HOMEPATH`)?a.join(r.get(`HOMEDRIVE`)||``,r.get(`HOMEPATH`)||``):void 0];return s(e.find(function(e){return!n(e)}))}():function(){return s((typeof i.homedir==`function`?i.homedir():void 0)||r.get(`HOME`))}()}function l(){function e(e,n){return e?a.join.apply(a,t([e],n)):void 0}function l(){var e=`/tmp`,t=[typeof i.tmpdir==`function`?i.tmpdir():void 0,r.get(`TMPDIR`),r.get(`TEMP`),r.get(`TMP`)];return s(t.find(function(e){return!n(e)}))||e}function u(){var t=`C:\\Temp`,a=[typeof i.tmpdir==`function`?i.tmpdir:function(){},function(){return r.get(`TEMP`)},function(){return r.get(`TMP`)},function(){return e(r.get(`LOCALAPPDATA`),[`Temp`])},function(){return e(c(),[`AppData`,`Local`,`Temp`])},function(){return e(r.get(`ALLUSERSPROFILE`),[`Temp`])},function(){return e(r.get(`SystemRoot`),[`Temp`])},function(){return e(r.get(`windir`),[`Temp`])},function(){return e(r.get(`SystemDrive`),[`\\`,`Temp`])}].find(function(e){return e&&!n(e())});return a&&s(a())||t}return o?u():l()}return{OSPaths:new(function(){function e(){function t(){return new e}return t.home=c,t.temp=l,t}return e}())}}e.Adapt=r})),yd=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};e.__esModule=!0;var i=r(require(`os`)),a=r(require(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:i,path:a,process}})),bd=e.__commonJSMin(((e,t)=>{var n=vd(),r=yd();t.exports=n.Adapt(r.adapter).OSPaths})),xd=e.__export({default:()=>wd}),Sd,Cd,wd,Td=e.__esmMin((()=>{Sd=e.__toESM(bd()),Cd=Sd.default,wd=Cd})),Ed=e.__commonJSMin((t=>{var n=t&&t.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=t&&t.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=t&&t.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};t.__esModule=!0;var o=i(require(`path`));t.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:a((Td(),e.__toCommonJS(xd))).default,path:o,process}})),Dd=e.__commonJSMin(((e,t)=>{var n=_d(),r=Ed();t.exports=n.Adapt(r.adapter).XDG})),Od=e.__export({default:()=>Ad}),kd,Ad,jd=e.__esmMin((()=>{kd=e.__toESM(Dd()),e.__reExport(Od,e.__toESM(Dd())),Ad=kd.default})),Md=e.__commonJSMin((t=>{var n=t&&t.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=t&&t.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),i=t&&t.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},a=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};t.__esModule=!0;var o=i(require(`path`)),s=a((jd(),e.__toCommonJS(Od)));t.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=(typeof require<`u`&&require!==null&&require.main?require.main:{filename:void 0}).filename;return(e===process.execArgv[0]?void 0:e)||(process._eval===void 0?process.argv[1]:void 0)},pkgMainFilename:function(){return process.pkg?process.execPath:void 0}},path:o,process,xdg:s.default}})),Nd=e.__commonJSMin(((e,t)=>{var n=gd(),r=Md();t.exports=n.Adapt(r.adapter).XDGAppPaths})),Pd=e.__toESM(Nd()),Fd=Pd.default;const Id=10,Ld=(e=0)=>t=>`\u001B[${t+e}m`,Rd=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,zd=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,q={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},Bd=Object.keys(q.modifier),Vd=Object.keys(q.color),Hd=Object.keys(q.bgColor),Ud=[...Vd,...Hd];function Wd(){let e=new Map;for(let[t,n]of Object.entries(q)){for(let[t,r]of Object.entries(n))q[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=q[t],e.set(r[0],r[1]);Object.defineProperty(q,t,{value:n,enumerable:!1})}return Object.defineProperty(q,`codes`,{value:e,enumerable:!1}),q.color.close=`\x1B[39m`,q.bgColor.close=`\x1B[49m`,q.color.ansi=Ld(),q.color.ansi256=Rd(),q.color.ansi16m=zd(),q.bgColor.ansi=Ld(10),q.bgColor.ansi256=Rd(10),q.bgColor.ansi16m=zd(10),Object.defineProperties(q,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>q.rgbToAnsi256(...q.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>q.ansi256ToAnsi(q.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>q.ansi256ToAnsi(q.hexToAnsi256(e)),enumerable:!1}}),q}const Gd=Wd();var Kd=Gd;function qd(e,t=globalThis.Deno?globalThis.Deno.args:x.default.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}const{env:J}=x.default;let Jd;qd(`no-color`)||qd(`no-colors`)||qd(`color=false`)||qd(`color=never`)?Jd=0:(qd(`color`)||qd(`colors`)||qd(`color=true`)||qd(`color=always`))&&(Jd=1);function Yd(){if(`FORCE_COLOR`in J)return J.FORCE_COLOR===`true`?1:J.FORCE_COLOR===`false`?0:J.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(J.FORCE_COLOR,10),3)}function Xd(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Zd(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=Yd();r!==void 0&&(Jd=r);let i=n?Jd:r;if(i===0)return 0;if(n){if(qd(`color=16m`)||qd(`color=full`)||qd(`color=truecolor`))return 3;if(qd(`color=256`))return 2}if(`TF_BUILD`in J&&`AGENT_NAME`in J)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(J.TERM===`dumb`)return a;if(x.default.platform===`win32`){let e=S.default.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in J)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in J)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in J)||J.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in J)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(J.TEAMCITY_VERSION)?1:0;if(J.COLORTERM===`truecolor`||J.TERM===`xterm-kitty`||J.TERM===`xterm-ghostty`||J.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in J){let e=Number.parseInt((J.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(J.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(J.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(J.TERM)||`COLORTERM`in J?1:a}function Qd(e,t={}){let n=Zd(e,{streamIsTTY:e&&e.isTTY,...t});return Xd(n)}const $d={stdout:Qd({isTTY:C.default.isatty(1)}),stderr:Qd({isTTY:C.default.isatty(2)})};var ef=$d;function tf(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function nf(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
40
40
|
`:`
|
|
41
41
|
`)+n,i=r+1,r=e.indexOf(`
|
|
42
|
-
`,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:
|
|
43
|
-
`);return a!==-1&&(t=Jd(t,i,r,a)),r+t+i};Object.defineProperties(af.prototype,tf);const ff=af(),pf=af({level:Xd?Xd.level:0});var mf=ff,hf=e.__commonJSMin(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}})),gf=e.__commonJSMin(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})),_f=e.__toESM(hf(),1),vf=e.__toESM(gf(),1);function yf({onlyFirst:e=!1}={}){let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}const bf=yf();function xf(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(bf,``)}function Sf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var Cf={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(e){var t=e.charCodeAt(0),n=e.length==2?e.charCodeAt(1):0,r=t;return 55296<=t&&t<=56319&&56320<=n&&n<=57343&&(t&=1023,n&=1023,r=t<<10|n,r+=65536),r==12288||65281<=r&&r<=65376||65504<=r&&r<=65510?`F`:r==8361||65377<=r&&r<=65470||65474<=r&&r<=65479||65482<=r&&r<=65487||65490<=r&&r<=65495||65498<=r&&r<=65500||65512<=r&&r<=65518?`H`:4352<=r&&r<=4447||4515<=r&&r<=4519||4602<=r&&r<=4607||9001<=r&&r<=9002||11904<=r&&r<=11929||11931<=r&&r<=12019||12032<=r&&r<=12245||12272<=r&&r<=12283||12289<=r&&r<=12350||12353<=r&&r<=12438||12441<=r&&r<=12543||12549<=r&&r<=12589||12593<=r&&r<=12686||12688<=r&&r<=12730||12736<=r&&r<=12771||12784<=r&&r<=12830||12832<=r&&r<=12871||12880<=r&&r<=13054||13056<=r&&r<=19903||19968<=r&&r<=42124||42128<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||55216<=r&&r<=55238||55243<=r&&r<=55291||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65106||65108<=r&&r<=65126||65128<=r&&r<=65131||110592<=r&&r<=110593||127488<=r&&r<=127490||127504<=r&&r<=127546||127552<=r&&r<=127560||127568<=r&&r<=127569||131072<=r&&r<=194367||177984<=r&&r<=196605||196608<=r&&r<=262141?`W`:32<=r&&r<=126||162<=r&&r<=163||165<=r&&r<=166||r==172||r==175||10214<=r&&r<=10221||10629<=r&&r<=10630?`Na`:r==161||r==164||167<=r&&r<=168||r==170||173<=r&&r<=174||176<=r&&r<=180||182<=r&&r<=186||188<=r&&r<=191||r==198||r==208||215<=r&&r<=216||222<=r&&r<=225||r==230||232<=r&&r<=234||236<=r&&r<=237||r==240||242<=r&&r<=243||247<=r&&r<=250||r==252||r==254||r==257||r==273||r==275||r==283||294<=r&&r<=295||r==299||305<=r&&r<=307||r==312||319<=r&&r<=322||r==324||328<=r&&r<=331||r==333||338<=r&&r<=339||358<=r&&r<=359||r==363||r==462||r==464||r==466||r==468||r==470||r==472||r==474||r==476||r==593||r==609||r==708||r==711||713<=r&&r<=715||r==717||r==720||728<=r&&r<=731||r==733||r==735||768<=r&&r<=879||913<=r&&r<=929||931<=r&&r<=937||945<=r&&r<=961||963<=r&&r<=969||r==1025||1040<=r&&r<=1103||r==1105||r==8208||8211<=r&&r<=8214||8216<=r&&r<=8217||8220<=r&&r<=8221||8224<=r&&r<=8226||8228<=r&&r<=8231||r==8240||8242<=r&&r<=8243||r==8245||r==8251||r==8254||r==8308||r==8319||8321<=r&&r<=8324||r==8364||r==8451||r==8453||r==8457||r==8467||r==8470||8481<=r&&r<=8482||r==8486||r==8491||8531<=r&&r<=8532||8539<=r&&r<=8542||8544<=r&&r<=8555||8560<=r&&r<=8569||r==8585||8592<=r&&r<=8601||8632<=r&&r<=8633||r==8658||r==8660||r==8679||r==8704||8706<=r&&r<=8707||8711<=r&&r<=8712||r==8715||r==8719||r==8721||r==8725||r==8730||8733<=r&&r<=8736||r==8739||r==8741||8743<=r&&r<=8748||r==8750||8756<=r&&r<=8759||8764<=r&&r<=8765||r==8776||r==8780||r==8786||8800<=r&&r<=8801||8804<=r&&r<=8807||8810<=r&&r<=8811||8814<=r&&r<=8815||8834<=r&&r<=8835||8838<=r&&r<=8839||r==8853||r==8857||r==8869||r==8895||r==8978||9312<=r&&r<=9449||9451<=r&&r<=9547||9552<=r&&r<=9587||9600<=r&&r<=9615||9618<=r&&r<=9621||9632<=r&&r<=9633||9635<=r&&r<=9641||9650<=r&&r<=9651||9654<=r&&r<=9655||9660<=r&&r<=9661||9664<=r&&r<=9665||9670<=r&&r<=9672||r==9675||9678<=r&&r<=9681||9698<=r&&r<=9701||r==9711||9733<=r&&r<=9734||r==9737||9742<=r&&r<=9743||9748<=r&&r<=9749||r==9756||r==9758||r==9792||r==9794||9824<=r&&r<=9825||9827<=r&&r<=9829||9831<=r&&r<=9834||9836<=r&&r<=9837||r==9839||9886<=r&&r<=9887||9918<=r&&r<=9919||9924<=r&&r<=9933||9935<=r&&r<=9953||r==9955||9960<=r&&r<=9983||r==10045||r==10071||10102<=r&&r<=10111||11093<=r&&r<=11097||12872<=r&&r<=12879||57344<=r&&r<=63743||65024<=r&&r<=65039||r==65533||127232<=r&&r<=127242||127248<=r&&r<=127277||127280<=r&&r<=127337||127344<=r&&r<=127386||917760<=r&&r<=917999||983040<=r&&r<=1048573||1048576<=r&&r<=1114109?`A`:`N`},t.characterLength=function(e){var t=this.eastAsianWidth(e);return t==`F`||t==`W`||t==`A`?2:1};function n(e){return e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}t.length=function(e){for(var t=n(e),r=0,i=0;i<t.length;i++)r+=this.characterLength(t[i]);return r},t.slice=function(e,r,i){textLen=t.length(e),r||=0,i||=1,r<0&&(r=textLen+r),i<0&&(i=textLen+i);for(var a=``,o=0,s=n(e),c=0;c<s.length;c++){var l=s[c],u=t.length(l);if(o>=r-(u==2?1:0))if(o+u<=i)a+=l;else break;o+=u}return a}})(Cf);var wf=Cf.exports;const Tf=Sf(wf);var Ef=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g};const Df=Sf(Ef);function Of(e,t={}){if(typeof e!=`string`||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=xf(e),e.length===0))return 0;e=e.replace(Df(),` `);let n=t.ambiguousIsNarrow?1:2,r=0;for(let t of e){let e=t.codePointAt(0);if(!(e<=31||e>=127&&e<=159||e>=768&&e<=879))switch(Tf.eastAsianWidth(t)){case`F`:case`W`:r+=2;break;case`A`:r+=n;break;default:r+=1}}return r}const kf=10,Af=(e=0)=>t=>`\x1B[${t+e}m`,jf=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Mf=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,Y={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(Y.modifier);const Nf=Object.keys(Y.color),Pf=Object.keys(Y.bgColor);[...Nf,...Pf];function Ff(){let e=new Map;for(let[t,n]of Object.entries(Y)){for(let[t,r]of Object.entries(n))Y[t]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[t]=Y[t],e.set(r[0],r[1]);Object.defineProperty(Y,t,{value:n,enumerable:!1})}return Object.defineProperty(Y,`codes`,{value:e,enumerable:!1}),Y.color.close=`\x1B[39m`,Y.bgColor.close=`\x1B[49m`,Y.color.ansi=Af(),Y.color.ansi256=jf(),Y.color.ansi16m=Mf(),Y.bgColor.ansi=Af(10),Y.bgColor.ansi256=jf(10),Y.bgColor.ansi16m=Mf(10),Object.defineProperties(Y,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>Y.rgbToAnsi256(...Y.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value:e=>{if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>Y.ansi256ToAnsi(Y.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>Y.ansi256ToAnsi(Y.hexToAnsi256(e)),enumerable:!1}}),Y}const If=Ff(),Lf=new Set([`\x1B`,``]),Rf=39,zf=`\x07`,Bf=`[`,Vf=`]`,Hf=`m`,Uf=`]8;;`,Wf=e=>`${Lf.values().next().value}[${e}m`,Gf=e=>`${Lf.values().next().value}${Uf}${e}`,Kf=e=>e.split(` `).map(e=>Of(e)),qf=(e,t,n)=>{let r=[...t],i=!1,a=!1,o=Of(xf(e[e.length-1]));for(let[t,s]of r.entries()){let c=Of(s);if(o+c<=n?e[e.length-1]+=s:(e.push(s),o=0),Lf.has(s)&&(i=!0,a=r.slice(t+1).join(``).startsWith(Uf)),i){a?s===`\x07`&&(i=!1,a=!1):s===`m`&&(i=!1);continue}o+=c,o===n&&t<r.length-1&&(e.push(``),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Jf=e=>{let t=e.split(` `),n=t.length;for(;n>0&&!(Of(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Yf=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=Kf(e),s=[``];for(let[r,i]of e.split(` `).entries()){n.trim!==!1&&(s[s.length-1]=s[s.length-1].trimStart());let e=Of(s[s.length-1]);if(r!==0&&(e>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),e=0),(e>0||n.trim===!1)&&(s[s.length-1]+=` `,e++)),n.hard&&o[r]>t){let n=t-e,a=1+Math.floor((o[r]-n-1)/t);Math.floor((o[r]-1)/t)<a&&s.push(``),qf(s,i,t);continue}if(e+o[r]>t&&e>0&&o[r]>0){if(n.wordWrap===!1&&e<t){qf(s,i,t);continue}s.push(``)}if(e+o[r]>t&&n.wordWrap===!1){qf(s,i,t);continue}s[s.length-1]+=i}n.trim!==!1&&(s=s.map(e=>Jf(e)));let c=[...s.join(`
|
|
44
|
-
`)];for(let[e,t]of c.entries()){if(r+=t,
|
|
45
|
-
`?(a&&(r
|
|
46
|
-
`&&(i&&n&&(r+=
|
|
42
|
+
`,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:rf,stderr:af}=ef,sf=Symbol(`GENERATOR`),cf=Symbol(`STYLER`),lf=Symbol(`IS_EMPTY`),uf=[`ansi`,`ansi`,`ansi256`,`ansi16m`],df=Object.create(null),ff=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=rf?rf.level:0;e.level=t.level===void 0?n:t.level},pf=e=>{let t=(...e)=>e.join(` `);return ff(t,e),Object.setPrototypeOf(t,mf.prototype),t};function mf(e){return pf(e)}Object.setPrototypeOf(mf.prototype,Function.prototype);for(let[e,t]of Object.entries(Kd))df[e]={get(){let n=vf(this,_f(t.open,t.close,this[cf]),this[lf]);return Object.defineProperty(this,e,{value:n}),n}};df.visible={get(){let e=vf(this,this[cf],!0);return Object.defineProperty(this,`visible`,{value:e}),e}};const hf=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?Kd[n].ansi16m(...r):t===`ansi256`?Kd[n].ansi256(Kd.rgbToAnsi256(...r)):Kd[n].ansi(Kd.rgbToAnsi(...r)):e===`hex`?hf(`rgb`,t,n,...Kd.hexToRgb(...r)):Kd[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){df[e]={get(){let{level:t}=this;return function(...n){let r=_f(hf(e,uf[t],`color`,...n),Kd.color.close,this[cf]);return vf(this,r,this[lf])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);df[t]={get(){let{level:t}=this;return function(...n){let r=_f(hf(e,uf[t],`bgColor`,...n),Kd.bgColor.close,this[cf]);return vf(this,r,this[lf])}}}}const gf=Object.defineProperties(()=>{},{...df,level:{enumerable:!0,get(){return this[sf].level},set(e){this[sf].level=e}}}),_f=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},vf=(e,t,n)=>{let r=(...e)=>yf(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,gf),r[sf]=e,r[cf]=t,r[lf]=n,r},yf=(e,t)=>{if(e.level<=0||!t)return e[lf]?``:t;let n=e[cf];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=tf(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
|
|
43
|
+
`);return a!==-1&&(t=nf(t,i,r,a)),r+t+i};Object.defineProperties(mf.prototype,df);const bf=mf(),xf=mf({level:af?af.level:0});var Sf=bf,Cf=e.__commonJSMin(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}})),wf=e.__commonJSMin(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})),Tf=e.__toESM(Cf(),1),Ef=e.__toESM(wf(),1);function Df({onlyFirst:e=!1}={}){let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}const Of=Df();function kf(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(Of,``)}function Af(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var jf={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(e){var t=e.charCodeAt(0),n=e.length==2?e.charCodeAt(1):0,r=t;return 55296<=t&&t<=56319&&56320<=n&&n<=57343&&(t&=1023,n&=1023,r=t<<10|n,r+=65536),r==12288||65281<=r&&r<=65376||65504<=r&&r<=65510?`F`:r==8361||65377<=r&&r<=65470||65474<=r&&r<=65479||65482<=r&&r<=65487||65490<=r&&r<=65495||65498<=r&&r<=65500||65512<=r&&r<=65518?`H`:4352<=r&&r<=4447||4515<=r&&r<=4519||4602<=r&&r<=4607||9001<=r&&r<=9002||11904<=r&&r<=11929||11931<=r&&r<=12019||12032<=r&&r<=12245||12272<=r&&r<=12283||12289<=r&&r<=12350||12353<=r&&r<=12438||12441<=r&&r<=12543||12549<=r&&r<=12589||12593<=r&&r<=12686||12688<=r&&r<=12730||12736<=r&&r<=12771||12784<=r&&r<=12830||12832<=r&&r<=12871||12880<=r&&r<=13054||13056<=r&&r<=19903||19968<=r&&r<=42124||42128<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||55216<=r&&r<=55238||55243<=r&&r<=55291||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65106||65108<=r&&r<=65126||65128<=r&&r<=65131||110592<=r&&r<=110593||127488<=r&&r<=127490||127504<=r&&r<=127546||127552<=r&&r<=127560||127568<=r&&r<=127569||131072<=r&&r<=194367||177984<=r&&r<=196605||196608<=r&&r<=262141?`W`:32<=r&&r<=126||162<=r&&r<=163||165<=r&&r<=166||r==172||r==175||10214<=r&&r<=10221||10629<=r&&r<=10630?`Na`:r==161||r==164||167<=r&&r<=168||r==170||173<=r&&r<=174||176<=r&&r<=180||182<=r&&r<=186||188<=r&&r<=191||r==198||r==208||215<=r&&r<=216||222<=r&&r<=225||r==230||232<=r&&r<=234||236<=r&&r<=237||r==240||242<=r&&r<=243||247<=r&&r<=250||r==252||r==254||r==257||r==273||r==275||r==283||294<=r&&r<=295||r==299||305<=r&&r<=307||r==312||319<=r&&r<=322||r==324||328<=r&&r<=331||r==333||338<=r&&r<=339||358<=r&&r<=359||r==363||r==462||r==464||r==466||r==468||r==470||r==472||r==474||r==476||r==593||r==609||r==708||r==711||713<=r&&r<=715||r==717||r==720||728<=r&&r<=731||r==733||r==735||768<=r&&r<=879||913<=r&&r<=929||931<=r&&r<=937||945<=r&&r<=961||963<=r&&r<=969||r==1025||1040<=r&&r<=1103||r==1105||r==8208||8211<=r&&r<=8214||8216<=r&&r<=8217||8220<=r&&r<=8221||8224<=r&&r<=8226||8228<=r&&r<=8231||r==8240||8242<=r&&r<=8243||r==8245||r==8251||r==8254||r==8308||r==8319||8321<=r&&r<=8324||r==8364||r==8451||r==8453||r==8457||r==8467||r==8470||8481<=r&&r<=8482||r==8486||r==8491||8531<=r&&r<=8532||8539<=r&&r<=8542||8544<=r&&r<=8555||8560<=r&&r<=8569||r==8585||8592<=r&&r<=8601||8632<=r&&r<=8633||r==8658||r==8660||r==8679||r==8704||8706<=r&&r<=8707||8711<=r&&r<=8712||r==8715||r==8719||r==8721||r==8725||r==8730||8733<=r&&r<=8736||r==8739||r==8741||8743<=r&&r<=8748||r==8750||8756<=r&&r<=8759||8764<=r&&r<=8765||r==8776||r==8780||r==8786||8800<=r&&r<=8801||8804<=r&&r<=8807||8810<=r&&r<=8811||8814<=r&&r<=8815||8834<=r&&r<=8835||8838<=r&&r<=8839||r==8853||r==8857||r==8869||r==8895||r==8978||9312<=r&&r<=9449||9451<=r&&r<=9547||9552<=r&&r<=9587||9600<=r&&r<=9615||9618<=r&&r<=9621||9632<=r&&r<=9633||9635<=r&&r<=9641||9650<=r&&r<=9651||9654<=r&&r<=9655||9660<=r&&r<=9661||9664<=r&&r<=9665||9670<=r&&r<=9672||r==9675||9678<=r&&r<=9681||9698<=r&&r<=9701||r==9711||9733<=r&&r<=9734||r==9737||9742<=r&&r<=9743||9748<=r&&r<=9749||r==9756||r==9758||r==9792||r==9794||9824<=r&&r<=9825||9827<=r&&r<=9829||9831<=r&&r<=9834||9836<=r&&r<=9837||r==9839||9886<=r&&r<=9887||9918<=r&&r<=9919||9924<=r&&r<=9933||9935<=r&&r<=9953||r==9955||9960<=r&&r<=9983||r==10045||r==10071||10102<=r&&r<=10111||11093<=r&&r<=11097||12872<=r&&r<=12879||57344<=r&&r<=63743||65024<=r&&r<=65039||r==65533||127232<=r&&r<=127242||127248<=r&&r<=127277||127280<=r&&r<=127337||127344<=r&&r<=127386||917760<=r&&r<=917999||983040<=r&&r<=1048573||1048576<=r&&r<=1114109?`A`:`N`},t.characterLength=function(e){var t=this.eastAsianWidth(e);return t==`F`||t==`W`||t==`A`?2:1};function n(e){return e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}t.length=function(e){for(var t=n(e),r=0,i=0;i<t.length;i++)r+=this.characterLength(t[i]);return r},t.slice=function(e,r,i){textLen=t.length(e),r||=0,i||=1,r<0&&(r=textLen+r),i<0&&(i=textLen+i);for(var a=``,o=0,s=n(e),c=0;c<s.length;c++){var l=s[c],u=t.length(l);if(o>=r-(u==2?1:0))if(o+u<=i)a+=l;else break;o+=u}return a}})(jf);var Mf=jf.exports;const Nf=Af(Mf);var Pf=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g};const Ff=Af(Pf);function If(e,t={}){if(typeof e!=`string`||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=kf(e),e.length===0))return 0;e=e.replace(Ff(),` `);let n=t.ambiguousIsNarrow?1:2,r=0;for(let t of e){let e=t.codePointAt(0);if(!(e<=31||e>=127&&e<=159||e>=768&&e<=879))switch(Nf.eastAsianWidth(t)){case`F`:case`W`:r+=2;break;case`A`:r+=n;break;default:r+=1}}return r}const Lf=10,Rf=(e=0)=>t=>`\x1B[${t+e}m`,zf=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Bf=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,Y={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(Y.modifier);const Vf=Object.keys(Y.color),Hf=Object.keys(Y.bgColor);[...Vf,...Hf];function Uf(){let e=new Map;for(let[t,n]of Object.entries(Y)){for(let[t,r]of Object.entries(n))Y[t]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[t]=Y[t],e.set(r[0],r[1]);Object.defineProperty(Y,t,{value:n,enumerable:!1})}return Object.defineProperty(Y,`codes`,{value:e,enumerable:!1}),Y.color.close=`\x1B[39m`,Y.bgColor.close=`\x1B[49m`,Y.color.ansi=Rf(),Y.color.ansi256=zf(),Y.color.ansi16m=Bf(),Y.bgColor.ansi=Rf(10),Y.bgColor.ansi256=zf(10),Y.bgColor.ansi16m=Bf(10),Object.defineProperties(Y,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>Y.rgbToAnsi256(...Y.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value:e=>{if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>Y.ansi256ToAnsi(Y.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>Y.ansi256ToAnsi(Y.hexToAnsi256(e)),enumerable:!1}}),Y}const Wf=Uf(),Gf=new Set([`\x1B`,``]),Kf=39,qf=`\x07`,Jf=`[`,Yf=`]`,Xf=`m`,Zf=`]8;;`,Qf=e=>`${Gf.values().next().value}[${e}m`,$f=e=>`${Gf.values().next().value}${Zf}${e}`,ep=e=>e.split(` `).map(e=>If(e)),tp=(e,t,n)=>{let r=[...t],i=!1,a=!1,o=If(kf(e[e.length-1]));for(let[t,s]of r.entries()){let c=If(s);if(o+c<=n?e[e.length-1]+=s:(e.push(s),o=0),Gf.has(s)&&(i=!0,a=r.slice(t+1).join(``).startsWith(Zf)),i){a?s===`\x07`&&(i=!1,a=!1):s===`m`&&(i=!1);continue}o+=c,o===n&&t<r.length-1&&(e.push(``),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},np=e=>{let t=e.split(` `),n=t.length;for(;n>0&&!(If(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},rp=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=ep(e),s=[``];for(let[r,i]of e.split(` `).entries()){n.trim!==!1&&(s[s.length-1]=s[s.length-1].trimStart());let e=If(s[s.length-1]);if(r!==0&&(e>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),e=0),(e>0||n.trim===!1)&&(s[s.length-1]+=` `,e++)),n.hard&&o[r]>t){let n=t-e,a=1+Math.floor((o[r]-n-1)/t);Math.floor((o[r]-1)/t)<a&&s.push(``),tp(s,i,t);continue}if(e+o[r]>t&&e>0&&o[r]>0){if(n.wordWrap===!1&&e<t){tp(s,i,t);continue}s.push(``)}if(e+o[r]>t&&n.wordWrap===!1){tp(s,i,t);continue}s[s.length-1]+=i}n.trim!==!1&&(s=s.map(e=>np(e)));let c=[...s.join(`
|
|
44
|
+
`)];for(let[e,t]of c.entries()){if(r+=t,Gf.has(t)){let{groups:t}=RegExp(`(?:\\[(?<code>\\d+)m|\\${Zf}(?<uri>.*))`).exec(c.slice(e).join(``))||{groups:{}};if(t.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}let n=Wf.codes.get(Number(i));c[e+1]===`
|
|
45
|
+
`?(a&&(r+=$f(``)),i&&n&&(r+=Qf(n))):t===`
|
|
46
|
+
`&&(i&&n&&(r+=Qf(i)),a&&(r+=$f(a)))}return r};function ip(e,t,n){return String(e).normalize().replace(/\r\n/g,`
|
|
47
47
|
`).split(`
|
|
48
|
-
`).map(e=>
|
|
49
|
-
`)}const
|
|
48
|
+
`).map(e=>rp(e,t,n)).join(`
|
|
49
|
+
`)}const ap={actions:new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]])};function op(e,t){if(typeof e==`string`)return ap.aliases.get(e)===t;for(let n of e)if(n!==void 0&&op(n,t))return!0;return!1}function sp(e,t){if(e===t)return;let n=e.split(`
|
|
50
50
|
`),r=t.split(`
|
|
51
|
-
`),i=[];for(let e=0;e<Math.max(n.length,r.length);e++)n[e]!==r[e]&&i.push(e);return i}const
|
|
52
|
-
`),
|
|
53
|
-
`).length-1;this.output.write(
|
|
54
|
-
`);this.output.write(r[n]),this._prevFrame=e,this.output.write(
|
|
51
|
+
`),i=[];for(let e=0;e<Math.max(n.length,r.length);e++)n[e]!==r[e]&&i.push(e);return i}const cp=globalThis.process.platform.startsWith(`win`),lp=Symbol(`clack:cancel`);function up(e){return e===lp}function dp(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function fp({input:e=x.stdin,output:t=x.stdout,overwrite:n=!0,hideCursor:r=!0}={}){let i=w.createInterface({input:e,output:t,prompt:``,tabSize:1});w.emitKeypressEvents(e,i),e.isTTY&&e.setRawMode(!0);let a=(i,{name:o,sequence:s})=>{if(op([String(i),o,s],`cancel`)){r&&t.write(Tf.cursor.show),process.exit(0);return}if(!n)return;let c=o===`return`?0:-1,l=o===`return`?-1:0;w.moveCursor(t,c,l,()=>{w.clearLine(t,1,()=>{e.once(`keypress`,a)})})};return r&&t.write(Tf.cursor.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(Tf.cursor.show),e.isTTY&&!cp&&e.setRawMode(!1),i.terminal=!1,i.close()}}var pp=Object.defineProperty,mp=(e,t,n)=>t in e?pp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hp=(e,t,n)=>(mp(e,typeof t==`symbol`?t:t+``,n),n),gp=class{constructor(e,t=!0){hp(this,`input`),hp(this,`output`),hp(this,`_abortSignal`),hp(this,`rl`),hp(this,`opts`),hp(this,`_render`),hp(this,`_track`,!1),hp(this,`_prevFrame`,``),hp(this,`_subscribers`,new Map),hp(this,`_cursor`,0),hp(this,`state`,`initial`),hp(this,`error`,``),hp(this,`value`);let{input:n=x.stdin,output:r=x.stdout,render:i,signal:a,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=a,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise((e,t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(lp);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}let n=new c.Writable;n._write=(e,t,n)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,``),this._cursor=this.rl?.cursor??0,this.emit(`value`,this.value)),n()},this.input.pipe(n),this.rl=w.default.createInterface({input:this.input,output:n,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),w.default.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on(`keypress`,this.onKeypress),dp(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(Tf.cursor.show),this.output.off(`resize`,this.render),dp(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(Tf.cursor.show),this.output.off(`resize`,this.render),dp(this.input,!1),e(lp)})})}onKeypress(e,t){if(this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&ap.aliases.has(t.name)&&this.emit(`cursor`,ap.aliases.get(t.name)),ap.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),e===` `&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit(`value`,this.opts.placeholder))),e&&this.emit(`key`,e.toLowerCase()),t?.name===`return`){if(this.opts.validate){let e=this.opts.validate(this.value);e&&(this.error=e instanceof Error?e.message:e,this.state=`error`,this.rl?.write(this.value))}this.state!==`error`&&(this.state=`submit`)}op([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
|
|
52
|
+
`),dp(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=ip(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
|
|
53
|
+
`).length-1;this.output.write(Tf.cursor.move(-999,e*-1))}render(){let e=ip(this._render(this)??``,process.stdout.columns,{hard:!0});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(Tf.cursor.hide);else{let t=sp(this._prevFrame,e);if(this.restoreCursor(),t&&t?.length===1){let n=t[0];this.output.write(Tf.cursor.move(0,n)),this.output.write(Tf.erase.lines(1));let r=e.split(`
|
|
54
|
+
`);this.output.write(r[n]),this._prevFrame=e,this.output.write(Tf.cursor.move(0,r.length-n-1));return}if(t&&t?.length>1){let n=t[0];this.output.write(Tf.cursor.move(0,n)),this.output.write(Tf.erase.down());let r=e.split(`
|
|
55
55
|
`).slice(n);this.output.write(r.join(`
|
|
56
|
-
`)),this._prevFrame=e;return}this.output.write(
|
|
57
|
-
${
|
|
56
|
+
`)),this._prevFrame=e;return}this.output.write(Tf.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},_p=class extends gp{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`value`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(Tf.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},vp=Object.defineProperty,yp=(e,t,n)=>t in e?vp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,bp=(e,t,n)=>(yp(e,typeof t==`symbol`?t:t+``,n),n),xp=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},Sp=(e,t,n)=>(xp(e,t,`read from private field`),n?n.call(e):t.get(e)),Cp=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},wp=(e,t,n,r)=>(xp(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n),Tp;let Ep=class extends gp{constructor(e){super(e,!1),bp(this,`options`),bp(this,`cursor`,0),Cp(this,Tp,void 0);let{options:t}=e;wp(this,Tp,e.selectableGroups!==!1),this.options=Object.entries(t).flatMap(([e,t])=>[{value:e,group:!0,label:e},...t.map(t=>({...t,group:e}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),Sp(this,Tp)?0:1),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let e=this.options[this.cursor]?.group===!0;!Sp(this,Tp)&&e&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case`down`:case`right`:{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let e=this.options[this.cursor]?.group===!0;!Sp(this,Tp)&&e&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case`space`:this.toggleValue();break}})}getGroupItems(e){return this.options.filter(t=>t.group===e)}isGroupSelected(e){return this.getGroupItems(e).every(e=>this.value.includes(e.value))}toggleValue(){let e=this.options[this.cursor];if(e.group===!0){let t=e.value,n=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter(e=>n.findIndex(t=>t.value===e)===-1):this.value=[...this.value,...n.map(e=>e.value)],this.value=Array.from(new Set(this.value))}else this.value=this.value.includes(e.value)?this.value.filter(t=>t!==e.value):[...this.value,e.value]}};Tp=new WeakMap;var Dp=Object.defineProperty,Op=(e,t,n)=>t in e?Dp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kp=(e,t,n)=>(Op(e,typeof t==`symbol`?t:t+``,n),n);let Ap=class extends gp{constructor(e){super(e,!1),kp(this,`options`),kp(this,`cursor`,0),this.options=e.options,this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0),this.on(`key`,e=>{e===`a`&&this.toggleAll()}),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case`down`:case`right`:this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break;case`space`:this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){this.value=this.value.length===this.options.length?[]:this.options.map(e=>e.value)}toggleValue(){this.value=this.value.includes(this._value)?this.value.filter(e=>e!==this._value):[...this.value,this._value]}};var jp=Object.defineProperty,Mp=(e,t,n)=>t in e?jp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Np=(e,t,n)=>(Mp(e,typeof t==`symbol`?t:t+``,n),n),Pp=class extends gp{constructor({mask:e,...t}){super(t),Np(this,`valueWithCursor`,``),Np(this,`_mask`,`•`),this._mask=e??`•`,this.on(`finalize`,()=>{this.valueWithCursor=this.masked}),this.on(`value`,()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${Ef.default.inverse(Ef.default.hidden(`_`))}`;else{let e=this.masked.slice(0,this.cursor),t=this.masked.slice(this.cursor);this.valueWithCursor=`${e}${Ef.default.inverse(t[0])}${t.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}},Fp=Object.defineProperty,Ip=(e,t,n)=>t in e?Fp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Lp=(e,t,n)=>(Ip(e,typeof t==`symbol`?t:t+``,n),n),Rp=class extends gp{constructor(e){super(e,!1),Lp(this,`options`),Lp(this,`cursor`,0),this.options=e.options,this.cursor=this.options.findIndex(({value:t})=>t===e.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case`down`:case`right`:this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}},zp=Object.defineProperty,Bp=(e,t,n)=>t in e?zp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Vp=(e,t,n)=>(Bp(e,typeof t==`symbol`?t:t+``,n),n),Hp=class extends gp{constructor(e){super(e,!1),Vp(this,`options`),Vp(this,`cursor`,0),this.options=e.options;let t=this.options.map(({value:[e]})=>e?.toLowerCase());this.cursor=Math.max(t.indexOf(e.initialValue),0),this.on(`key`,e=>{if(!t.includes(e))return;let n=this.options.find(({value:[t]})=>t?.toLowerCase()===e);n&&(this.value=n.value,this.state=`submit`,this.emit(`submit`))})}},Up=class extends gp{get valueWithCursor(){if(this.state===`submit`)return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;let e=this.value.slice(0,this.cursor),[t,...n]=this.value.slice(this.cursor);return`${e}${Ef.default.inverse(t)}${n.join(``)}`}get cursor(){return this._cursor}constructor(e){super(e),this.on(`finalize`,()=>{this.value||=e.defaultValue})}},X=e.__toESM(wf(),1),Wp=e.__toESM(Cf(),1);function Gp(){return x.default.platform===`win32`?!!x.default.env.CI||!!x.default.env.WT_SESSION||!!x.default.env.TERMINUS_SUBLIME||x.default.env.ConEmuTask===`{cmd::Cmder}`||x.default.env.TERM_PROGRAM===`Terminus-Sublime`||x.default.env.TERM_PROGRAM===`vscode`||x.default.env.TERM===`xterm-256color`||x.default.env.TERM===`alacritty`||x.default.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:x.default.env.TERM!==`linux`}const Kp=Gp(),Z=(e,t)=>Kp?e:t,qp=Z(`◆`,`*`),Jp=Z(`■`,`x`),Yp=Z(`▲`,`x`),Xp=Z(`◇`,`o`),Zp=Z(`┌`,`T`),Q=Z(`│`,`|`),Qp=Z(`└`,`—`),$p=Z(`●`,`>`),em=Z(`○`,` `),tm=Z(`◻`,`[•]`),nm=Z(`◼`,`[+]`),rm=Z(`◻`,`[ ]`),im=Z(`▪`,`•`),am=Z(`─`,`-`),om=Z(`╮`,`+`),sm=Z(`├`,`+`),cm=Z(`╯`,`+`),lm=Z(`●`,`•`),um=Z(`◆`,`*`),dm=Z(`▲`,`!`),fm=Z(`■`,`x`),pm=e=>{switch(e){case`initial`:case`active`:return X.default.cyan(qp);case`cancel`:return X.default.red(Jp);case`error`:return X.default.yellow(Yp);case`submit`:return X.default.green(Xp)}},mm=e=>{let{cursor:t,options:n,style:r}=e,i=e.maxItems??1/0,a=Math.max(process.stdout.rows-4,0),o=Math.min(a,Math.max(i,5)),s=0;t>=s+o-3?s=Math.max(Math.min(t-o+3,n.length-o),0):t<s+2&&(s=Math.max(t-2,0));let c=o<n.length&&s>0,l=o<n.length&&s+o<n.length;return n.slice(s,s+o).map((e,n,i)=>{let a=n===0&&c,o=n===i.length-1&&l;return a||o?X.default.dim(`...`):r(e,n+s===t)})},hm=e=>new Up({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){let t=`${X.default.gray(Q)}
|
|
57
|
+
${pm(this.state)} ${e.message}
|
|
58
58
|
`,n=e.placeholder?X.default.inverse(e.placeholder[0])+X.default.dim(e.placeholder.slice(1)):X.default.inverse(X.default.hidden(`_`)),r=this.value?this.valueWithCursor:n;switch(this.state){case`error`:return`${t.trim()}
|
|
59
59
|
${X.default.yellow(Q)} ${r}
|
|
60
|
-
${X.default.yellow(
|
|
60
|
+
${X.default.yellow(Qp)} ${X.default.yellow(this.error)}
|
|
61
61
|
`;case`submit`:return`${t}${X.default.gray(Q)} ${X.default.dim(this.value||e.placeholder)}`;case`cancel`:return`${t}${X.default.gray(Q)} ${X.default.strikethrough(X.default.dim(this.value??``))}${this.value?.trim()?`
|
|
62
62
|
${X.default.gray(Q)}`:``}`;default:return`${t}${X.default.cyan(Q)} ${r}
|
|
63
|
-
${X.default.cyan(
|
|
64
|
-
`}}}).prompt(),
|
|
65
|
-
${
|
|
63
|
+
${X.default.cyan(Qp)}
|
|
64
|
+
`}}}).prompt(),gm=e=>new Pp({validate:e.validate,mask:e.mask??im,render(){let t=`${X.default.gray(Q)}
|
|
65
|
+
${pm(this.state)} ${e.message}
|
|
66
66
|
`,n=this.valueWithCursor,r=this.masked;switch(this.state){case`error`:return`${t.trim()}
|
|
67
67
|
${X.default.yellow(Q)} ${r}
|
|
68
|
-
${X.default.yellow(
|
|
68
|
+
${X.default.yellow(Qp)} ${X.default.yellow(this.error)}
|
|
69
69
|
`;case`submit`:return`${t}${X.default.gray(Q)} ${X.default.dim(r)}`;case`cancel`:return`${t}${X.default.gray(Q)} ${X.default.strikethrough(X.default.dim(r??``))}${r?`
|
|
70
70
|
${X.default.gray(Q)}`:``}`;default:return`${t}${X.default.cyan(Q)} ${n}
|
|
71
|
-
${X.default.cyan(
|
|
72
|
-
`}}}).prompt(),
|
|
73
|
-
${
|
|
71
|
+
${X.default.cyan(Qp)}
|
|
72
|
+
`}}}).prompt(),_m=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new _p({active:t,inactive:n,initialValue:e.initialValue??!0,render(){let r=`${X.default.gray(Q)}
|
|
73
|
+
${pm(this.state)} ${e.message}
|
|
74
74
|
`,i=this.value?t:n;switch(this.state){case`submit`:return`${r}${X.default.gray(Q)} ${X.default.dim(i)}`;case`cancel`:return`${r}${X.default.gray(Q)} ${X.default.strikethrough(X.default.dim(i))}
|
|
75
|
-
${X.default.gray(Q)}`;default:return`${r}${X.default.cyan(Q)} ${this.value?`${X.default.green(
|
|
76
|
-
${X.default.cyan(
|
|
77
|
-
`}}}).prompt()},
|
|
78
|
-
${
|
|
75
|
+
${X.default.gray(Q)}`;default:return`${r}${X.default.cyan(Q)} ${this.value?`${X.default.green($p)} ${t}`:`${X.default.dim(em)} ${X.default.dim(t)}`} ${X.default.dim(`/`)} ${this.value?`${X.default.dim(em)} ${X.default.dim(n)}`:`${X.default.green($p)} ${n}`}
|
|
76
|
+
${X.default.cyan(Qp)}
|
|
77
|
+
`}}}).prompt()},vm=e=>{let t=(e,t)=>{let n=e.label??String(e.value);switch(t){case`selected`:return`${X.default.dim(n)}`;case`active`:return`${X.default.green($p)} ${n} ${e.hint?X.default.dim(`(${e.hint})`):``}`;case`cancelled`:return`${X.default.strikethrough(X.default.dim(n))}`;default:return`${X.default.dim(em)} ${X.default.dim(n)}`}};return new Rp({options:e.options,initialValue:e.initialValue,render(){let n=`${X.default.gray(Q)}
|
|
78
|
+
${pm(this.state)} ${e.message}
|
|
79
79
|
`;switch(this.state){case`submit`:return`${n}${X.default.gray(Q)} ${t(this.options[this.cursor],`selected`)}`;case`cancel`:return`${n}${X.default.gray(Q)} ${t(this.options[this.cursor],`cancelled`)}
|
|
80
|
-
${X.default.gray(Q)}`;default:return`${n}${X.default.cyan(Q)} ${
|
|
80
|
+
${X.default.gray(Q)}`;default:return`${n}${X.default.cyan(Q)} ${mm({cursor:this.cursor,options:this.options,maxItems:e.maxItems,style:(e,n)=>t(e,n?`active`:`inactive`)}).join(`
|
|
81
81
|
${X.default.cyan(Q)} `)}
|
|
82
|
-
${X.default.cyan(
|
|
83
|
-
`}}}).prompt()},
|
|
84
|
-
${
|
|
82
|
+
${X.default.cyan(Qp)}
|
|
83
|
+
`}}}).prompt()},ym=e=>{let t=(e,t=`inactive`)=>{let n=e.label??String(e.value);return t===`selected`?`${X.default.dim(n)}`:t===`cancelled`?`${X.default.strikethrough(X.default.dim(n))}`:t===`active`?`${X.default.bgCyan(X.default.gray(` ${e.value} `))} ${n} ${e.hint?X.default.dim(`(${e.hint})`):``}`:`${X.default.gray(X.default.bgWhite(X.default.inverse(` ${e.value} `)))} ${n} ${e.hint?X.default.dim(`(${e.hint})`):``}`};return new Hp({options:e.options,initialValue:e.initialValue,render(){let n=`${X.default.gray(Q)}
|
|
84
|
+
${pm(this.state)} ${e.message}
|
|
85
85
|
`;switch(this.state){case`submit`:return`${n}${X.default.gray(Q)} ${t(this.options.find(e=>e.value===this.value)??e.options[0],`selected`)}`;case`cancel`:return`${n}${X.default.gray(Q)} ${t(this.options[0],`cancelled`)}
|
|
86
86
|
${X.default.gray(Q)}`;default:return`${n}${X.default.cyan(Q)} ${this.options.map((e,n)=>t(e,n===this.cursor?`active`:`inactive`)).join(`
|
|
87
87
|
${X.default.cyan(Q)} `)}
|
|
88
|
-
${X.default.cyan(
|
|
89
|
-
`}}}).prompt()},
|
|
88
|
+
${X.default.cyan(Qp)}
|
|
89
|
+
`}}}).prompt()},bm=e=>{let t=(e,t)=>{let n=e.label??String(e.value);return t===`active`?`${X.default.cyan(tm)} ${n} ${e.hint?X.default.dim(`(${e.hint})`):``}`:t===`selected`?`${X.default.green(nm)} ${X.default.dim(n)} ${e.hint?X.default.dim(`(${e.hint})`):``}`:t===`cancelled`?`${X.default.strikethrough(X.default.dim(n))}`:t===`active-selected`?`${X.default.green(nm)} ${n} ${e.hint?X.default.dim(`(${e.hint})`):``}`:t===`submitted`?`${X.default.dim(n)}`:`${X.default.dim(rm)} ${X.default.dim(n)}`};return new Ap({options:e.options,initialValues:e.initialValues,required:e.required??!0,cursorAt:e.cursorAt,validate(e){if(this.required&&e.length===0)return`Please select at least one option.
|
|
90
90
|
${X.default.reset(X.default.dim(`Press ${X.default.gray(X.default.bgWhite(X.default.inverse(` space `)))} to select, ${X.default.gray(X.default.bgWhite(X.default.inverse(` enter `)))} to submit`))}`},render(){let n=`${X.default.gray(Q)}
|
|
91
|
-
${
|
|
91
|
+
${pm(this.state)} ${e.message}
|
|
92
92
|
`,r=(e,n)=>{let r=this.value.includes(e.value);return n&&r?t(e,`active-selected`):r?t(e,`selected`):t(e,n?`active`:`inactive`)};switch(this.state){case`submit`:return`${n}${X.default.gray(Q)} ${this.options.filter(({value:e})=>this.value.includes(e)).map(e=>t(e,`submitted`)).join(X.default.dim(`, `))||X.default.dim(`none`)}`;case`cancel`:{let e=this.options.filter(({value:e})=>this.value.includes(e)).map(e=>t(e,`cancelled`)).join(X.default.dim(`, `));return`${n}${X.default.gray(Q)} ${e.trim()?`${e}
|
|
93
93
|
${X.default.gray(Q)}`:``}`}case`error`:{let t=this.error.split(`
|
|
94
|
-
`).map((e,t)=>t===0?`${X.default.yellow(
|
|
95
|
-
`);return`${n+X.default.yellow(Q)} ${
|
|
94
|
+
`).map((e,t)=>t===0?`${X.default.yellow(Qp)} ${X.default.yellow(e)}`:` ${e}`).join(`
|
|
95
|
+
`);return`${n+X.default.yellow(Q)} ${mm({options:this.options,cursor:this.cursor,maxItems:e.maxItems,style:r}).join(`
|
|
96
96
|
${X.default.yellow(Q)} `)}
|
|
97
97
|
${t}
|
|
98
|
-
`}default:return`${n}${X.default.cyan(Q)} ${
|
|
98
|
+
`}default:return`${n}${X.default.cyan(Q)} ${mm({options:this.options,cursor:this.cursor,maxItems:e.maxItems,style:r}).join(`
|
|
99
99
|
${X.default.cyan(Q)} `)}
|
|
100
|
-
${X.default.cyan(
|
|
101
|
-
`}}}).prompt()},
|
|
100
|
+
${X.default.cyan(Qp)}
|
|
101
|
+
`}}}).prompt()},xm=e=>{let{selectableGroups:t=!0}=e,n=(e,n,r=[])=>{let i=e.label??String(e.value),a=typeof e.group==`string`,o=a&&(r[r.indexOf(e)+1]??{group:!0}),s=a&&o.group===!0,c=a?t?`${s?Qp:Q} `:` `:``;if(n===`active`)return`${X.default.dim(c)}${X.default.cyan(tm)} ${i} ${e.hint?X.default.dim(`(${e.hint})`):``}`;if(n===`group-active`)return`${c}${X.default.cyan(tm)} ${X.default.dim(i)}`;if(n===`group-active-selected`)return`${c}${X.default.green(nm)} ${X.default.dim(i)}`;if(n===`selected`){let n=a||t?X.default.green(nm):``;return`${X.default.dim(c)}${n} ${X.default.dim(i)} ${e.hint?X.default.dim(`(${e.hint})`):``}`}if(n===`cancelled`)return`${X.default.strikethrough(X.default.dim(i))}`;if(n===`active-selected`)return`${X.default.dim(c)}${X.default.green(nm)} ${i} ${e.hint?X.default.dim(`(${e.hint})`):``}`;if(n===`submitted`)return`${X.default.dim(i)}`;let l=a||t?X.default.dim(rm):``;return`${X.default.dim(c)}${l} ${X.default.dim(i)}`};return new Ep({options:e.options,initialValues:e.initialValues,required:e.required??!0,cursorAt:e.cursorAt,selectableGroups:t,validate(e){if(this.required&&e.length===0)return`Please select at least one option.
|
|
102
102
|
${X.default.reset(X.default.dim(`Press ${X.default.gray(X.default.bgWhite(X.default.inverse(` space `)))} to select, ${X.default.gray(X.default.bgWhite(X.default.inverse(` enter `)))} to submit`))}`},render(){let t=`${X.default.gray(Q)}
|
|
103
|
-
${
|
|
103
|
+
${pm(this.state)} ${e.message}
|
|
104
104
|
`;switch(this.state){case`submit`:return`${t}${X.default.gray(Q)} ${this.options.filter(({value:e})=>this.value.includes(e)).map(e=>n(e,`submitted`)).join(X.default.dim(`, `))}`;case`cancel`:{let e=this.options.filter(({value:e})=>this.value.includes(e)).map(e=>n(e,`cancelled`)).join(X.default.dim(`, `));return`${t}${X.default.gray(Q)} ${e.trim()?`${e}
|
|
105
105
|
${X.default.gray(Q)}`:``}`}case`error`:{let e=this.error.split(`
|
|
106
|
-
`).map((e,t)=>t===0?`${X.default.yellow(
|
|
106
|
+
`).map((e,t)=>t===0?`${X.default.yellow(Qp)} ${X.default.yellow(e)}`:` ${e}`).join(`
|
|
107
107
|
`);return`${t}${X.default.yellow(Q)} ${this.options.map((e,t,r)=>{let i=this.value.includes(e.value)||e.group===!0&&this.isGroupSelected(`${e.value}`),a=t===this.cursor;return!a&&typeof e.group==`string`&&this.options[this.cursor].value===e.group?n(e,i?`group-active-selected`:`group-active`,r):a&&i?n(e,`active-selected`,r):i?n(e,`selected`,r):n(e,a?`active`:`inactive`,r)}).join(`
|
|
108
108
|
${X.default.yellow(Q)} `)}
|
|
109
109
|
${e}
|
|
110
110
|
`}default:return`${t}${X.default.cyan(Q)} ${this.options.map((e,t,r)=>{let i=this.value.includes(e.value)||e.group===!0&&this.isGroupSelected(`${e.value}`),a=t===this.cursor;return!a&&typeof e.group==`string`&&this.options[this.cursor].value===e.group?n(e,i?`group-active-selected`:`group-active`,r):a&&i?n(e,`active-selected`,r):i?n(e,`selected`,r):n(e,a?`active`:`inactive`,r)}).join(`
|
|
111
111
|
${X.default.cyan(Q)} `)}
|
|
112
|
-
${X.default.cyan(
|
|
113
|
-
`}}}).prompt()},
|
|
112
|
+
${X.default.cyan(Qp)}
|
|
113
|
+
`}}}).prompt()},Sm=(e=``,t=``)=>{let n=`
|
|
114
114
|
${e}
|
|
115
115
|
`.split(`
|
|
116
116
|
`),r=(0,l.stripVTControlCharacters)(t).length,i=Math.max(n.reduce((e,t)=>{let n=(0,l.stripVTControlCharacters)(t);return n.length>e?n.length:e},0),r)+2,a=n.map(e=>`${X.default.gray(Q)} ${X.default.dim(e)}${` `.repeat(i-(0,l.stripVTControlCharacters)(e).length)}${X.default.gray(Q)}`).join(`
|
|
117
117
|
`);process.stdout.write(`${X.default.gray(Q)}
|
|
118
|
-
${X.default.green(
|
|
118
|
+
${X.default.green(Xp)} ${X.default.reset(t)} ${X.default.gray(am.repeat(Math.max(i-r-1,1))+om)}
|
|
119
119
|
${a}
|
|
120
|
-
${X.default.gray(
|
|
121
|
-
`)},
|
|
120
|
+
${X.default.gray(sm+am.repeat(i+2)+cm)}
|
|
121
|
+
`)},Cm=(e=``)=>{process.stdout.write(`${X.default.gray(Qp)} ${X.default.red(e)}
|
|
122
122
|
|
|
123
|
-
`)},
|
|
124
|
-
`)},
|
|
125
|
-
${X.default.gray(
|
|
123
|
+
`)},wm=(e=``)=>{process.stdout.write(`${X.default.gray(Zp)} ${e}
|
|
124
|
+
`)},Tm=(e=``)=>{process.stdout.write(`${X.default.gray(Q)}
|
|
125
|
+
${X.default.gray(Qp)} ${e}
|
|
126
126
|
|
|
127
|
-
`)},
|
|
127
|
+
`)},Em={message:(e=``,{symbol:t=X.default.gray(Q)}={})=>{let n=[`${X.default.gray(Q)}`];if(e){let[r,...i]=e.split(`
|
|
128
128
|
`);n.push(`${t} ${r}`,...i.map(e=>`${X.default.gray(Q)} ${e}`))}process.stdout.write(`${n.join(`
|
|
129
129
|
`)}
|
|
130
|
-
`)},info:e=>{
|
|
130
|
+
`)},info:e=>{Em.message(e,{symbol:X.default.blue(lm)})},success:e=>{Em.message(e,{symbol:X.default.green(um)})},step:e=>{Em.message(e,{symbol:X.default.green(Xp)})},warn:e=>{Em.message(e,{symbol:X.default.yellow(dm)})},warning:e=>{Em.warn(e)},error:e=>{Em.message(e,{symbol:X.default.red(fm)})}},Dm=`${X.default.gray(Q)} `,Om={message:async(e,{symbol:t=X.default.gray(Q)}={})=>{process.stdout.write(`${X.default.gray(Q)}
|
|
131
131
|
${t} `);let n=3;for await(let t of e){t=t.replace(/\n/g,`
|
|
132
|
-
${
|
|
132
|
+
${Dm}`),t.includes(`
|
|
133
133
|
`)&&(n=3+(0,l.stripVTControlCharacters)(t.slice(t.lastIndexOf(`
|
|
134
134
|
`))).length);let e=(0,l.stripVTControlCharacters)(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
135
|
-
${
|
|
136
|
-
`)},info:e=>
|
|
135
|
+
${Dm}${t.trimStart()}`),n=3+(0,l.stripVTControlCharacters)(t.trimStart()).length)}process.stdout.write(`
|
|
136
|
+
`)},info:e=>Om.message(e,{symbol:X.default.blue(lm)}),success:e=>Om.message(e,{symbol:X.default.green(um)}),step:e=>Om.message(e,{symbol:X.default.green(Xp)}),warn:e=>Om.message(e,{symbol:X.default.yellow(dm)}),warning:e=>Om.warn(e),error:e=>Om.message(e,{symbol:X.default.red(fm)})},km=({indicator:e=`dots`}={})=>{let t=Kp?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],n=Kp?80:120,r=process.env.CI===`true`,i,a,o=!1,s=``,c,l=performance.now(),u=e=>{o&&y(e>1?`Something went wrong`:`Canceled`,e)},d=()=>u(2),f=()=>u(1),p=()=>{process.on(`uncaughtExceptionMonitor`,d),process.on(`unhandledRejection`,d),process.on(`SIGINT`,f),process.on(`SIGTERM`,f),process.on(`exit`,u)},m=()=>{process.removeListener(`uncaughtExceptionMonitor`,d),process.removeListener(`unhandledRejection`,d),process.removeListener(`SIGINT`,f),process.removeListener(`SIGTERM`,f),process.removeListener(`exit`,u)},h=()=>{if(c===void 0)return;r&&process.stdout.write(`
|
|
137
137
|
`);let e=c.split(`
|
|
138
|
-
`);process.stdout.write(
|
|
139
|
-
`);let d=0,f=0;p(),a=setInterval(()=>{if(r&&s===c)return;h(),c=s;let n=X.default.magenta(t[d]);if(r)process.stdout.write(`${n} ${s}...`);else if(e===`timer`)process.stdout.write(`${n} ${s} ${_(l)}`);else{let e=`.`.repeat(Math.floor(f)).slice(0,3);process.stdout.write(`${n} ${s}${e}`)}d=d+1<t.length?d+1:0,f=f<t.length?f+.125:0},n)},y=(t=``,n=0)=>{o=!1,clearInterval(a),h();let r=n===0?X.default.green(
|
|
138
|
+
`);process.stdout.write(Wp.cursor.move(-999,e.length-1)),process.stdout.write(Wp.erase.down(e.length))},g=e=>e.replace(/\.+$/,``),_=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},v=(u=``)=>{o=!0,i=fp(),s=g(u),l=performance.now(),process.stdout.write(`${X.default.gray(Q)}
|
|
139
|
+
`);let d=0,f=0;p(),a=setInterval(()=>{if(r&&s===c)return;h(),c=s;let n=X.default.magenta(t[d]);if(r)process.stdout.write(`${n} ${s}...`);else if(e===`timer`)process.stdout.write(`${n} ${s} ${_(l)}`);else{let e=`.`.repeat(Math.floor(f)).slice(0,3);process.stdout.write(`${n} ${s}${e}`)}d=d+1<t.length?d+1:0,f=f<t.length?f+.125:0},n)},y=(t=``,n=0)=>{o=!1,clearInterval(a),h();let r=n===0?X.default.green(Xp):n===1?X.default.red(Jp):X.default.red(Yp);s=g(t??s),e===`timer`?process.stdout.write(`${r} ${s} ${_(l)}
|
|
140
140
|
`):process.stdout.write(`${r} ${s}
|
|
141
|
-
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Sm=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&np(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},Cm=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=xm();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let wm;function Tm(){try{return o.default.statSync(`/.dockerenv`),!0}catch{return!1}}function Em(){try{return o.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Dm(){return wm===void 0&&(wm=Tm()||Em()),wm}let Om;const km=()=>{try{return o.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function Am(){return Om===void 0&&(Om=km()||Dm()),Om}const jm=()=>{if(x.default.platform!==`linux`)return!1;if(S.default.release().toLowerCase().includes(`microsoft`))return!Am();try{return o.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Am():!1}catch{return!1}};var Mm=x.default.env.__IS_WSL_TEST__?jm:jm();const Nm=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await E.default.access(n,E.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await E.default.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Pm=async()=>`${await Nm()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Fm=async()=>Mm?Pm():`${x.default.env.SYSTEMROOT||x.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Im(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 Lm=(0,l.promisify)(T.execFile);async function Rm(){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Lm(`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 zm=(0,l.promisify)(T.execFile);async function Bm(e,{humanReadableOutput:t=!0,signal:n}={}){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await zm(`osascript`,[`-e`,e,r],i);return a.trim()}async function Vm(e){return Bm(`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 Hm=(0,l.promisify)(T.execFile),Um={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 Wm=class extends Error{};async function Gm(e=Hm){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 Wm(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Um[r];if(!i)throw new Wm(`Unknown browser ID: ${r}`);return i}const Km=(0,l.promisify)(T.execFile),qm=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Jm(){if(x.default.platform===`darwin`){let e=await Rm();return{name:await Vm(e),id:e}}if(x.default.platform===`linux`){let{stdout:e}=await Km(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:qm(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(x.default.platform===`win32`)return Gm();throw Error(`Only macOS, Linux, and Windows are supported`)}const Ym=(0,l.promisify)(T.default.execFile),Xm=b.default.dirname((0,s.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),Zm=b.default.join(Xm,`xdg-open`),{platform:Qm,arch:$m}=x.default;async function eh(){let e=await Fm(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=a.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await Ym(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[i]?{id:o[i]}:{}}const th=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},nh=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return th(e.app,t=>nh({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return th(t,t=>nh({...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=Mm?await eh():await Jm();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),nh({...e,app:{name:oh[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],o={};if(Qm===`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(Qm===`win32`||Mm&&!Am()&&!t){r=await Fm(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Mm||(o.windowsVerbatimArguments=!0);let s=[`Start`];e.wait&&s.push(`-Wait`),t?(s.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&s.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),s.push(`-ArgumentList`,n.join(`,`))),e.target=a.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!Xm||Xm===`/`,t=!1;try{await E.default.access(Zm,E.constants.X_OK),t=!0}catch{}r=x.default.versions.electron??(Qm===`android`||e||!t)?`xdg-open`:Zm}n.length>0&&i.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}Qm===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let s=T.default.spawn(r,i,o);return e.wait?new Promise((t,n)=>{s.once(`error`,n),s.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(s)})}):(s.unref(),s)},rh=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return nh({...t,target:e})};function ih(e){if(typeof e==`string`||Array.isArray(e))return e;let{[$m]:t}=e;if(!t)throw Error(`${$m} is not supported`);return t}function ah({[Qm]:e},{wsl:t}){if(t&&Mm)return ih(t);if(!e)throw Error(`${Qm} is not supported`);return ih(e)}const oh={};Im(oh,`chrome`,()=>ah({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`]}})),Im(oh,`brave`,()=>ah({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`]}})),Im(oh,`firefox`,()=>ah({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Im(oh,`edge`,()=>ah({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Im(oh,`browser`,()=>`browser`),Im(oh,`browserPrivate`,()=>`browserPrivate`);var sh=rh;async function ch(e,t=void 0){try{(await sh(e)).once(`error`,n=>{console.log(mf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(mf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function lh(e){let t=e||fh();if((0,o.existsSync)(t)){let e=(0,o.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function uh(e,t){let n=t||fh();(0,o.existsSync)((0,b.dirname)(n))||(0,o.mkdirSync)((0,b.dirname)(n),{recursive:!0}),(0,o.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function dh(e){let t=e||fh();(0,o.existsSync)(t)&&(0,o.unlinkSync)(t)}function fh(){let e=Dd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,b.join)(e[0],`auth.json`)}function ph(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,_.useState)(),[s,c]=(0,_.useState)(()=>lh(i)),[l,u]=(0,_.useState)(),d=(0,_.useRef)(n),f=(0,_.useRef)(r);(0,_.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,_.useCallback)(async()=>{u(void 0);try{let e=lh(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new sd({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=(0,_.useCallback)(async()=>{u(void 0);try{let e=new sd,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();uh(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=(0,_.useCallback)(()=>{dh(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,_.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function mh(e){let{directory:t,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,_.useMemo)(()=>n.resolveConfig(t),[t]),[s,c]=(0,_.useState)(void 0),[l,u]=(0,_.useState)(void 0),[d,f]=(0,_.useState)(`building`),p=(0,_.useRef)(r),m=(0,_.useRef)(i),h=(0,_.useRef)(a);return(0,_.useEffect)(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),(0,_.useEffect)(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),h.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),(0,_.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function hh(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function gh(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const _h=100,vh=/^\.+(\\|\/)|^\.+$/,yh=/[. ]+$/,bh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,xh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Sh=e=>e===``,Ch=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,wh=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Th;function Eh(){return Th??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Th}function Dh(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(hh().test(n)||[...n].some(e=>xh.test(e)&&!Sh(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(wh,` `),n.length>0&&(e=e.replaceAll(Ch,`$1`)),e=e.replace(yh,``),e=e.replace(vh,n),e=e.replace(hh(),n),e=e.replaceAll(bh,e=>Sh(e)?e:n),e.length===0&&(e=n),e=gh().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=Oh(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Oh(n,a)+i}}return e}function Oh(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Eh().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function kh(e){return`${e}.lock`}function Ah(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function jh(e,t={}){let n=kh(e),r=process.pid.toString();try{return o.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(o.readFileSync(n,`utf8`),10)}catch{return o.unlinkSync(n),jh(e,{...t,stale:0})}if(!Ah(i))try{return o.unlinkSync(n),jh(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return jh(e,{...t,stale:0});throw n}return!1}}async function Mh(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=b.resolve(e),i=0;for(;i<=n.retries;){if(jh(r,n))return()=>Nh(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 Nh(e){let t=b.resolve(e),n=kh(t);try{if(parseInt(o.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}o.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Ph(e){let t=b.resolve(e),n=kh(t);try{if(!o.existsSync(n))return{locked:!1};let e=o.readFileSync(n,`utf8`),t=parseInt(e,10);return Ah(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Fh=e=>{o.mkdirSync(e,{recursive:!0})},Ih=e=>{try{o.fdatasyncSync(e)}catch{}try{o.closeSync(e)}catch{}},Lh=e=>{try{let t=o.openSync(e,`r`);try{o.fsyncSync(t)}finally{o.closeSync(t)}}catch{}},Rh=(e,t)=>{let n=b.dirname(e);Fh(n);let r=b.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=o.openSync(r,`w`),o.writeFileSync(i,t,`utf-8`),Ih(i),i=void 0,o.renameSync(r,e),Lh(e),Lh(n)}catch(e){if(i!==void 0)try{o.closeSync(i)}catch{}try{o.rmSync(r,{force:!0})}catch{}throw e}},zh=(e,t)=>{let n=new Map,r,i=e=>{if(o.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(e,`utf-8`))},a=(e,t)=>{Rh(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=b.join(e,`index.json`);Fh(e),o.existsSync(t)||o.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Mh(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=b.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=b.join(e,`index.json`);a(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return b.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=b.join(e,n);if(o.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),o=Dh(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=o,t.current=i;let r=b.join(e,o);a(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!o.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=b.join(e,i),a=o.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let s=Ph(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await u(r);if(!a){let t=Dh(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=b.join(e,t);Fh(e),o.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),a=i}finally{await n()}}if(i?.force){let e=Ph(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await Mh(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let i=b.join(e,n);try{o.rmSync(i,{force:!0}),Lh(e)}catch{}}}finally{await t()}},async release(){try{p()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Bh=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,s,c=new Map,l=new Map,u=b.join(e,`index.json`),d=()=>{try{if(!o.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=o.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let i=b.join(e,n);try{let e=o.statSync(i,{throwIfNoEntry:!1}),a=l.get(n);if(!e){a&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(c=Ph(i)),!a||a.mtime!==s||a.locked!==c.locked||a.pid!==c.pid){let e;e=!a||a.mtime!==s?JSON.parse(o.readFileSync(i,`utf-8`)):a.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},g=()=>{if(a)return;try{o.mkdirSync(e,{recursive:!0})}catch{}a=o.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return i.size===0&&g(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function Vh({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=Hh}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=(0,m.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const Hh=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(m.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},Uh=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function Wh(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var Gh=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=zh(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=Bh(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.locked?`streaming`:`idle`,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=>{let t=e instanceof Error?e.message:String(e);this.onError?.(t)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!Wh(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!(0,m.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await Vh({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,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 Kh(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=(0,_.useRef)(null),[c,l]=(0,_.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,_.useEffect)(()=>{s.current&&s.current.dispose();let e=new Gh({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}),n=e.subscribe(e=>{l(e)});return l(e.getState()),s.current=e,()=>{n(),e.dispose(),s.current=null}},[t,r]),(0,_.useEffect)(()=>{s.current&&s.current.setAgent(n)},[n]);let u=(0,_.useCallback)(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=(0,_.useCallback)(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=(0,_.useCallback)(()=>{s.current&&s.current.stopStreaming()},[]),p=(0,_.useCallback)(async()=>{s.current&&await s.current.resetChat()},[]),m=(0,_.useCallback)(()=>{s.current&&s.current.clearQueue()},[]),h=(0,_.useCallback)(async e=>{s.current&&await s.current.deleteMessages([e])},[]),g=(0,_.useCallback)(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,stopStreaming:f,resetChat:p,clearQueue:m,deleteMessage:h,start:g}}function qh(e){return(0,f.join)(e,`.blink`,`devhook.txt`)}function Jh(e){return(0,p.existsSync)(qh(e))}function Yh(e){let t=qh(e);if((0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`).trim()}function Xh(e){let t=qh(e);if((0,p.mkdirSync)((0,f.dirname)(t),{recursive:!0}),(0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,p.writeFileSync)(t,n),n}const Zh=(e,t)=>e.json({error:t},400),Qh=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}},$h=()=>new t.Hono,eg=$h().get(`/:key`,async e=>{let{key:t,err:n}=Qh(e);if(n)return Zh(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Zh(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Zh(t,`Value must be a string`):Zh(t,`Value is required`)}),async e=>{let{key:t,err:n}=Qh(e);if(n)return Zh(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Qh(e);return n?Zh(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),tg=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`}},ng=t.validator(`param`,e=>({id:e.id})),rg=$h().post(`/:key`,async e=>{let{key:t,err:n}=tg(e);return n?Zh(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,ng,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,ng,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,t.validator(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):Zh(e,`ID is required`)}).delete(`/:id/messages`,ng,t.validator(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,ng,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,ng,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,ng,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),ig=$h().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),ag=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,eg).route(`/chat`,rg).route(`/otlp`,ig);var og=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function sg(e){return typeof e==`string`&&og.test(e)}var cg=sg;function lg(e){if(!cg(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var ug=lg;const $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function dg(e,t=0){return($[e[t+0]]+$[e[t+1]]+$[e[t+2]]+$[e[t+3]]+`-`+$[e[t+4]]+$[e[t+5]]+`-`+$[e[t+6]]+$[e[t+7]]+`-`+$[e[t+8]]+$[e[t+9]]+`-`+$[e[t+10]]+$[e[t+11]]+$[e[t+12]]+$[e[t+13]]+$[e[t+14]]+$[e[t+15]]).toLowerCase()}function fg(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}const pg=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,mg=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function hg(e,t,n,r,i,a){let o=typeof n==`string`?fg(n):n,s=typeof r==`string`?ug(r):r;if(typeof r==`string`&&(r=ug(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return dg(c)}function gg(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,u.createHash)(`sha1`).update(e).digest()}var _g=gg;function vg(e,t,n,r){return hg(80,_g,e,t,n,r)}vg.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,vg.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var yg=vg;function bg(e){let n=(0,b.join)(e.dataDirectory,`chats`),r={},i=(0,b.join)(e.dataDirectory,`storage.json`);o.existsSync(i)&&(r=JSON.parse(o.readFileSync(i,`utf-8`)));let a=new Map,s=t=>{let r=a.get(t);return r||(r=new Gh({chatId:t,chatsDirectory:n}),a.set(t,r)),r.setAgent(e.getAgent()),r},c={async upsert(e){let t=yg(JSON.stringify(e),yg.URL),n=s(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=s(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return s(e).getState().messages},async sendMessages(e,t,n){let r=s(e),i=t.map(e=>Uh(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await s(e).deleteMessages(t)},async start(e){await s(e).start()},async stop(e){await s(e).stop()},async delete(e){await s(e).resetChat()}},l={get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},u=(0,d.createServer)(t.createServerAdapter(e=>ag.fetch(e,{chat:c,store:l})));u.listen(e.port??0);let f=zh(n,`id`);return{url:`http://127.0.0.1:${u.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of a.values())e.dispose();a.clear(),f.dispose(),u.close()}}}function xg({agent:e,capabilities:n,messages:r}){let[i,a]=(0,_.useState)(void 0),[o,s]=(0,_.useState)(!0),[c,l]=(0,_.useState)(void 0),u=(0,_.useRef)(c);(0,_.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,_.useState)(()=>t.lastUIOptions(r));(0,_.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,_.useState)(void 0),h=(0,_.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=(0,_.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))h(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);(0,_.useEffect)(()=>{if(!d&&!c){m(void 0);return}g()},[d,c,g]);let v=(0,_.useRef)(void 0),y=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,_.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),v.current=void 0;return}let t=p?JSON.stringify(p):``;if(v.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,_.useCallback)((e,t)=>{g({[e]:t})},[g]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Sg(e){let t=(0,_.useRef)(e.onRequest);(0,_.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=(0,_.useState)(`disconnected`);return(0,_.useEffect)(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=(0,b.join)(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Mh(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=Ph(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(mf.red(`\nError: Another ${mf.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(mf.red(`Please stop the other process and try again.
|
|
142
|
-
`)),process.exit(1)}let t
|
|
141
|
+
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Am=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&up(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},jm=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=km();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let Mm;function Nm(){try{return o.default.statSync(`/.dockerenv`),!0}catch{return!1}}function Pm(){try{return o.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Fm(){return Mm===void 0&&(Mm=Nm()||Pm()),Mm}let Im;const Lm=()=>{try{return o.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function Rm(){return Im===void 0&&(Im=Lm()||Fm()),Im}const zm=()=>{if(x.default.platform!==`linux`)return!1;if(S.default.release().toLowerCase().includes(`microsoft`))return!Rm();try{return o.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Rm():!1}catch{return!1}};var Bm=x.default.env.__IS_WSL_TEST__?zm:zm();const Vm=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await E.default.access(n,E.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await E.default.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Hm=async()=>`${await Vm()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Um=async()=>Bm?Hm():`${x.default.env.SYSTEMROOT||x.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Wm(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 Gm=(0,l.promisify)(T.execFile);async function Km(){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Gm(`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 qm=(0,l.promisify)(T.execFile);async function Jm(e,{humanReadableOutput:t=!0,signal:n}={}){if(x.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await qm(`osascript`,[`-e`,e,r],i);return a.trim()}async function Ym(e){return Jm(`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 Xm=(0,l.promisify)(T.execFile),Zm={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 Qm=class extends Error{};async function $m(e=Xm){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 Qm(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Zm[r];if(!i)throw new Qm(`Unknown browser ID: ${r}`);return i}const eh=(0,l.promisify)(T.execFile),th=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function nh(){if(x.default.platform===`darwin`){let e=await Km();return{name:await Ym(e),id:e}}if(x.default.platform===`linux`){let{stdout:e}=await eh(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:th(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(x.default.platform===`win32`)return $m();throw Error(`Only macOS, Linux, and Windows are supported`)}const rh=(0,l.promisify)(T.default.execFile),ih=b.default.dirname((0,s.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),ah=b.default.join(ih,`xdg-open`),{platform:oh,arch:sh}=x.default;async function ch(){let e=await Um(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=a.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await rh(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[i]?{id:o[i]}:{}}const lh=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},uh=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return lh(e.app,t=>uh({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return lh(t,t=>uh({...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=Bm?await ch():await nh();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),uh({...e,app:{name:mh[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],o={};if(oh===`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(oh===`win32`||Bm&&!Rm()&&!t){r=await Um(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Bm||(o.windowsVerbatimArguments=!0);let s=[`Start`];e.wait&&s.push(`-Wait`),t?(s.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&s.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),s.push(`-ArgumentList`,n.join(`,`))),e.target=a.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!ih||ih===`/`,t=!1;try{await E.default.access(ah,E.constants.X_OK),t=!0}catch{}r=x.default.versions.electron??(oh===`android`||e||!t)?`xdg-open`:ah}n.length>0&&i.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}oh===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let s=T.default.spawn(r,i,o);return e.wait?new Promise((t,n)=>{s.once(`error`,n),s.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(s)})}):(s.unref(),s)},dh=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return uh({...t,target:e})};function fh(e){if(typeof e==`string`||Array.isArray(e))return e;let{[sh]:t}=e;if(!t)throw Error(`${sh} is not supported`);return t}function ph({[oh]:e},{wsl:t}){if(t&&Bm)return fh(t);if(!e)throw Error(`${oh} is not supported`);return fh(e)}const mh={};Wm(mh,`chrome`,()=>ph({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`]}})),Wm(mh,`brave`,()=>ph({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`]}})),Wm(mh,`firefox`,()=>ph({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Wm(mh,`edge`,()=>ph({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Wm(mh,`browser`,()=>`browser`),Wm(mh,`browserPrivate`,()=>`browserPrivate`);var hh=dh;async function gh(e,t=void 0){try{(await hh(e)).once(`error`,n=>{console.log(Sf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(Sf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function _h(e){let t=e||bh();if((0,o.existsSync)(t)){let e=(0,o.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function vh(e,t){let n=t||bh();(0,o.existsSync)((0,b.dirname)(n))||(0,o.mkdirSync)((0,b.dirname)(n),{recursive:!0}),(0,o.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function yh(e){let t=e||bh();(0,o.existsSync)(t)&&(0,o.unlinkSync)(t)}function bh(){let e=Fd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,b.join)(e[0],`auth.json`)}function xh(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,_.useState)(),[s,c]=(0,_.useState)(()=>_h(i)),[l,u]=(0,_.useState)(),d=(0,_.useRef)(n),f=(0,_.useRef)(r);(0,_.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,_.useCallback)(async()=>{u(void 0);try{let e=_h(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new hd({baseURL:`https://blink.so`});t.authToken=e;let n={email:(await t.users.me()).email};o(n),d.current?.(n)}catch(e){o(void 0),u(e instanceof Error?e.message:String(e)),d.current?.(void 0)}},[i]),m=(0,_.useCallback)(async()=>{u(void 0);try{let e=new hd,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();vh(t,i),c(t);let r={email:n.email};return o(r),d.current?.(r),r}catch(e){let t=e instanceof Error?e.message:String(e);throw u(t),e}},[i]),h=(0,_.useCallback)(()=>{yh(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,_.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}let Sh=Promise.resolve();var Ch=class{constructor(e){this.printLog=e}setPrintLog(e){this.printLog=e}error(e,...t){Sh=Sh.then(()=>this.printLog(`error`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}log(e,...t){Sh=Sh.then(()=>this.printLog(`log`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}flush(){return Sh}};const wh=(0,_.createContext)(void 0);function Th(e){let{directory:t,logger:r,onBuildStart:i,onBuildSuccess:a,onBuildError:o}=typeof e==`string`?{directory:e,logger:new Ch(async()=>{})}:e,s=(0,_.useMemo)(()=>n.resolveConfig(t),[t]),[c,l]=(0,_.useState)(void 0),[u,d]=(0,_.useState)(void 0),[f,p]=(0,_.useState)(`building`),m=(0,_.useRef)(i),h=(0,_.useRef)(a),g=(0,_.useRef)(o);return(0,_.useEffect)(()=>{m.current=i,h.current=a,g.current=o},[i,a,o]),(0,_.useEffect)(()=>{let e=new AbortController;return s.build({cwd:t,entry:s.entry,outdir:s.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{p(`building`),l(void 0),d(void 0),m.current?.()},onResult:e=>{`error`in e?(l(e.error),p(`error`),g.current?.(e.error)):(d(e),p(`success`),h.current?.(e))}}).catch(e=>{r.error(`system`,`error`,e),p(`error`),l(e),g.current?.(e)}),()=>{e.abort()}},[t]),(0,_.useMemo)(()=>({error:c,status:f,result:u,entry:s.entry,outdir:s.outdir}),[c,f,u,s.entry,s.outdir])}function Eh(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Dh(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Oh=100,kh=/^\.+(\\|\/)|^\.+$/,Ah=/[. ]+$/,jh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Mh=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Nh=e=>e===``,Ph=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Fh=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Ih;function Lh(){return Ih??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Ih}function Rh(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Eh().test(n)||[...n].some(e=>Mh.test(e)&&!Nh(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Fh,` `),n.length>0&&(e=e.replaceAll(Ph,`$1`)),e=e.replace(Ah,``),e=e.replace(kh,n),e=e.replace(Eh(),n),e=e.replaceAll(jh,e=>Nh(e)?e:n),e.length===0&&(e=n),e=Dh().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=zh(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=zh(n,a)+i}}return e}function zh(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Lh().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Bh(e){return`${e}.lock`}function Vh(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Hh(e,t={}){let n=Bh(e),r=process.pid.toString();try{return o.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(o.readFileSync(n,`utf8`),10)}catch{return o.unlinkSync(n),Hh(e,{...t,stale:0})}if(!Vh(i))try{return o.unlinkSync(n),Hh(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Hh(e,{...t,stale:0});throw n}return!1}}async function Uh(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=b.resolve(e),i=0;for(;i<=n.retries;){if(Hh(r,n))return()=>Wh(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 Wh(e){let t=b.resolve(e),n=Bh(t);try{if(parseInt(o.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}o.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Gh(e){let t=b.resolve(e),n=Bh(t);try{if(!o.existsSync(n))return{locked:!1};let e=o.readFileSync(n,`utf8`),t=parseInt(e,10);return Vh(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Kh=e=>{o.mkdirSync(e,{recursive:!0})},qh=e=>{try{o.fdatasyncSync(e)}catch{}try{o.closeSync(e)}catch{}},Jh=e=>{try{let t=o.openSync(e,`r`);try{o.fsyncSync(t)}finally{o.closeSync(t)}}catch{}},Yh=(e,t)=>{let n=b.dirname(e);Kh(n);let r=b.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=o.openSync(r,`w`),o.writeFileSync(i,t,`utf-8`),qh(i),i=void 0,o.renameSync(r,e),Jh(e),Jh(n)}catch(e){if(i!==void 0)try{o.closeSync(i)}catch{}try{o.rmSync(r,{force:!0})}catch{}throw e}},Xh=(e,t)=>{let n=new Map,r,i=e=>{if(o.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(e,`utf-8`))},a=(e,t)=>{Yh(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=b.join(e,`index.json`);Kh(e),o.existsSync(t)||o.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Uh(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=b.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=b.join(e,`index.json`);a(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return b.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=b.join(e,n);if(o.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(o.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),o=Rh(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=o,t.current=i;let r=b.join(e,o);a(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!o.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=b.join(e,i),a=o.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let s=Gh(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await u(r);if(!a){let t=Rh(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=b.join(e,t);Kh(e),o.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),a=i}finally{await n()}}if(i?.force){let e=Gh(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await Uh(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let i=b.join(e,n);try{o.rmSync(i,{force:!0}),Jh(e)}catch{}}}finally{await t()}},async release(){try{p()}finally{n.delete(r)}}}},dispose(){n.clear()}}},Zh=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,s,c=new Map,l=new Map,u=b.join(e,`index.json`),d=()=>{try{if(!o.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=o.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let i=b.join(e,n);try{let e=o.statSync(i,{throwIfNoEntry:!1}),a=l.get(n);if(!e){a&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(c=Gh(i)),!a||a.mtime!==s||a.locked!==c.locked||a.pid!==c.pid){let e;e=!a||a.mtime!==s?JSON.parse(o.readFileSync(i,`utf-8`)):a.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},g=()=>{if(a)return;try{o.mkdirSync(e,{recursive:!0})}catch{}a=o.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return i.size===0&&g(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){a&&=(a.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function Qh({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=$h}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,id:e},{signal:r}),l=(0,m.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const $h=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(m.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},eg=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function tg(e){return typeof e==`object`&&e?.__blink_internal!==void 0}function ng(e){return typeof e.metadata==`object`&&e.metadata!==null&&`__blink_log`in e.metadata&&e.metadata.__blink_log===!0&&`level`in e.metadata&&`source`in e.metadata&&`message`in e.metadata}var rg=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];logQueue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=Xh(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=Zh(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.locked?`streaming`:`idle`,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=>{let t=e instanceof Error?e.message:String(e);this.onError?.(t)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!tg(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue,queuedLogs:this.logQueue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async queueLogMessage({message:e,level:t,source:n}){let r=`(EDIT MODE NOTE) ${n===`agent`?`The agent`:"The `blink dev` CLI"} printed the following ${t}:\n\`\`\`\n${(0,l.stripVTControlCharacters)(e)}\n\`\`\`\n`,i={id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`user`,parts:[{type:`text`,text:r}],metadata:{__blink_log:!0,level:t,source:n,message:e},mode:`edit`};this.logQueue.push(i),this.notifyListeners()}async flushLogQueue(e){if(this.logQueue.length===0)return;let t=[...this.logQueue];this.logQueue=[],await this.upsertMessages(t,e)}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId),await this.flushLogQueue(e);let n=!0;for(;this.queue.length>0||n;)try{var t=Xs();n=!1;let r=new AbortController;this.abortController=r;let i=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),i.length>0&&await this.upsertMessages(i,e);let a=this.chat.messages;this.filterMessages&&(a=a.filter(this.filterMessages)),a=a.map(e=>({...e,parts:e.parts.map(e=>!(0,m.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})})),t.u(await this.agent.agentLock.read());let o=performance.now(),s=await Qh({agent:this.agent,id:this.chatId,signal:r.signal,messages:a}),c=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)},l=s.getReader();r.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||r.signal.aborted)break;u||=performance.now()-o,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let n={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(n):n,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}catch(e){t.e=e}finally{t.d()}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.status=`idle`,e&&(await this.flushLogQueue(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.stopStreaming()}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=[],this.logQueue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function ig(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=(0,_.useRef)(null),[c,l]=(0,_.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[],queuedLogs:[]});(0,_.useEffect)(()=>{s.current&&s.current.dispose();let e=new rg({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}),n=e.subscribe(e=>{l(e)});return l(e.getState()),s.current=e,()=>{n(),e.dispose(),s.current=null}},[t,r]),(0,_.useEffect)(()=>{s.current&&s.current.setAgent(n)},[n]);let u=(0,_.useCallback)(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=(0,_.useCallback)(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=(0,_.useCallback)(async e=>{s.current&&await s.current.queueLogMessage(e)},[]),p=(0,_.useCallback)(()=>{s.current&&s.current.stopStreaming()},[]),m=(0,_.useCallback)(async()=>{s.current&&await s.current.resetChat()},[]),h=(0,_.useCallback)(()=>{s.current&&s.current.clearQueue()},[]),g=(0,_.useCallback)(async e=>{s.current&&await s.current.deleteMessages([e])},[]),v=(0,_.useCallback)(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,queueLogMessage:f,stopStreaming:p,resetChat:m,clearQueue:h,deleteMessage:g,start:v}}function ag(e){return(0,f.join)(e,`.blink`,`devhook.txt`)}function og(e){return(0,p.existsSync)(ag(e))}function sg(e){let t=ag(e);if((0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`).trim()}function cg(e){let t=ag(e);if((0,p.mkdirSync)((0,f.dirname)(t),{recursive:!0}),(0,p.existsSync)(t))return(0,p.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,p.writeFileSync)(t,n),n}const lg=(e,t)=>e.json({error:t},400),ug=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}},dg=()=>new t.Hono,fg=dg().get(`/:key`,async e=>{let{key:t,err:n}=ug(e);if(n)return lg(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?lg(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:lg(t,`Value must be a string`):lg(t,`Value is required`)}),async e=>{let{key:t,err:n}=ug(e);if(n)return lg(e,n);let{value:r}=e.req.valid(`json`);return await e.env.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=ug(e);return n?lg(e,n):(await e.env.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),pg=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`}},mg=t.validator(`param`,e=>({id:e.id})),hg=dg().post(`/:key`,async e=>{let{key:t,err:n}=pg(e);return n?lg(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,mg,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,mg,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,t.validator(`json`,e=>({id:e.id,messages:e.messages,options:e.options})),async e=>{let{id:t,messages:n,options:r}=e.req.valid(`json`);return t?(await e.env.chat.sendMessages(t,n,r),e.body(null,204)):lg(e,`ID is required`)}).delete(`/:id/messages`,mg,t.validator(`query`,e=>(typeof e.message==`string`&&(e.message=[e.message]),{messages:e.message})),async e=>{let{id:t}=e.req.valid(`param`),{messages:n}=e.req.valid(`query`);return await e.env.chat.deleteMessages(t,n),e.body(null,204)}).post(`/:id/start`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,mg,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),gg=dg().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),_g=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,fg).route(`/chat`,hg).route(`/otlp`,gg);var vg=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function yg(e){return typeof e==`string`&&vg.test(e)}var bg=yg;function xg(e){if(!bg(e))throw TypeError(`Invalid UUID`);let t;return Uint8Array.of((t=parseInt(e.slice(0,8),16))>>>24,t>>>16&255,t>>>8&255,t&255,(t=parseInt(e.slice(9,13),16))>>>8,t&255,(t=parseInt(e.slice(14,18),16))>>>8,t&255,(t=parseInt(e.slice(19,23),16))>>>8,t&255,(t=parseInt(e.slice(24,36),16))/1099511627776&255,t/4294967296&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255)}var Sg=xg;const $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function Cg(e,t=0){return($[e[t+0]]+$[e[t+1]]+$[e[t+2]]+$[e[t+3]]+`-`+$[e[t+4]]+$[e[t+5]]+`-`+$[e[t+6]]+$[e[t+7]]+`-`+$[e[t+8]]+$[e[t+9]]+`-`+$[e[t+10]]+$[e[t+11]]+$[e[t+12]]+$[e[t+13]]+$[e[t+14]]+$[e[t+15]]).toLowerCase()}function wg(e){e=unescape(encodeURIComponent(e));let t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t}const Tg=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Eg=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Dg(e,t,n,r,i,a){let o=typeof n==`string`?wg(n):n,s=typeof r==`string`?Sg(r):r;if(typeof r==`string`&&(r=Sg(r)),r?.length!==16)throw TypeError(`Namespace must be array-like (16 iterable integer values, 0-255)`);let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a||=0;for(let e=0;e<16;++e)i[a+e]=c[e];return i}return Cg(c)}function Og(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,u.createHash)(`sha1`).update(e).digest()}var kg=Og;function Ag(e,t,n,r){return Dg(80,kg,e,t,n,r)}Ag.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Ag.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var jg=Ag;function Mg(e){let n=(0,b.join)(e.dataDirectory,`chats`),r={},i=(0,b.join)(e.dataDirectory,`storage.json`);o.existsSync(i)&&(r=JSON.parse(o.readFileSync(i,`utf-8`)));let a=new Map,s=t=>{let r=a.get(t);return r||(r=new rg({chatId:t,chatsDirectory:n}),a.set(t,r)),r.setAgent(e.getAgent()),r},c={async upsert(e){let t=jg(JSON.stringify(e),jg.URL),n=s(t).getState(),r=n.messages.length===0&&!n.created_at;return{id:n.id,created:r,createdAt:n.created_at??new Date().toISOString(),key:e}},async get(e){let t=s(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return s(e).getState().messages},async sendMessages(e,t,n){let r=s(e),i=t.map(e=>eg(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await s(e).deleteMessages(t)},async start(e){await s(e).start()},async stop(e){await s(e).stop()},async delete(e){await s(e).resetChat()}},l={get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],o.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},u=(0,d.createServer)(t.createServerAdapter(e=>_g.fetch(e,{chat:c,store:l})));u.listen(e.port??0);let f=Xh(n,`id`);return{url:`http://127.0.0.1:${u.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of a.values())e.dispose();a.clear(),f.dispose(),u.close()}}}function Ng({agent:e,capabilities:n,messages:r}){let[i,a]=(0,_.useState)(void 0),[o,s]=(0,_.useState)(!0),[c,l]=(0,_.useState)(void 0),u=(0,_.useRef)(c);(0,_.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,_.useState)(()=>t.lastUIOptions(r));(0,_.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,_.useState)(void 0),h=(0,_.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),g=(0,_.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))h(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,h]);(0,_.useEffect)(()=>{if(!d&&!c){m(void 0);return}g()},[d,c,g]);let v=(0,_.useRef)(void 0),y=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,_.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),v.current=void 0;return}let t=p?JSON.stringify(p):``;if(v.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,_.useCallback)((e,t)=>{g({[e]:t})},[g]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Pg(e){let t=(0,_.useRef)(e.onRequest);(0,_.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=(0,_.useState)(`disconnected`);return(0,_.useEffect)(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=(0,b.join)(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Uh(c,{stale:!0,retries:0})}catch(t){if(t&&typeof t==`object`&&`code`in t&&t.code===`ELOCKED`){let t=``;try{let e=Gh(c);e.locked&&e.pid&&(t=` (PID: ${e.pid})`)}catch{}e.logger.error(`system`,Sf.red(`\nError: Another ${Sf.bold(`blink dev`)} process is already running in this directory${t}.`)),e.logger.error(`system`,Sf.red(`Please stop the other process and try again.
|
|
142
|
+
`)),process.exit(1)}let n=t&&typeof t==`object`&&`message`in t?String(t.message):String(t);e.logger.error(`system`,Sf.yellow(`\nWarning: Failed to acquire devhook lock: ${n}`)),e.logger.error(`system`,Sf.yellow(`Continuing without lock. Multiple ${Sf.bold(`blink dev`)} processes may conflict with each other.\n`))}let l=()=>{if(!(n||o)){if(o=!0,i){try{i.dispose()}catch{}i=void 0}i=new hd({baseURL:`https://blink.so`}).devhook.listen({id:e.id,onRequest:async e=>t.current(e),onConnect:()=>{o=!1,r(`connected`)},onDisconnect:()=>{o=!1,r(`disconnected`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))},onError:e=>{o=!1,r(`error`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))}})}};l()})(),()=>{if(n=!0,a&&=(clearTimeout(a),void 0),i){try{i.dispose()}catch{}i=void 0}if(s)try{s()}catch(t){e.logger.error(`system`,`Failed to release devhook lock:`,t)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var Fg=e.__commonJSMin(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),Ig=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=Fg().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
143
143
|
`);let r;for(;(r=f.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
|
|
144
|
-
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),Tg=e.__toESM(wg());async function Eg(e,t){let n=e;for(;n!==(0,f.dirname)(n);){let e=(0,f.join)(n,t);try{return await(0,h.stat)(e),e}catch{}n=(0,f.dirname)(n)}}function Dg(e,t=`.env.local`){let[n,r]=(0,_.useState)({});return(0,_.useEffect)(()=>{let n,i=e=>{try{let t=(0,p.readFileSync)(e,`utf-8`),n=(0,Tg.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return Eg(e,t).then(e=>{if(!e){r({});return}i(e),n=(0,p.watch)(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}var Og=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},kg=class extends Og{};new kg;function Ag(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function jg(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Mg(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Ng(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Pg(e,t){return Mg(e,t,``)}function Fg(e,t){return Ng(e,t,``)}function Ig(e,t){return t.slice(0,Lg(e,t))}function Lg(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Rg(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function zg(e){let t=e.match(/^\s*/);return t?t[0]:``}const Bg=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,Vg=RegExp(`[${Bg}]+|\\s+|[^${Bg}]`,`ug`);var Hg=class extends Og{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match(Vg)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&Ug(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Ug(n,i,r,null),e}};new Hg;function Ug(e,t,n,r){if(t&&n){let i=zg(t.value),a=Rg(t.value),o=zg(n.value),s=Rg(n.value);if(e){let r=Ag(i,o);e.value=Ng(e.value,o,r),t.value=Pg(t.value,r),n.value=Pg(n.value,r)}if(r){let e=jg(a,s);r.value=Mg(r.value,s,e),t.value=Fg(t.value,e),n.value=Fg(n.value,e)}}else if(n){if(e){let e=zg(n.value);n.value=n.value.substring(e.length)}if(r){let e=zg(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=zg(r.value),i=zg(t.value),a=Rg(t.value),o=Ag(n,i);t.value=Pg(t.value,o);let s=jg(Pg(n,o),a);t.value=Fg(t.value,s),r.value=Mg(r.value,n,s),e.value=Ng(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=zg(r.value),n=Rg(t.value),i=Ig(n,e);t.value=Fg(t.value,i)}else if(e){let n=Rg(e.value),r=zg(t.value),i=Ig(n,r);t.value=Pg(t.value,i)}}var Wg=class extends Og{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Bg}]+|[^\\S\\n\\r]+|[^${Bg}]`,`ug`);return e.match(t)||[]}};new Wg;var Gg=class extends Og{constructor(){super(...arguments),this.tokenize=Jg}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
144
|
+
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function y(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function b(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),Lg=e.__toESM(Ig());async function Rg(e,t){let n=e;for(;n!==(0,f.dirname)(n);){let e=(0,f.join)(n,t);try{return await(0,h.stat)(e),e}catch{}n=(0,f.dirname)(n)}}function zg(e,t,n=`.env.local`){let[r,i]=(0,_.useState)({});return(0,_.useEffect)(()=>{let r,a=e=>{try{let t=(0,p.readFileSync)(e,`utf-8`),n=(0,Lg.parse)(t);i(n)}catch(e){t.error(`system`,`Error reading ${n}:`,e),i({})}};return Rg(e,n).then(e=>{if(!e){i({});return}a(e),r=(0,p.watch)(e,{persistent:!1},()=>{a(e)})}),()=>{r&&r.close()}},[e,n]),r}var Bg=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},Vg=class extends Bg{};new Vg;function Hg(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function Ug(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Wg(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Gg(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function Kg(e,t){return Wg(e,t,``)}function qg(e,t){return Gg(e,t,``)}function Jg(e,t){return t.slice(0,Yg(e,t))}function Yg(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Xg(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Zg(e){let t=e.match(/^\s*/);return t?t[0]:``}const Qg=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,$g=RegExp(`[${Qg}]+|\\s+|[^${Qg}]`,`ug`);var e_=class extends Bg{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match($g)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&t_(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&t_(n,i,r,null),e}};new e_;function t_(e,t,n,r){if(t&&n){let i=Zg(t.value),a=Xg(t.value),o=Zg(n.value),s=Xg(n.value);if(e){let r=Hg(i,o);e.value=Gg(e.value,o,r),t.value=Kg(t.value,r),n.value=Kg(n.value,r)}if(r){let e=Ug(a,s);r.value=Wg(r.value,s,e),t.value=qg(t.value,e),n.value=qg(n.value,e)}}else if(n){if(e){let e=Zg(n.value);n.value=n.value.substring(e.length)}if(r){let e=Zg(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zg(r.value),i=Zg(t.value),a=Xg(t.value),o=Hg(n,i);t.value=Kg(t.value,o);let s=Ug(Kg(n,o),a);t.value=qg(t.value,s),r.value=Wg(r.value,n,s),e.value=Gg(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Zg(r.value),n=Xg(t.value),i=Jg(n,e);t.value=qg(t.value,i)}else if(e){let n=Xg(e.value),r=Zg(t.value),i=Jg(n,r);t.value=Kg(t.value,i)}}var n_=class extends Bg{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Qg}]+|[^\\S\\n\\r]+|[^${Qg}]`,`ug`);return e.match(t)||[]}};new n_;var r_=class extends Bg{constructor(){super(...arguments),this.tokenize=o_}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
145
145
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
146
146
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
147
147
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
148
|
-
`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};const
|
|
149
|
-
`));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function
|
|
150
|
-
`)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function
|
|
148
|
+
`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};const i_=new r_;function a_(e,t,n){return i_.diff(e,t,n)}function o_(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
149
|
+
`));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function s_(e){return e==`.`||e==`!`||e==`?`}var c_=class extends Bg{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(s_(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}};new c_;var l_=class extends Bg{tokenize(e){return e.split(/([{}:;,]|\s+)/)}};new l_;var u_=class extends Bg{constructor(){super(...arguments),this.tokenize=o_}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(d_(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};new u_;function d_(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=d_(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=d_(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}var f_=class extends Bg{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};new f_;function p_(e,t,n,r,i,a,o){let s;s=o?typeof o==`function`?{callback:o}:o:{},s.context===void 0&&(s.context=4);let c=s.context;if(s.newlineIsToken)throw Error(`newlineIsToken may not be used with patch-generation functions, only with diffing functions`);if(s.callback){let{callback:e}=s;a_(n,r,Object.assign(Object.assign({},s),{callback:t=>{let n=l(t);e(n)}}))}else return l(a_(n,r,s));function l(n){if(!n)return;n.push({value:``,lines:[]});function r(e){return e.map(function(e){return` `+e})}let o=[],s=0,l=0,u=[],d=1,f=1;for(let e=0;e<n.length;e++){let t=n[e],i=t.lines||m_(t.value);if(t.lines=i,t.added||t.removed){if(!s){let t=n[e-1];s=d,l=f,t&&(u=c>0?r(t.lines.slice(-c)):[],s-=u.length,l-=u.length)}for(let e of i)u.push((t.added?`+`:`-`)+e);t.added?f+=i.length:d+=i.length}else{if(s)if(i.length<=c*2&&e<n.length-2)for(let e of r(i))u.push(e);else{let e=Math.min(i.length,c);for(let t of r(i.slice(0,e)))u.push(t);let t={oldStart:s,oldLines:d-s+e,newStart:l,newLines:f-l+e,lines:u};o.push(t),s=0,l=0,u=[]}d+=i.length,f+=i.length}}for(let e of o)for(let t=0;t<e.lines.length;t++)e.lines[t].endsWith(`
|
|
150
|
+
`)?e.lines[t]=e.lines[t].slice(0,-1):(e.lines.splice(t+1,0,`\`),t++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:a,hunks:o}}}function m_(e){let t=e.endsWith(`
|
|
151
151
|
`),n=e.split(`
|
|
152
152
|
`).map(e=>e+`
|
|
153
|
-
`);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const
|
|
153
|
+
`);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const h_={readLineLimit:2e3,readLineLengthLimit:2e3,plainOutputCharacterLimit:8192};let g_;const __=e=>{let t=()=>g_||(g_=Promise.resolve((0,D.createInMemoryClientServer)().client),g_);return{...e({client(){return t()}}),withContext:n=>{if(n.client||=t(),typeof n.client==`function`){let t=n.client;return e({client:t})}return e({client:()=>Promise.resolve(n.client)})}}},v_=e=>{let{ansiOutput:t,...n}=e;return{type:`json`,value:n}},y_={execute_bash:__(({client:e})=>({description:"Execute a bash command in a compute instance. **ALL OUTPUT IS AUTOMATICALLY CAPTURED AND STORED** - never use pipes to filter output during execution.\n\n**Process Management:**\n- Use the returned PID with `process_wait` to get complete results\n- Use `process_grep_output` to search through the FULL stored output\n- Use `process_read_output` to read any portion of the stored output\n- **NEVER use pipes like `| grep`, `| head`, `| tail`** - run commands cleanly and analyze afterward\n\n**Output Storage:**\n- Every command's complete stdout/stderr is permanently stored\n- You can search, filter, and read from this stored output multiple times\n- No information is ever lost, even from long-running processes\n\nExample workflow:\n1. `execute_bash` returns PID 123\n2. `process_wait` on PID 123 to see if it completed\n3. `process_grep_output` on PID 123 to find errors",inputSchema:y.z.object({command:y.z.string(),working_directory:y.z.string().describe(`The working directory to execute the command in. Use '.' for the current directory.`),env:y.z.record(y.z.string(),y.z.string()),env_file:y.z.string().optional().describe(`A file to read environment variables from. e.g. .env.local`)}),execute:async(t,n)=>(await e()).request(`process_execute`,{command:`bash`,args:[`-c`,t.command],cwd:t.working_directory,env:t.env,env_file:t.env_file},{signal:n.abortSignal})})),execute_bash_sync:__(({client:e})=>({description:`Execute a bash command and return output synchronously in a compute instance. **ALL OUTPUT IS AUTOMATICALLY CAPTURED AND STORED** - never use pipes to filter output during execution.
|
|
154
154
|
|
|
155
|
-
Use the same rules as \`execute_bash\`, but the output is returned synchronously.`,inputSchema:y.z.object({command:y.z.string(),working_directory:y.z.string().describe(`The working directory to execute the command in. Use '.' for the current directory.`),env:y.z.record(y.z.string(),y.z.string()),env_file:y.z.string().optional().describe(`A file to read environment variables from. e.g. .env.local`)}),async*execute(t,n){let r=await(await e()).request(`process_execute`,{command:`bash`,args:[`-c`,t.command],cwd:t.working_directory,env:t.env,env_file:t.env_file},{signal:n.abortSignal});for await(let t of
|
|
155
|
+
Use the same rules as \`execute_bash\`, but the output is returned synchronously.`,inputSchema:y.z.object({command:y.z.string(),working_directory:y.z.string().describe(`The working directory to execute the command in. Use '.' for the current directory.`),env:y.z.record(y.z.string(),y.z.string()),env_file:y.z.string().optional().describe(`A file to read environment variables from. e.g. .env.local`)}),async*execute(t,n){let r=await(await e()).request(`process_execute`,{command:`bash`,args:[`-c`,t.command],cwd:t.working_directory,env:t.env,env_file:t.env_file},{signal:n.abortSignal});for await(let t of b_({client:await e(),pid:r.pid,abortSignal:n.abortSignal}))yield t},toModelOutput:v_})),process_send_input:__(({client:e})=>({description:`Send input to a process by PID that was started by the execute_bash tool.
|
|
156
156
|
|
|
157
157
|
Use "\r
|
|
158
|
-
" to send a newline (e.g. for an interactive prompt).`,inputSchema:y.z.object({pid:y.z.number(),data:y.z.string()}),execute:async(t,n)=>(await e()).request(`process_send_input`,{pid:t.pid,data:t.data},{signal:n.abortSignal})})),process_kill:
|
|
158
|
+
" to send a newline (e.g. for an interactive prompt).`,inputSchema:y.z.object({pid:y.z.number(),data:y.z.string()}),execute:async(t,n)=>(await e()).request(`process_send_input`,{pid:t.pid,data:t.data},{signal:n.abortSignal})})),process_kill:__(({client:e})=>({description:`Kill a process by PID that was started by the execute_bash tool.`,inputSchema:y.z.object({pid:y.z.number(),signal:y.z.string()}),execute:async(t,n)=>(await e()).request(`process_kill`,{pid:t.pid,signal:t.signal},{signal:n.abortSignal})})),process_wait:__(({client:e})=>({description:`This tool waits for a process to exit, or returns instantly if the process already has exited.
|
|
159
159
|
|
|
160
160
|
Output from the process will be returned along with it's exit code, duration, and whether the process is still running.
|
|
161
161
|
|
|
162
162
|
IMPORTANT: ALWAYS use this tool to determine the status of a process. NEVER use "ps".
|
|
163
|
-
`,inputSchema:y.z.object({pid:y.z.number(),timeout_ms:y.z.number().optional().describe(`The timeout in milliseconds to wait to return output. This does *not* kill the process, it simply returns early with current output of the process. Defaults to 25 seconds.`)}),async*execute(t,n){for await(let r of
|
|
163
|
+
`,inputSchema:y.z.object({pid:y.z.number(),timeout_ms:y.z.number().optional().describe(`The timeout in milliseconds to wait to return output. This does *not* kill the process, it simply returns early with current output of the process. Defaults to 25 seconds.`)}),async*execute(t,n){for await(let r of b_({client:await e(),pid:t.pid,abortSignal:n.abortSignal,timeoutMs:t.timeout_ms}))yield r},toModelOutput:v_})),read_file:__(({client:e})=>(0,m.tool)({description:`Reads a file from the workspace filesystem. You can access any file directly by using this tool.
|
|
164
164
|
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
|
|
165
165
|
|
|
166
166
|
Usage:
|
|
167
167
|
- The path parameter can be a relative path or an absolute path
|
|
168
|
-
- By default, it reads up to ${
|
|
168
|
+
- By default, it reads up to ${h_.readLineLimit} lines starting from the beginning of the file
|
|
169
169
|
- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
|
|
170
|
-
- Any lines longer than ${
|
|
170
|
+
- Any lines longer than ${h_.readLineLengthLimit} characters will be truncated
|
|
171
171
|
- Results are returned using cat -n format, with line numbers starting at 1
|
|
172
172
|
- This tool allows Blink to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Blink is a multimodal LLM
|
|
173
173
|
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
|
|
174
174
|
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/123/abc/T/TemporaryItems/NSIRD_screencaptureui_ZfB1tD/Screenshot.png
|
|
175
|
-
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:y.z.object({file_path:y.z.string(),line_offset:y.z.number(),line_limit:y.z.number()}),execute:async(t,n)=>await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal}),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:
|
|
175
|
+
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:y.z.object({file_path:y.z.string(),line_offset:y.z.number(),line_limit:y.z.number()}),execute:async(t,n)=>await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal}),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:__(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:y.z.object({file_path:y.z.string(),content:y.z.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:__(({client:e})=>(0,m.tool)({description:`Reads a directory from the workspace filesystem.`,inputSchema:y.z.object({directory_path:y.z.string()}),execute:async(t,n)=>(await e()).request(`read_directory`,{path:t.directory_path})})),edit_file:__(({client:e})=>({description:`This is a tool for making multiple edits to a single file in one operation. It is built on top of the "workspace_edit_file" tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the "workspace_edit_file" tool when you need to make multiple edits to the same file.
|
|
176
176
|
|
|
177
177
|
Before using this tool:
|
|
178
178
|
|
|
@@ -210,7 +210,7 @@ When making edits:
|
|
|
210
210
|
If you want to create a new file, use:
|
|
211
211
|
- A new file path, including dir name if needed
|
|
212
212
|
- First edit: empty old_string and the new file's contents as new_string
|
|
213
|
-
- Subsequent edits: normal edit operations on the created content`,inputSchema:y.z.object({file_path:y.z.string(),edits:y.z.array(y.z.object({old_string:y.z.string(),new_string:y.z.string(),expected_replacements:y.z.number()}))}),execute:async(t,n)=>{let r=await e(),i;try{i=(await r.request(`read_file`,{path:t.file_path},{signal:n.abortSignal})).content}catch{if(i=t.edits[0].new_string,t.edits.length>0&&t.edits[0].old_string===``)i=t.edits[0].new_string,t.edits.shift();else throw Error(`input is invalid: File does not exist and first edit is not for file creation.\nFile: ${t.file_path}`)}let a=i,o=[];for(let e of t.edits){let t=e.expected_replacements??1,n=e.old_string,r=e.new_string;if(n===r)throw Error(`input is invalid: old_string and new_string are identical.\nString: ${n}`);let i=
|
|
213
|
+
- Subsequent edits: normal edit operations on the created content`,inputSchema:y.z.object({file_path:y.z.string(),edits:y.z.array(y.z.object({old_string:y.z.string(),new_string:y.z.string(),expected_replacements:y.z.number()}))}),execute:async(t,n)=>{let r=await e(),i;try{i=(await r.request(`read_file`,{path:t.file_path},{signal:n.abortSignal})).content}catch{if(i=t.edits[0].new_string,t.edits.length>0&&t.edits[0].old_string===``)i=t.edits[0].new_string,t.edits.shift();else throw Error(`input is invalid: File does not exist and first edit is not for file creation.\nFile: ${t.file_path}`)}let a=i,o=[];for(let e of t.edits){let t=e.expected_replacements??1,n=e.old_string,r=e.new_string;if(n===r)throw Error(`input is invalid: old_string and new_string are identical.\nString: ${n}`);let i=x_(a,n);if(i===0)throw Error(`input is invalid: String to replace not found in file.\nString: ${n}`);if(i!==t)throw Error(`input is invalid: Found ${i} matches of the string to replace, but expected ${t}. The number of actual matches must equal the expected replacements. Please adjust your string to match or update the expected count.\nString: ${n}`)}for(let e of t.edits){let t=e.old_string,n=e.new_string;a=S_(a,t,n),o.push({old_string:t,new_string:n})}await r.request(`write_file`,{path:t.file_path,content:a},{signal:n.abortSignal});let s=p_(t.file_path,t.file_path,i,a);return{edits:o,file_path:t.file_path,structured_patch:s.hunks.map(e=>({old_start:e.oldStart,old_end:e.oldLines,new_start:e.newStart,new_end:e.newLines,lines:e.lines}))}}})),process_grep_output:__(({client:e})=>({description:`Search through the output of a running or completed process. **This is the PRIMARY tool for analyzing command output** - use this instead of piping commands to grep, tail, or re-running commands with filters.
|
|
214
214
|
|
|
215
215
|
Use this for:
|
|
216
216
|
- Finding test failures and error messages
|
|
@@ -218,7 +218,7 @@ Use this for:
|
|
|
218
218
|
- Extracting relevant information from verbose output
|
|
219
219
|
- Analyzing build or test results
|
|
220
220
|
|
|
221
|
-
Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:y.z.object({pid:y.z.number(),pattern:y.z.string(),before_lines:y.z.number(),after_lines:y.z.number()}),execute:async(t,n)=>{let r;try{r=new RegExp(t.pattern)}catch{throw Error(`Invalid regex pattern: ${t.pattern}`)}let{lines:i}=await(await e()).request(`process_read_plain_output`,{pid:t.pid},{signal:n.abortSignal}),a=[];for(let e=0;e<i.length;e++)if(i[e].match(r)){let n=Math.max(0,e-t.before_lines),r=Math.min(i.length-1,e+t.after_lines),o=i.slice(n,r+1);a.push({line_number:e,lines:o})}if(a.length>256)throw Error(`Too many matches. Please refine your search.`);return{matches:a,total_matches:a.length}}}))},
|
|
221
|
+
Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:y.z.object({pid:y.z.number(),pattern:y.z.string(),before_lines:y.z.number(),after_lines:y.z.number()}),execute:async(t,n)=>{let r;try{r=new RegExp(t.pattern)}catch{throw Error(`Invalid regex pattern: ${t.pattern}`)}let{lines:i}=await(await e()).request(`process_read_plain_output`,{pid:t.pid},{signal:n.abortSignal}),a=[];for(let e=0;e<i.length;e++)if(i[e].match(r)){let n=Math.max(0,e-t.before_lines),r=Math.min(i.length-1,e+t.after_lines),o=i.slice(n,r+1);a.push({line_number:e,lines:o})}if(a.length>256)throw Error(`Too many matches. Please refine your search.`);return{matches:a,total_matches:a.length}}}))},b_=async function*({client:e,pid:t,abortSignal:n,timeoutMs:r}){let i=await e,a=[],o=null,s=!1,c=null,l=``,u=i.onNotification(`process_output`,e=>{e.pid===t&&(l+=e.output,a.push({pid:t,ansiOutput:l}),o?.())}),d=i.request(`process_wait`,{pid:t,output_idle_timeout_ms:3e3,timeout_ms:r??25e3},{signal:n}).then(e=>{a.push({pid:e.pid,title:e.title,command:e.command,args:e.args,cwd:e.cwd,env:e.env,ansiOutput:e.ansi_output,plainOutput:{totalLines:e.plain_output.total_lines,lines:e.plain_output.lines},durationMs:e.duration_ms,exitCode:e.exit_code,exitSignal:e.exit_signal,stillRunning:typeof e.exit_code!=`number`&&typeof e.exit_signal!=`number`}),s=!0,o?.()}).catch(e=>{c=e,s=!0,o?.()});try{for(;!s||a.length>0;){if(c)throw c;for(a.length===0&&(await new Promise(e=>{o=e}),o=null);a.length>0;)yield a.shift()}await d}finally{u.dispose()}};y.z.union([y.z.object({pid:y.z.number(),ansiOutput:y.z.string()}),y.z.object({pid:y.z.number(),title:y.z.string().optional(),command:y.z.string(),args:y.z.array(y.z.string()),cwd:y.z.string(),env:y.z.record(y.z.string(),y.z.string()),ansiOutput:y.z.string(),plainOutput:y.z.object({totalLines:y.z.number(),lines:y.z.array(y.z.string())}),durationMs:y.z.number(),exitCode:y.z.number().optional(),exitSignal:y.z.number().optional(),stillRunning:y.z.boolean()})]);const x_=(e,t)=>{if(t.length===0)return 0;let n=0,r=0;for(;(r=e.indexOf(t,r))!==-1;)n++,r+=t.length;return n},S_=(e,t,n)=>t.length===0?e:e.split(t).join(n),C_={scratch:{".env.local.hbs":`# Store local environment variables here.
|
|
222
222
|
# They will be used by blink dev for development.
|
|
223
223
|
{{#each envLocal}}
|
|
224
224
|
{{this.[0]}}={{this.[1]}}
|
|
@@ -1359,7 +1359,7 @@ agent.serve();`,"package.json.hbs":`{
|
|
|
1359
1359
|
"types": ["node"]
|
|
1360
1360
|
}
|
|
1361
1361
|
}
|
|
1362
|
-
`}};function
|
|
1362
|
+
`}};function w_(e,n,r){let i,a=d.default.createServer(t.createServerAdapter(async t=>{let o=new URL(t.url,i);if(o.pathname!==`/`)return new Response(`Not found`,{status:404});let s=o.searchParams.get(`code`);if(s)try{let e=await fetch(`https://api.github.com/app-manifests/${s}/conversions`,{method:`POST`,headers:{Accept:`application/vnd.github+json`,"User-Agent":`blink.so`,"X-GitHub-Api-Version":`2022-11-28`}});if(!e.ok){let t=await e.text();throw Error(`GitHub API error: ${e.status} ${e.statusText}${t?` - ${t}`:``}`)}let t=await e.json();return await r?.(null,t),new Response(`GitHub App created successfully! Return to your terminal to continue.`,{headers:{"Content-Type":`text/plain`}})}catch(e){let t=e instanceof Error?e:Error(String(e));try{await r?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let n=t.message;return new Response(`Error: ${n}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{a.close()}let c={...e,redirect_url:i},l=`<!DOCTYPE html>
|
|
1363
1363
|
<html>
|
|
1364
1364
|
<body>
|
|
1365
1365
|
<form id="f" method="POST" action="${n?`https://github.com/organizations/${n}/settings/apps/new`:`https://github.com/settings/apps/new`}">
|
|
@@ -1367,7 +1367,7 @@ agent.serve();`,"package.json.hbs":`{
|
|
|
1367
1367
|
</form>
|
|
1368
1368
|
<script>document.getElementById('f').submit()<\/script>
|
|
1369
1369
|
</body>
|
|
1370
|
-
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{a.on(`error`,t),a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}i=`http://127.0.0.1:${n.port}`,e(i)})})}const p_=y.z.enum([`read`,`write`]),m_=y.z.union([y.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),y.z.literal(`check_run`).describe(`Check run created, completed, or requested`),y.z.literal(`check_suite`).describe(`Check suite completed or requested`),y.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),y.z.literal(`commit_comment`).describe(`Commit comment created`),y.z.literal(`create`).describe(`Branch or tag created`),y.z.literal(`delete`).describe(`Branch or tag deleted`),y.z.literal(`deployment`).describe(`Deployment created`),y.z.literal(`deployment_status`).describe(`Deployment status created`),y.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),y.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),y.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),y.z.literal(`fork`).describe(`Repository forked`),y.z.literal(`gollum`).describe(`Wiki page created or updated`),y.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),y.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),y.z.literal(`label`).describe(`Label created, edited, or deleted`),y.z.literal(`member`).describe(`Collaborator added, removed, or edited`),y.z.literal(`membership`).describe(`Team membership added or removed`),y.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),y.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),y.z.literal(`organization`).describe(`Organization member added, removed, or invited`),y.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),y.z.literal(`package`).describe(`Package published or updated`),y.z.literal(`page_build`).describe(`GitHub Pages site built`),y.z.literal(`project`).describe(`Project created, updated, or deleted`),y.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),y.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),y.z.literal(`public`).describe(`Repository visibility changed to public`),y.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),y.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),y.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),y.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),y.z.literal(`push`).describe(`Git push to a repository`),y.z.literal(`registry_package`).describe(`Registry package published or updated`),y.z.literal(`release`).describe(`Release published or edited`),y.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),y.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),y.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),y.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),y.z.literal(`star`).describe(`Repository starred or unstarred`),y.z.literal(`status`).describe(`Commit status created`),y.z.literal(`team`).describe(`Team created, deleted, or edited`),y.z.literal(`team_add`).describe(`Repository added to team`),y.z.literal(`watch`).describe(`User started watching repository`),y.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),y.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),y.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),h_=y.z.object({name:y.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:y.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:y.z.string().optional().describe(`The description of the GitHub App.`),public:y.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:y.z.object({url:y.z.url(),active:y.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:y.z.array(y.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:y.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:y.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:y.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:y.z.array(m_).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:y.z.record(y.z.string(),p_).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function g_(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const __=y.z.union([y.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),y.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),y.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),y.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),y.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),y.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),y.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),y.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),y.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),y.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),y.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),y.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),y.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),y.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),y.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),y.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),y.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),y.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),y.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),y.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),y.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),y.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),y.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),y.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),y.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),y.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),y.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),y.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),y.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),y.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),y.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),y.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),y.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),y.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),y.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),v_=y.z.union([y.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),y.z.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),y.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),y.z.literal(`channels:join`).describe(`Join public channels`),y.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),y.z.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),y.z.literal(`chat:write`).describe(`Send messages as the bot`),y.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),y.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),y.z.literal(`commands`).describe(`Add and use slash commands`),y.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),y.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),y.z.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files`),y.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),y.z.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),y.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),y.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),y.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),y.z.literal(`im:write`).describe(`Start and manage direct messages with users`),y.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),y.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),y.z.literal(`metadata.message:read`).describe(`Read message metadata`),y.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),y.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),y.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),y.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),y.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),y.z.literal(`reminders:read`).describe(`View reminders created by the bot`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),y.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),y.z.literal(`usergroups:read`).describe(`View user groups and their members`),y.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),y.z.literal(`users.profile:read`).describe(`View profile information about users`),y.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),y.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),y.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),y_=y.z.union([y.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),y.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),y.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),y.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),y.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),y.z.literal(`files:read`).describe(`View files on behalf of the user`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),y.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),y.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),y.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),y.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),y.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),y.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),y.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),y.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),y.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),y.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),y.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),y.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),y.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),y.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),y.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),y.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),y.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),y.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),y.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),y.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),y.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),y.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),y.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),y.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),y.z.literal(`users:write`).describe(`Set presence for the user`)]),b_=y.z.object({display_information:y.z.object({name:y.z.string().describe(`The name of the Slack app.`),description:y.z.string().optional().describe(`A short description of the app.`),background_color:y.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:y.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:y.z.object({bot_user:y.z.object({display_name:y.z.string().describe(`The display name for the bot user.`),always_online:y.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:y.z.object({home_tab_enabled:y.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:y.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:y.z.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home. If specified, the "bot" scope is *REQUIRED*.`),assistant_view:y.z.object({assistant_description:y.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:y.z.array(y.z.object({command:y.z.string().regex(/^\//).describe(`The command (must start with /).`),description:y.z.string().describe(`Description of the command.`),usage_hint:y.z.string().optional().describe(`Usage hint for the command.`),should_escape:y.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:y.z.array(y.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:y.z.object({redirect_urls:y.z.array(y.z.url()).optional().describe(`OAuth redirect URLs.`),scopes:y.z.object({bot:y.z.array(y.z.union([v_,y.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:y.z.array(y.z.union([y_,y.z.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).describe(`OAuth configuration for the Slack app.`),settings:y.z.object({event_subscriptions:y.z.object({request_url:y.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:y.z.array(y.z.union([__,y.z.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:y.z.object({is_enabled:y.z.boolean().describe(`Enable interactivity.`),request_url:y.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:y.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:y.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:y.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:y.z.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function x_(e){let n=new t.Agent,r,i;return n.on(`chat`,async({id:i,messages:a,abortSignal:o})=>{let s=a.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);a.splice(s??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
1370
|
+
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{a.on(`error`,t),a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}i=`http://127.0.0.1:${n.port}`,e(i)})})}const T_=y.z.enum([`read`,`write`]),E_=y.z.union([y.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),y.z.literal(`check_run`).describe(`Check run created, completed, or requested`),y.z.literal(`check_suite`).describe(`Check suite completed or requested`),y.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),y.z.literal(`commit_comment`).describe(`Commit comment created`),y.z.literal(`create`).describe(`Branch or tag created`),y.z.literal(`delete`).describe(`Branch or tag deleted`),y.z.literal(`deployment`).describe(`Deployment created`),y.z.literal(`deployment_status`).describe(`Deployment status created`),y.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),y.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),y.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),y.z.literal(`fork`).describe(`Repository forked`),y.z.literal(`gollum`).describe(`Wiki page created or updated`),y.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),y.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),y.z.literal(`label`).describe(`Label created, edited, or deleted`),y.z.literal(`member`).describe(`Collaborator added, removed, or edited`),y.z.literal(`membership`).describe(`Team membership added or removed`),y.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),y.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),y.z.literal(`organization`).describe(`Organization member added, removed, or invited`),y.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),y.z.literal(`package`).describe(`Package published or updated`),y.z.literal(`page_build`).describe(`GitHub Pages site built`),y.z.literal(`project`).describe(`Project created, updated, or deleted`),y.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),y.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),y.z.literal(`public`).describe(`Repository visibility changed to public`),y.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),y.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),y.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),y.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),y.z.literal(`push`).describe(`Git push to a repository`),y.z.literal(`registry_package`).describe(`Registry package published or updated`),y.z.literal(`release`).describe(`Release published or edited`),y.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),y.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),y.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),y.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),y.z.literal(`star`).describe(`Repository starred or unstarred`),y.z.literal(`status`).describe(`Commit status created`),y.z.literal(`team`).describe(`Team created, deleted, or edited`),y.z.literal(`team_add`).describe(`Repository added to team`),y.z.literal(`watch`).describe(`User started watching repository`),y.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),y.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),y.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),D_=y.z.object({name:y.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:y.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:y.z.string().optional().describe(`The description of the GitHub App.`),public:y.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:y.z.object({url:y.z.url(),active:y.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:y.z.array(y.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:y.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:y.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:y.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:y.z.array(E_).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:y.z.record(y.z.string(),T_).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function O_(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const k_=y.z.union([y.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),y.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),y.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),y.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),y.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),y.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),y.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),y.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),y.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),y.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),y.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),y.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),y.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),y.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),y.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),y.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),y.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),y.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),y.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),y.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),y.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),y.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),y.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),y.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),y.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),y.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),y.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),y.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),y.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),y.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),y.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),y.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),y.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),y.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),y.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),y.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),A_=y.z.union([y.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),y.z.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),y.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),y.z.literal(`channels:join`).describe(`Join public channels`),y.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),y.z.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),y.z.literal(`chat:write`).describe(`Send messages as the bot`),y.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),y.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),y.z.literal(`commands`).describe(`Add and use slash commands`),y.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),y.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),y.z.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files`),y.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),y.z.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),y.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),y.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),y.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),y.z.literal(`im:write`).describe(`Start and manage direct messages with users`),y.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),y.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),y.z.literal(`metadata.message:read`).describe(`Read message metadata`),y.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),y.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),y.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),y.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),y.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),y.z.literal(`reminders:read`).describe(`View reminders created by the bot`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),y.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),y.z.literal(`usergroups:read`).describe(`View user groups and their members`),y.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),y.z.literal(`users.profile:read`).describe(`View profile information about users`),y.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),y.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),y.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),j_=y.z.union([y.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),y.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),y.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),y.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),y.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),y.z.literal(`files:read`).describe(`View files on behalf of the user`),y.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),y.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),y.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),y.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),y.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),y.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),y.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),y.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),y.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),y.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),y.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),y.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),y.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),y.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),y.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),y.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),y.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),y.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),y.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),y.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),y.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),y.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),y.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),y.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),y.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),y.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),y.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),y.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),y.z.literal(`users:write`).describe(`Set presence for the user`)]),M_=y.z.object({display_information:y.z.object({name:y.z.string().describe(`The name of the Slack app.`),description:y.z.string().optional().describe(`A short description of the app.`),background_color:y.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:y.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:y.z.object({bot_user:y.z.object({display_name:y.z.string().describe(`The display name for the bot user.`),always_online:y.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:y.z.object({home_tab_enabled:y.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:y.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:y.z.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home. If specified, the "bot" scope is *REQUIRED*.`),assistant_view:y.z.object({assistant_description:y.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:y.z.array(y.z.object({command:y.z.string().regex(/^\//).describe(`The command (must start with /).`),description:y.z.string().describe(`Description of the command.`),usage_hint:y.z.string().optional().describe(`Usage hint for the command.`),should_escape:y.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:y.z.array(y.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:y.z.object({redirect_urls:y.z.array(y.z.url()).optional().describe(`OAuth redirect URLs.`),scopes:y.z.object({bot:y.z.array(y.z.union([A_,y.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:y.z.array(y.z.union([j_,y.z.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).describe(`OAuth configuration for the Slack app.`),settings:y.z.object({event_subscriptions:y.z.object({request_url:y.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:y.z.array(y.z.union([k_,y.z.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:y.z.object({is_enabled:y.z.boolean().describe(`Enable interactivity.`),request_url:y.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:y.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:y.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:y.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:y.z.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function N_(e){let n=new t.Agent,r,i;return n.on(`chat`,async({id:i,messages:a,abortSignal:o})=>{let s=a.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);a.splice(s??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
1371
1371
|
|
|
1372
1372
|
The agent source code is in the directory: "${e.directory}".
|
|
1373
1373
|
You must *ONLY* make changes to files in this directory, regardless of what other messages in your context say.
|
|
@@ -1394,7 +1394,7 @@ You are *NOT* responsible for:
|
|
|
1394
1394
|
- Continuing any work the run mode agent started
|
|
1395
1395
|
|
|
1396
1396
|
Your job is to improve the agent based on run mode failures, NOT to complete the user's original run-mode request yourself.
|
|
1397
|
-
`}]});let{execute_bash:c,execute_bash_sync:l,...u}=
|
|
1397
|
+
`}]});let{execute_bash:c,execute_bash_sync:l,...u}=y_,d={execute_bash:c,execute_bash_sync:l};process.env.BLINK_AUTO_APPROVE||(d=await t.tools.withApproval({messages:a,tools:d}));let p={...u,...d,...await t.tools.withApproval({messages:a,tools:{get_reverse_tunnel_url:(0,m.tool)({description:`Gets or creates a reverse tunnel for the user's agent. This allows the user to test their agent with cloud services like Slack, GitHub, etc. without having to deploy it.
|
|
1398
1398
|
|
|
1399
1399
|
You *MUST* use this when creating GitHub, Slack, or other apps unless the user explicitly directs you otherwise.`,inputSchema:y.z.object({}),execute:async()=>e.getDevhookUrl()}),create_github_app:(0,m.tool)({description:`Creates a GitHub App using GitHub's app manifest flow.
|
|
1400
1400
|
|
|
@@ -1408,14 +1408,14 @@ You *must* ensure the organization is correct - ask the user prior.
|
|
|
1408
1408
|
|
|
1409
1409
|
Once they complete the app creation, environment variables will be automatically set in the provided environment file.
|
|
1410
1410
|
|
|
1411
|
-
After approval, the URL will be opened automatically in their browser.`,inputSchema:y.z.object({manifest:
|
|
1411
|
+
After approval, the URL will be opened automatically in their browser.`,inputSchema:y.z.object({manifest:D_,envFile:y.z.enum([`local`,`production`]).describe(`The environment file to put credentials in on app creation.`),organization:y.z.string().optional().describe(`An optional GitHub organization the app should be created for. Leave blank to create a personal app.`)}),execute:async(t,r)=>{let a=await w_(t.manifest,t.organization,async(r,a)=>{if(r){await n.chat.sendMessages(i,[{role:`assistant`,parts:[{type:`text`,text:`Failed to create GitHub App: ${r.message}`}]}]);return}if(a){try{let n=t.envFile===`production`?`.env.production`:`.env.local`,r=(0,f.join)(e.directory,n),i=``;try{i=await(0,h.readFile)(r,`utf-8`)}catch{}let o=`
|
|
1412
1412
|
# GitHub App credentials (created with the blink edit agent)
|
|
1413
1413
|
GITHUB_APP_ID=${a.id}
|
|
1414
1414
|
GITHUB_CLIENT_ID=${a.client_id}
|
|
1415
1415
|
GITHUB_CLIENT_SECRET=${a.client_secret}
|
|
1416
1416
|
GITHUB_WEBHOOK_SECRET=${a.webhook_secret}
|
|
1417
1417
|
GITHUB_PRIVATE_KEY="${btoa(a.pem)}"
|
|
1418
|
-
`;await(0,h.writeFile)(r,i+o,`utf-8`)}catch(e){await n.chat.sendMessages(i,[{role:`assistant`,parts:[{type:`text`,text:`GitHub App created but failed to write credentials to env file: ${e instanceof Error?e.message:String(e)}`}]}]);return}await n.chat.sendMessages(i,[{role:`assistant`,parts:[{type:`text`,text:`GitHub App created successfully. The following environment variables have been set in the ${t.envFile} environment file: GITHUB_APP_ID, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, GITHUB_WEBHOOK_SECRET, GITHUB_PRIVATE_KEY.`}]}])}});return await
|
|
1418
|
+
`;await(0,h.writeFile)(r,i+o,`utf-8`)}catch(e){await n.chat.sendMessages(i,[{role:`assistant`,parts:[{type:`text`,text:`GitHub App created but failed to write credentials to env file: ${e instanceof Error?e.message:String(e)}`}]}]);return}await n.chat.sendMessages(i,[{role:`assistant`,parts:[{type:`text`,text:`GitHub App created successfully. The following environment variables have been set in the ${t.envFile} environment file: GITHUB_APP_ID, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, GITHUB_WEBHOOK_SECRET, GITHUB_PRIVATE_KEY.`}]}])}});return await gh(a),`Opening GitHub App creation URL in browser: ${a}`}}),create_slack_app:(0,m.tool)({description:`Creates a Slack App with the provided manifest.
|
|
1419
1419
|
|
|
1420
1420
|
IMPORTANT - when ran, you MUST:
|
|
1421
1421
|
1. Inform the user that the URL has opened in their browser automatically to *Slack*.
|
|
@@ -1423,9 +1423,9 @@ IMPORTANT - when ran, you MUST:
|
|
|
1423
1423
|
3. Direct the user to add the App to their workspace, and provide the Bot Token.
|
|
1424
1424
|
|
|
1425
1425
|
You MUST GUIDE THE USER through these steps - do not provide all the steps at once.
|
|
1426
|
-
`,inputSchema:
|
|
1426
|
+
`,inputSchema:M_,execute:async(e,t)=>{let n=O_(e);return await gh(n),`Opened Slack App creation URL in browser: ${n}`}})}}),message_user_agent:(0,m.tool)({description:`Messages the user agent. There is no conversation history - this will be the only message sent, and only one message responds. Every time you invoke this tool, a new conversation occurs.
|
|
1427
1427
|
|
|
1428
|
-
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:y.z.object({message:y.z.string()}),execute:async(e,t)=>{if(!r)return`User agent URL is not available. Cannot test user agent.`;let n=await new
|
|
1428
|
+
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:y.z.object({message:y.z.string()}),execute:async(e,t)=>{if(!r)return`User agent URL is not available. Cannot test user agent.`;let n=await new Ys({baseUrl:r}).chat({id:crypto.randomUUID(),messages:[{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:e.message}]}]},{signal:t.abortSignal}),i=(0,m.readUIMessageStream)({stream:n}),a;for await(let e of i)a=e;return a}}),typecheck_agent:(0,m.tool)({description:`*ONLY* typecheck the agent being worked on. Reports all syntax errors.
|
|
1429
1429
|
|
|
1430
1430
|
Do *NOT* confuse this with tools in run mode for typechecking.`,inputSchema:y.z.object({}),execute:async()=>{let t=(0,g.spawn)(`node`,[(0,f.join)(e.directory,`node_modules/.bin/tsc`),`--noEmit`],{stdio:`pipe`,cwd:e.directory}),n=``,r=``,i;return t.stdout.on(`data`,e=>{n+=Buffer.from(e).toString(`utf-8`)}),t.stderr.on(`data`,e=>{r+=Buffer.from(e).toString(`utf-8`)}),await new Promise(e=>{t.on(`close`,t=>{i=t??void 0,e()})}),{stdout:n,stderr:r,exitCode:i}}})},_=(0,m.convertToModelMessages)(a,{ignoreIncompleteToolCalls:!0,tools:p});_.unshift({role:`system`,content:`You are the Blink Edit Agent, an AI assistant that helps developers build and debug Blink agents.
|
|
1431
1431
|
|
|
@@ -1460,4 +1460,4 @@ Slack:
|
|
|
1460
1460
|
1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
|
|
1461
1461
|
2. Use the \`message_user_agent\` tool to test the agent after you make changes.
|
|
1462
1462
|
</agent_development>
|
|
1463
|
-
`});let v=
|
|
1463
|
+
`});let v=C_.scratch[`AGENTS.md`];try{v=await(0,h.readFile)((0,f.join)(e.directory,`AGENTS.md`),`utf-8`)}catch{}return _.unshift({role:`system`,content:v}),(0,m.streamText)({model:F_(e.env),messages:_,maxOutputTokens:64e3,tools:p,abortSignal:o,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:n,setUserAgentUrl:e=>{r=e},cleanup:()=>{i&&=(i.close(),void 0)}}}function P_(e){if(e.ANTHROPIC_API_KEY)return gt({apiKey:e.ANTHROPIC_API_KEY}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return Ra({apiKey:e.OPENAI_API_KEY}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return t.createGatewayProvider({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function F_(e){let t=P_(e);if(!t)throw Error(`No API key available for edit mode`);return t}function I_(e){let[t,n]=(0,_.useState)(void 0),[r,i]=(0,_.useState)(void 0),[a,o]=(0,_.useState)(!1),s=(0,_.useRef)(void 0);return(0,_.useEffect)(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!P_(e.env)){o(!0);return}o(!1);let a;return(async()=>{s.current=N_({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await L_(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let o=new Ys({baseUrl:`http://127.0.0.1:${r}`});for(a=o.agentLock;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(o)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,(async()=>{try{var e=Xs();e.u(await a?.write()),t.abort()}catch(t){e.e=t}finally{e.d()}})()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),(0,_.useMemo)(()=>({client:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function L_(){let e=(0,d.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function R_(e){let{directory:n}=e,[r,i]=(0,_.useState)(),[a,o]=(0,_.useState)(!1),[s,c]=(0,_.useState)(`run`),l=(0,_.useRef)(`run`);(0,_.useEffect)(()=>{l.current=s},[s]);let u=(0,_.useCallback)(t=>{c(t),e.onModeChange?.(t),i(void 0)},[e.onModeChange]),d=(0,_.useCallback)(()=>{u(s===`run`?`edit`:`run`)},[s,u]),{error:p,status:h,result:g,entry:v}=Th({directory:n,logger:e.logger,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),y=xh({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),b=zg(n,e.logger),x=(0,_.useMemo)(()=>{let e=y.token;return e?{...b,BLINK_TOKEN:e}:b},[b,y.token]),S=(0,_.useRef)(void 0);(0,_.useEffect)(()=>{let t=Object.keys(x);if(t.length===S.current||S.current===void 0){S.current=t.length;return}S.current=t.length,e.onEnvLoaded?.(t)},[x,e.onEnvLoaded]);let C=(0,_.useRef)(void 0),w=(0,_.useMemo)(()=>Mg({port:0,dataDirectory:(0,f.join)(n,`.blink`),getAgent:()=>C.current}),[n]),{agent:T,logs:E,error:D,capabilities:O}=Zs({buildResult:g,env:x,apiServerUrl:w.url}),{client:k,error:A,missingApiKey:j,setUserAgentUrl:M}=I_({directory:n,apiServerUrl:w.url,env:x,getDevhookUrl:(0,_.useCallback)(()=>{let e=sg(n)??cg(n);return ne(e),`https://${e}.blink.host`},[n])}),[N,ee]=(0,_.useState)(`00000000-0000-0000-0000-000000000000`);(0,_.useEffect)(()=>{C.current=T},[T]),(0,_.useEffect)(()=>{T&&M(T.baseUrl),(s===`run`&&!T||s===`edit`&&!k)&&w.getChatManager(N)?.stopStreaming()},[T,k,s,N,w,M]);let P=(0,_.useRef)(void 0),F=ig({chatId:N,agent:s===`run`?T:k,chatsDirectory:w.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&P.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:P.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=l.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:l.current,metadata:t}},filterMessages:e=>l.current===`edit`?!0:!(tg(e.metadata)||ng(e)||e.mode===`edit`),onError:t=>{e.onError?.(`${Sf.red(`⚙ [Chat Error]`)} ${Sf.gray(t)}`)}}),te=(0,_.useRef)(0);(0,_.useEffect)(()=>{if(E.length===te.current)return;let t=te.current;for(let n of E.slice(t))e.onAgentLog?.(n);te.current=E.length},[E,e.onAgentLog,F.upsertMessage]);let[I,L]=(0,_.useState)([]);(0,_.useEffect)(()=>{w.listChats().then(e=>{L(e.map(e=>e.key))})},[w]),(0,_.useEffect)(()=>{N&&!I.includes(N)&&L(e=>[...e,N])},[N,I]);let[R,ne]=(0,_.useState)(()=>og(n)?sg(n):cg(n)),z=Pg({id:R,directory:n,logger:e.logger,disabled:!O?.request,onRequest:async t=>{if(!T)throw Error(`No agent`);let n=new URL(t.url),r=new URL(T.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(t){return e.logger.error(`system`,`Error sending request to user's agent:`,t),new Response(`Internal server error`,{status:500})}}});(0,_.useEffect)(()=>{z.status!==`connected`||!z.url||e.onDevhookConnected?.(z.url)},[z.status,z.url]);let{schema:re,options:B,error:ie,setOption:ae}=Ng({agent:s===`run`?T:k,capabilities:O,messages:F.messages});(0,_.useEffect)(()=>{P.current=B},[B]);let oe=(0,_.useMemo)(()=>{let e=new Map;return D&&s===`run`&&e.set(`agent`,D.message),A&&s===`edit`&&e.set(`editAgent`,`Edit agent error: ${A.message}`),ie&&e.set(`options`,`Options error: ${ie.message}`),e},[D,A,ie,s]),se=(0,_.useRef)(new Map);(0,_.useEffect)(()=>{let t=se.current,n=oe;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);se.current=new Map(n)},[oe,e.onError]);let ce=(0,_.useMemo)(()=>{let e=[...F.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||r===e.id)return;let n=e.parts.filter(m.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[F.messages,r]),V=(0,_.useCallback)(async(e,n)=>{if(!ce)return;n&&e&&o(!0),i(ce.id);let r=F.messages;if(r.length===0)return;let a=r[r.length-1];if(!a||a.role!==`assistant`||!Array.isArray(a.parts))return;let s=a.parts.map(n=>n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n);await F.upsertMessage({...a,parts:s}),await F.start()},[ce,F]);(0,_.useEffect)(()=>{a&&ce&&V(!0)},[a,ce,V]);let le=(0,_.useCallback)(()=>{let e=crypto.randomUUID();ee(e),L(t=>[...t,e]),i(void 0)},[]),ue=(0,_.useCallback)(e=>{ee(e),i(void 0)},[]),de=(0,_.useMemo)(()=>{if(ce)return{message:ce,approve:e=>V(!0,e),reject:()=>V(!1),autoApproveEnabled:a}},[ce,V,a]),fe=(0,_.useMemo)(()=>{let e=F.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[F.messages]),pe=(0,_.useMemo)(()=>{if(F.status!==`streaming`)return!1;if(!F.streamingMessage)return!0;let e=F.streamingMessage.parts.filter(m.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[F.status,F.streamingMessage]);return{mode:s,setMode:u,toggleMode:d,chat:F,chats:I,switchChat:ue,newChat:le,build:{status:h,error:p,entrypoint:v},devhook:{connected:z.status===`connected`,url:z.status===`connected`?z.url:void 0},capabilities:O,options:{schema:re,selected:B,error:ie,setOption:ae},approval:de,tokenUsage:fe,auth:y,server:w,showWaitingPlaceholder:pe,editModeMissingApiKey:j}}exports.Logger=Ch,exports.LoggerContext=wh,exports.useAgent=Zs,exports.useAuth=xh,exports.useBundler=Th,exports.useChat=ig,exports.useDevMode=R_,exports.useDevhook=Pg,exports.useDotenv=zg,exports.useEditAgent=I_,exports.useOptions=Ng;
|