blink 1.1.20 → 1.1.22
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 +7 -7
- package/dist/browser/agent/client/index.js +6 -6
- package/dist/cli/{auth-CoJASYGP.js → auth-DbpOUCTO.js} +2 -2
- package/dist/cli/{chat-BDAEIrJW.js → chat-CAtArOPl.js} +1 -1
- package/dist/cli/chat-manager-GWR_v50X.js +21 -0
- package/dist/cli/connect-DWScpJzS.js +1 -0
- package/dist/cli/{dev-C5PZ-A_f.js → dev-BSh59jdn.js} +211 -181
- package/dist/cli/execAsync-Dwktgsum.js +1 -0
- package/dist/cli/execAsync-qNF4iDpO.js +1 -0
- package/dist/cli/{getMachineId-bsd-BQaAhwjO.js → getMachineId-bsd-0cOO_RKK.js} +1 -1
- package/dist/cli/{getMachineId-bsd-Cw8CWhxJ.js → getMachineId-bsd-BDrKPt3B.js} +1 -1
- package/dist/cli/{getMachineId-bsd-DcR5dlLj.js → getMachineId-bsd-BJ3yH7j4.js} +1 -1
- package/dist/{node/getMachineId-bsd-BxqlJcyA.js → cli/getMachineId-bsd-BpxYEV3F.js} +1 -1
- package/dist/cli/getMachineId-bsd-BrJwIGYU.js +1 -0
- package/dist/cli/getMachineId-bsd-C6osJ6-S.js +1 -0
- package/dist/cli/{getMachineId-bsd-CbeuYR7X.js → getMachineId-bsd-CHVQhSq2.js} +1 -1
- package/dist/cli/getMachineId-bsd-DeIJ5F9l.js +1 -0
- package/dist/cli/{getMachineId-darwin-D7CuR-jd.js → getMachineId-darwin-0AdOS_kz.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DJ-H8l7s.js → getMachineId-darwin-BaA8JJgE.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DYCKXuZX.js → getMachineId-darwin-BeAdNwpL.js} +1 -1
- package/dist/cli/{getMachineId-darwin-DyN_uugK.js → getMachineId-darwin-C8-xkmnZ.js} +1 -1
- package/dist/{node/getMachineId-darwin-Bf4P0U5b.js → cli/getMachineId-darwin-CJ2gOzlU.js} +1 -1
- package/dist/cli/getMachineId-darwin-CYvRIQbp.js +2 -0
- package/dist/cli/getMachineId-darwin-DWSKszGZ.js +2 -0
- package/dist/cli/getMachineId-darwin-wYLDmdQt.js +2 -0
- package/dist/cli/getMachineId-linux-D0cDy6Ik.js +1 -0
- package/dist/cli/getMachineId-linux-DgyKUIyK.js +1 -0
- package/dist/cli/getMachineId-linux-DnzutOBC.js +1 -0
- package/dist/cli/getMachineId-linux-nBO1QX9q.js +1 -0
- package/dist/cli/getMachineId-unsupported-DQBLgw4s.js +1 -0
- package/dist/cli/getMachineId-unsupported-DTFeADdG.js +1 -0
- package/dist/cli/getMachineId-unsupported-DgVzHx1H.js +1 -0
- package/dist/cli/getMachineId-unsupported-TE5qi9PD.js +1 -0
- package/dist/cli/{getMachineId-win-BB1s3SWz.js → getMachineId-win-4Psd7Tlr.js} +1 -1
- package/dist/cli/{getMachineId-win-BrQ4d5bO.js → getMachineId-win-BA0Li8oF.js} +1 -1
- package/dist/cli/{getMachineId-win-CgPYGelR.js → getMachineId-win-BvGLfEpq.js} +1 -1
- package/dist/cli/getMachineId-win-BzRwVWue.js +1 -0
- package/dist/cli/{getMachineId-win-B7f9VGFu.js → getMachineId-win-C4wjvjxC.js} +1 -1
- package/dist/cli/getMachineId-win-DXCyELQJ.js +1 -0
- package/dist/cli/getMachineId-win-hHwtD9GX.js +1 -0
- package/dist/cli/getMachineId-win-lhgCxX3y.js +1 -0
- package/dist/cli/index.js +8 -8
- package/dist/cli/init-Ciwa_eM0.js +23 -0
- package/dist/cli/{init-templates-CB4tNZfU.js → init-templates-By3gx42M.js} +33 -23
- package/dist/cli/login-BDP8JC4X.js +1 -0
- package/dist/cli/{run-bKDX6K46.js → run-CZZ6WAdr.js} +1 -1
- package/dist/cli/setup-slack-app-DagQxNol.js +1 -0
- package/dist/cli/{token-DNRiDJM-.js → token-BdYp2nw_.js} +1 -1
- package/dist/cli/token-util-C9doIH9w.js +1 -0
- package/dist/cli/{token-util-IqDtKhK6.js → token-util-KdD-UX1l.js} +1 -1
- package/dist/cli/undici-Bm_EanIy.js +1 -0
- package/dist/cli/util-CUfifM0g.js +5 -0
- package/dist/cli/{util-DDB5k1Go.js → util-k3x8m_i5.js} +9 -9
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.d.ts +1 -1
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/build/index.d.ts +1 -1
- package/dist/node/execAsync-CY8juV7n.js +1 -0
- package/dist/node/{getMachineId-bsd-C10eVJgT.js → getMachineId-bsd-Ckr9jSoT.js} +1 -1
- package/dist/node/{getMachineId-bsd-B84ixt26.cjs → getMachineId-bsd-O0bNSuuh.cjs} +1 -1
- package/dist/node/{getMachineId-darwin-JB29MQsG.js → getMachineId-darwin-36SFRv2R.js} +1 -1
- package/dist/node/{getMachineId-darwin-Cyng5kFG.cjs → getMachineId-darwin-DivkCgLG.cjs} +1 -1
- package/dist/node/{getMachineId-win-CjJkZMZe.cjs → getMachineId-win-B_okYUv6.cjs} +1 -1
- package/dist/node/{getMachineId-win-C4G-fkEF.js → getMachineId-win-CGqZ4f4O.js} +1 -1
- package/dist/node/index.node-Bvp48I1R.cjs +50 -0
- package/dist/node/index.node-ppzOWVGE.js +50 -0
- package/dist/node/react/index.node.cjs +130 -121
- package/dist/node/react/index.node.d.cts +9 -2
- package/dist/node/react/index.node.d.ts +11 -4
- package/dist/node/react/index.node.js +84 -75
- package/dist/node/{token-DOfE6QlD.js → token-CI2_C_5D.js} +1 -1
- package/dist/node/{token-BBGr-czK.cjs → token-D4jFpAk0.cjs} +1 -1
- package/dist/node/token-util-BENsR1Bn.cjs +1 -0
- package/dist/node/{token-util-C_uzN2q9.js → token-util-idU3T5iM.js} +1 -1
- package/package.json +19 -1
- package/dist/cli/chat-manager-BRchJngj.js +0 -21
- package/dist/cli/connect-WyCmuQHj.js +0 -1
- package/dist/cli/init-CFrylDAP.js +0 -25
- package/dist/cli/login-DZFx5155.js +0 -1
- package/dist/cli/setup-slack-app-D_iwQuzr.js +0 -1
- package/dist/cli/token-util-C6Xu44iO.js +0 -1
- package/dist/cli/undici-L5V8WBce.js +0 -1
- package/dist/cli/util-BgbIWOFE.js +0 -6
- package/dist/node/execAsync-pJEPzmP4.cjs +0 -1
- package/dist/node/getMachineId-bsd-BudRe7J9.cjs +0 -1
- package/dist/node/getMachineId-darwin-ZVi3EKE3.cjs +0 -2
- package/dist/node/getMachineId-linux-CJXPQ8U5.cjs +0 -1
- package/dist/node/getMachineId-linux-CmMSYp7C.js +0 -1
- package/dist/node/getMachineId-unsupported-DM7fz1pP.cjs +0 -1
- package/dist/node/getMachineId-unsupported-Dtt3HTNZ.js +0 -1
- package/dist/node/getMachineId-win-D1szVnqR.js +0 -1
- package/dist/node/getMachineId-win-DDz2FyEp.cjs +0 -1
- package/dist/node/index.node-B6JXREDl.js +0 -55
- package/dist/node/index.node-BrLfthBj.cjs +0 -55
- package/dist/node/token-util-D9kCwzE6.cjs +0 -1
- /package/dist/cli/{connect-CQUVd44y.js → connect-BCK40kvG.js} +0 -0
- /package/dist/cli/{devtools-DvNholmW.js → devtools-DsAYEmyP.js} +0 -0
- /package/dist/cli/{execAsync-Bhq3YKvl.js → execAsync-BOPj9Mml.js} +0 -0
- /package/dist/cli/{execAsync-BnYBiViJ.js → execAsync-Bv4jTnD3.js} +0 -0
- /package/dist/cli/{execAsync-Djebuxfm.js → execAsync-CyP3Ojec.js} +0 -0
- /package/dist/cli/{execAsync-_tP2SNTy.js → execAsync-DHh3DKKp.js} +0 -0
- /package/dist/{node/execAsync-DzxhVi7q.js → cli/execAsync-DdLzES9n.js} +0 -0
- /package/dist/{node/execAsync-epR2wT1r.js → cli/execAsync-Dv6XOE2I.js} +0 -0
- /package/dist/cli/{getMachineId-linux-BCOAWAJr.js → getMachineId-linux-BQISLgy5.js} +0 -0
- /package/dist/cli/{getMachineId-linux-CBDQri3D.js → getMachineId-linux-Bg5YnekM.js} +0 -0
- /package/dist/cli/{getMachineId-linux-EqaaEzYC.js → getMachineId-linux-Boq-GGfA.js} +0 -0
- /package/dist/cli/{getMachineId-linux-QFNGh16E.js → getMachineId-linux-C9BHlxRm.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-BLalsIU8.js → getMachineId-unsupported-4qhSqb7w.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-CNgpP2gn.js → getMachineId-unsupported-BsEK_LG9.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-CQrnjCuH.js → getMachineId-unsupported-C6cVb167.js} +0 -0
- /package/dist/cli/{getMachineId-unsupported-CcRcqdy3.js → getMachineId-unsupported-CqJy0sqq.js} +0 -0
- /package/dist/cli/{token-error-DVSfBVaT.js → token-error-COQY18OP.js} +0 -0
- /package/dist/cli/{undici-BUZTy5qm.js → undici-CRntNDHY.js} +0 -0
- /package/dist/node/{execAsync-C9Unrkco.cjs → execAsync-BMxJf0Eg.cjs} +0 -0
- /package/dist/node/{getMachineId-linux-B-CtXK0L.cjs → getMachineId-linux-C8A0ak4z.cjs} +0 -0
- /package/dist/node/{getMachineId-linux-BPnkHJah.js → getMachineId-linux-ZoT5w75D.js} +0 -0
- /package/dist/node/{getMachineId-unsupported--0R36RP6.cjs → getMachineId-unsupported-DSRCXJha.cjs} +0 -0
- /package/dist/node/{getMachineId-unsupported-C_4fnT4Z.js → getMachineId-unsupported-XVp8oFCM.js} +0 -0
- /package/dist/node/{index-CnBfy-54.d.ts → index-B4OXlWm3.d.ts} +0 -0
- /package/dist/node/{index.node-Dvc-cHCZ.d.ts → index.node-D5_czyKY.d.ts} +0 -0
- /package/dist/node/{token-util-BOoyY0PX.cjs → token-util-BxSJFXkT.cjs} +0 -0
- /package/dist/node/{token-util-_pz5CtFI.js → token-util-ChGcRyiF.js} +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-BrLfthBj.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-EgdtUZTI.cjs`);let r=require(`zod/v4`);r=e.__toESM(r),require(`zod/v3`);let i=require(`node:buffer`);i=e.__toESM(i);let a=require(`node:fs`);a=e.__toESM(a);let o=require(`node:url`);o=e.__toESM(o);let s=require(`node:stream`);s=e.__toESM(s);let c=require(`node:util`);c=e.__toESM(c);let l=require(`node:crypto`);l=e.__toESM(l);let u=require(`http`);u=e.__toESM(u);let d=require(`path`);d=e.__toESM(d);let f=require(`fs`);f=e.__toESM(f);let p=require(`ai`);p=e.__toESM(p);let m=require(`fs/promises`);m=e.__toESM(m);let h=require(`child_process`);h=e.__toESM(h);let g=require(`react`);g=e.__toESM(g);let _=require(`node:module`);_=e.__toESM(_);let v=require(`zod`);v=e.__toESM(v);let y=require(`node:path`);y=e.__toESM(y);let b=require(`node:process`);b=e.__toESM(b);let x=require(`node:readline`);x=e.__toESM(x);let S=require(`node:child_process`);S=e.__toESM(S);let C=require(`node:fs/promises`);C=e.__toESM(C);let w=require(`node:os`);w=e.__toESM(w),require(`@blink-sdk/compute-protocol/client`);let T=require(`@blink-sdk/compute-protocol/transport`);T=e.__toESM(T);var E=`2.0.23`,D=r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),O=t.createJsonErrorResponseHandler({errorSchema:D,errorToMessage:e=>e.error.message}),k=r.z.object({citations:r.z.object({enabled:r.z.boolean()}).optional(),title:r.z.string().optional(),context:r.z.string().optional()}),A=r.z.object({sendReasoning:r.z.boolean().optional(),thinking:r.z.object({type:r.z.union([r.z.literal(`enabled`),r.z.literal(`disabled`)]),budgetTokens:r.z.number().optional()}).optional(),disableParallelToolUse:r.z.boolean().optional(),cacheControl:r.z.object({type:r.z.literal(`ephemeral`),ttl:r.z.union([r.z.literal(`5m`),r.z.literal(`1h`)]).optional()}).optional()});function j(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var M=r.z.object({maxCharacters:r.z.number().optional()}),N=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ee=(e={})=>N(e),P=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),city:r.z.string().optional(),region:r.z.string().optional(),country:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),F=r.z.array(r.z.object({url:r.z.string(),title:r.z.string(),pageAge:r.z.string().nullable(),encryptedContent:r.z.string(),type:r.z.literal(`web_search_result`)})),te=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.z.object({query:r.z.string()}),outputSchema:F}),I=(e={})=>te(e),L=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),citations:r.z.object({enabled:r.z.boolean()}).optional(),maxContentTokens:r.z.number().optional()}),R=r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.union([r.z.object({type:r.z.literal(`base64`),mediaType:r.z.literal(`application/pdf`),data:r.z.string()}),r.z.object({type:r.z.literal(`text`),mediaType:r.z.literal(`text/plain`),data:r.z.string()})])}),retrievedAt:r.z.string().nullable()}),ne=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.z.object({url:r.z.string()}),outputSchema:R}),z=(e={})=>ne(e);function re({tools:e,toolChoice:n,disableParallelToolUse:r}){e=e?.length?e:void 0;let i=[],a=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};let o=[];for(let t of e)switch(t.type){case`function`:{let e=j(t.providerOptions);o.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:a.add(`code-execution-2025-05-22`),o.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=M.parse(t.args);o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{a.add(`web-fetch-2025-09-10`);let e=L.parse(t.args);o.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=P.parse(t.args);o.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:a};let s=n.type;switch(s){case`auto`:return{tools:o,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`required`:return{tools:o,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case`tool`:return{tools:o,toolChoice:{type:`tool`,name:n.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var B=r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),ie=t.createProviderDefinedToolFactoryWithOutputSchema({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.z.object({code:r.z.string()}),outputSchema:B}),ae=(e={})=>ie(e);function oe(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new t.UnsupportedFunctionalityError({functionality:`URL-based text documents are not supported for citations`}):new t.UnsupportedFunctionalityError({functionality:`unsupported data type for text documents: ${typeof e}`})}async function se({prompt:e,sendReasoning:n,warnings:r}){let i=new Set,a=ce(e),o,s=[];async function c(e){return(await t.parseProviderOptions({provider:`anthropic`,providerOptions:e,schema:k}))?.citations?.enabled??!1}async function l(e){let n=await t.parseProviderOptions({provider:`anthropic`,providerOptions:e,schema:k});return{title:n?.title,context:n?.context}}for(let e=0;e<a.length;e++){let u=a[e],d=e===a.length-1,f=u.type;switch(f){case`system`:if(o!=null)throw new t.UnsupportedFunctionalityError({functionality:`Multiple system messages that are separated by user/assistant messages`});o=u.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:j(t)}));break;case`user`:{let e=[];for(let n of u.messages){let{role:r,content:a}=n;switch(r){case`user`:for(let r=0;r<a.length;r++){let o=a[r],s=r===a.length-1,u=j(o.providerOptions)??(s?j(n.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:t.convertToBase64(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){i.add(`pdfs-2024-09-25`);let n=await c(o.providerOptions),r=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:t.convertToBase64(o.data)},title:r.title??o.filename,...r.context&&{context:r.context},...n&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:oe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r],o=r===a.length-1,s=j(i.providerOptions)??(o?j(n.providerOptions):void 0),c=i.output,l;switch(c.type){case`content`:l=c.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new t.UnsupportedFunctionalityError({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:s})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}}s.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let i=0;i<u.messages.length;i++){let a=u.messages[i],o=i===u.messages.length-1,{content:s}=a;for(let i=0;i<s.length;i++){let c=s[i],l=i===s.length-1,u=j(c.providerOptions)??(l?j(a.providerOptions):void 0);switch(c.type){case`text`:e.push({type:`text`,text:d&&o&&l?c.text.trim():c.text,cache_control:u});break;case`reasoning`:if(n){let n=await t.parseProviderOptions({provider:`anthropic`,providerOptions:c.providerOptions,schema:he});n==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):n.signature==null?n.redactedData==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:n.redactedData,cache_control:u}):e.push({type:`thinking`,thinking:c.text,signature:n.signature,cache_control:u})}else r.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(c.providerExecuted){c.toolName===`code_execution`||c.toolName===`web_fetch`||c.toolName===`web_search`?e.push({type:`server_tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u}):r.push({type:`other`,message:`provider executed tool call for tool ${c.toolName} is not supported`});break}e.push({type:`tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u});break;case`tool-result`:if(c.toolName===`code_execution`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=B.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:c.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:u});break}if(c.toolName===`web_fetch`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=R.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:c.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:u});break}if(c.toolName===`web_search`){let t=c.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let n=F.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:c.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:u});break}r.push({type:`other`,message:`provider executed tool result for tool ${c.toolName} is not supported`});break}}}s.push({role:`assistant`,content:e});break}default:{let e=f;throw Error(`content type: ${e}`)}}}return{prompt:{system:o,messages:s},betas:i}}function ce(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function V({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var H={webSearchResult:r.z.object({type:r.z.literal(`web_search_result_location`),cited_text:r.z.string(),url:r.z.string(),title:r.z.string(),encrypted_index:r.z.string()}),pageLocation:r.z.object({type:r.z.literal(`page_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_page_number:r.z.number(),end_page_number:r.z.number()}),charLocation:r.z.object({type:r.z.literal(`char_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_char_index:r.z.number(),end_char_index:r.z.number()})},le=r.z.discriminatedUnion(`type`,[H.webSearchResult,H.pageLocation,H.charLocation]);r.z.discriminatedUnion(`type`,[H.pageLocation,H.charLocation]);function ue(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=de(e,t,n);i&&r(i)}}function de(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var fe=class{constructor(e,n){this.specificationVersion=`v2`,this.modelId=e,this.config=n,this.generateId=n.generateId??t.generateId}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:n=4096,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[];o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),u!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),l?.type===`json`&&(l.schema==null?m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):d!=null&&m.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let h=l?.type===`json`&&l.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,g=await t.parseProviderOptions({provider:`anthropic`,providerOptions:p,schema:A}),{prompt:_,betas:v}=await se({prompt:e,sendReasoning:g?.sendReasoning??!0,warnings:m}),y=g?.thinking?.type===`enabled`,b=g?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:n,temperature:r,top_k:a,top_p:i,stop_sequences:c,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:_.system,messages:_.messages};if(y){if(b==null)throw new t.UnsupportedFunctionalityError({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(x.top_k=void 0,m.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(x.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=n+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=re(h==null?{tools:d??[],toolChoice:f,disableParallelToolUse:g?.disableParallelToolUse}:{tools:[h],toolChoice:{type:`tool`,toolName:h.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...m,...w],betas:new Set([...v,...T]),usesJsonResponseTool:h!=null}}async getHeaders({betas:e,headers:n}){return t.combineHeaders(await t.resolve(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},n)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:n,warnings:r,betas:i,usesJsonResponseTool:a}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),{responseHeaders:s,value:c,rawValue:l}=await t.postJsonToApi({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(n),failedResponseHandler:O,successfulResponseHandler:t.createJsonResponseHandler(pe),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=[];for(let e of c.content)switch(e.type){case`text`:if(!a&&(u.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)ue(t,o,this.generateId,e=>u.push(e));break;case`thinking`:u.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:u.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:u.push(a?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&u.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?u.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&u.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){u.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)u.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else u.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?u.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&u.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:u,finishReason:V({finishReason:c.stop_reason,isJsonResponseFromTool:a}),usage:{inputTokens:c.usage.input_tokens,outputTokens:c.usage.output_tokens,totalTokens:c.usage.input_tokens+c.usage.output_tokens,cachedInputTokens:c.usage.cache_read_input_tokens??void 0},request:{body:n},response:{id:c.id??void 0,modelId:c.model??void 0,headers:s,body:l},warnings:r,providerMetadata:{anthropic:{usage:c.usage,cacheCreationInputTokens:c.usage.cache_creation_input_tokens??null,stopSequence:c.stop_sequence??null}}}}async doStream(e){let{args:n,warnings:r,betas:i,usesJsonResponseTool:a}=await this.getArgs(e),o=this.extractCitationDocuments(e.prompt),s={...n,stream:!0},{responseHeaders:c,value:l}=await t.postJsonToApi({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(s),failedResponseHandler:O,successfulResponseHandler:t.createEventSourceResponseHandler(me),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=`unknown`,d={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},f={},p,m=null,h=null,g,_=this.generateId;return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(g=e,e){case`text`:f[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:f[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:f[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:f[r.index]=a?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(a?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(f[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:_(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(f[r.index]!=null){let e=f[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:a||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete f[r.index]}g=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(a)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:g===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=f[r.index],t=r.delta.partial_json;if(a){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;ue(e,o,_,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:d.inputTokens=r.message.usage.input_tokens,d.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,p={...r.message.usage},m=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:d.outputTokens=r.usage.output_tokens,d.totalTokens=(d.inputTokens??0)+(r.usage.output_tokens??0),u=V({finishReason:r.delta.stop_reason,isJsonResponseFromTool:a}),h=r.delta.stop_sequence??null,p={...p,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:u,usage:d,providerMetadata:{anthropic:{usage:p??null,cacheCreationInputTokens:m,stopSequence:h}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:s},response:{headers:c}}}},pe=r.z.object({type:r.z.literal(`message`),id:r.z.string().nullish(),model:r.z.string().nullish(),content:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string(),citations:r.z.array(le).optional()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string(),signature:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.unknown()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])),stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})}),me=r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message_start`),message:r.z.object({id:r.z.string().nullish(),model:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})})}),r.z.object({type:r.z.literal(`content_block_start`),index:r.z.number(),content_block:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])}),r.z.object({type:r.z.literal(`content_block_delta`),index:r.z.number(),delta:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`input_json_delta`),partial_json:r.z.string()}),r.z.object({type:r.z.literal(`text_delta`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking_delta`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`signature_delta`),signature:r.z.string()}),r.z.object({type:r.z.literal(`citations_delta`),citation:le})])}),r.z.object({type:r.z.literal(`content_block_stop`),index:r.z.number()}),r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),r.z.object({type:r.z.literal(`message_delta`),delta:r.z.object({stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish()}),usage:r.z.looseObject({output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish()})}),r.z.object({type:r.z.literal(`message_stop`)}),r.z.object({type:r.z.literal(`ping`)})]),he=r.z.object({signature:r.z.string().optional(),redactedData:r.z.string().optional()}),ge=t.createProviderDefinedToolFactory({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),_e=t.createProviderDefinedToolFactory({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),ve=t.createProviderDefinedToolFactory({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.z.array(r.z.number().int()).optional(),text:r.z.string().optional()})}),ye=t.createProviderDefinedToolFactory({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),duration:r.z.number().optional(),scroll_amount:r.z.number().optional(),scroll_direction:r.z.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),text:r.z.string().optional()})}),U=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),be=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),xe=t.createProviderDefinedToolFactory({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),Se={bash_20241022:ge,bash_20250124:_e,codeExecution_20250522:ae,computer_20241022:ve,computer_20250124:ye,textEditor_20241022:U,textEditor_20250124:be,textEditor_20250429:xe,textEditor_20250728:ee,webFetch_20250910:z,webSearch_20250305:I};function Ce(e={}){let n=t.withoutTrailingSlash(e.baseURL)??`https://api.anthropic.com/v1`,r=()=>t.withUserAgentSuffix({"anthropic-version":`2023-06-01`,"x-api-key":t.loadApiKey({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${E}`),i=i=>new fe(i,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:e.generateId??t.generateId,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`imageModel`})},a.tools=Se,a}var we=Ce(),Te=`2.0.17`,Ee=r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string()})}),W=t.createJsonErrorResponseHandler({errorSchema:Ee,errorToMessage:e=>e.error.message}),De=r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),Oe=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}){let a=await t.parseProviderOptions({provider:`google`,providerOptions:i,schema:De});if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=t.combineHeaders(await t.resolve(this.config.headers),n);if(e.length===1){let{responseHeaders:n,value:i,rawValue:s}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:W,successfulResponseHandler:t.createJsonResponseHandler(Ae),abortSignal:r,fetch:this.config.fetch});return{embeddings:[i.embedding.values],usage:void 0,response:{headers:n,body:s}}}let{responseHeaders:s,value:c,rawValue:l}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}))},failedResponseHandler:W,successfulResponseHandler:t.createJsonResponseHandler(ke),abortSignal:r,fetch:this.config.fetch});return{embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},ke=r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}),Ae=r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})});function G(e){if(e==null||je(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=G(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(G):G(a)),o&&(p.allOf=o.map(G)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=G(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(G),p.nullable=!0}else p.anyOf=s.map(G);return c&&(p.oneOf=c.map(G)),d!==void 0&&(p.minLength=d),p}function je(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function Me(e,n){let r=[],i=[],a=!0,o=n?.isGemmaModel??!1;for(let{role:n,content:o}of e)switch(n){case`system`:if(!a)throw new t.UnsupportedFunctionalityError({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let n of o)switch(n.type){case`text`:e.push({text:n.text});break;case`file`:{let r=n.mediaType===`image/*`?`image/jpeg`:n.mediaType;e.push(n.data instanceof URL?{fileData:{mimeType:r,fileUri:n.data.toString()}}:{inlineData:{mimeType:r,data:t.convertToBase64(n.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new t.UnsupportedFunctionalityError({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:t.convertToBase64(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
|
|
1
|
+
const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-Bvp48I1R.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-EgdtUZTI.cjs`);let r=require(`zod/v4`);r=e.__toESM(r);let i=require(`zod/v3`);i=e.__toESM(i);let a=require(`node:buffer`);a=e.__toESM(a);let o=require(`node:fs`);o=e.__toESM(o);let s=require(`node:url`);s=e.__toESM(s);let c=require(`node:stream`);c=e.__toESM(c);let l=require(`node:util`);l=e.__toESM(l);let u=require(`node:crypto`);u=e.__toESM(u);let d=require(`http`);d=e.__toESM(d);let f=require(`path`);f=e.__toESM(f);let p=require(`fs`);p=e.__toESM(p);let m=require(`ai`);m=e.__toESM(m);let h=require(`fs/promises`);h=e.__toESM(h);let g=require(`child_process`);g=e.__toESM(g);let _=require(`react`);_=e.__toESM(_);let v=require(`node:module`);v=e.__toESM(v);let y=require(`zod`);y=e.__toESM(y);let b=require(`node:path`);b=e.__toESM(b);let x=require(`node:process`);x=e.__toESM(x);let S=require(`node:os`);S=e.__toESM(S);let C=require(`node:tty`);C=e.__toESM(C);let w=require(`node:readline`);w=e.__toESM(w);let T=require(`node:child_process`);T=e.__toESM(T);let E=require(`node:fs/promises`);E=e.__toESM(E),require(`@blink-sdk/compute-protocol/client`);let D=require(`@blink-sdk/compute-protocol/transport`);D=e.__toESM(D);function O(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function k(e){return Object.fromEntries([...e.headers])}function A(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 j(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function M(e,...t){let n=j(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var N=({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()}`},ee=N();function P(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var F=[`fetch failed`,`failed to fetch`];function te({error:e,url:n,requestBodyValues:r}){if(P(e))return e;if(e instanceof TypeError&&F.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 I=`3.0.10`;function L({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 R=/"__proto__"\s*:/,ne=/"constructor"\s*:/;function z(e){let t=JSON.parse(e);return typeof t!=`object`||!t||R.test(e)===!1&&ne.test(e)===!1?t:re(t)}function re(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 B(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return z(e)}finally{Error.stackTraceLimit=t}}var ie=Symbol.for(`vercel.ai.validator`);function ae(e){return{[ie]:!0,validate:e}}function oe(e){return typeof e==`object`&&!!e&&ie in e&&e[ie]===!0&&`validate`in e}function se(e){return oe(e)?e:ce(e)}function ce(e){return ae(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 V({value:e,schema:n}){let r=await le({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function le({value:e,schema:n}){let r=se(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 ue({text:e,schema:n}){try{let t=B(e);return n==null?t:V({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 de({text:e,schema:n}){try{let t=B(e);return n==null?{success:!0,value:t,rawValue:t}:await le({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 fe({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 de({text:e,schema:n}))}}))}async function pe({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await le({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 me=()=>globalThis.fetch,he=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>ge({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),ge=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=me()})=>{try{let c=await s(e,{method:`POST`,headers:M(n,`ai-sdk/provider-utils/${I}`,A()),body:r.content,signal:o}),l=k(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw P(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&&(P(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 te({error:t,url:e,requestBodyValues:r.values})}};function _e(e){return e}function ve({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_e({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function ye({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_e({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function be(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var H=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=k(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 ue({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)})}}},xe=e=>async({response:n})=>{let r=k(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:fe({stream:n.body,schema:e})}},Se=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await de({text:a,schema:e}),s=k(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}},Ce=Symbol(`Let zodToJsonSchema decide on which parser to use`),we=Symbol.for(`vercel.ai.schema`),{btoa:Te,atob:Ee}=globalThis;function De(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Te(t)}function Oe(e){return e instanceof Uint8Array?De(e):e}function ke(e){return e?.replace(/\/$/,``)}var Ae=`2.0.23`,je=r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),Me=H({errorSchema:je,errorToMessage:e=>e.error.message}),U=r.z.object({citations:r.z.object({enabled:r.z.boolean()}).optional(),title:r.z.string().optional(),context:r.z.string().optional()}),Ne=r.z.object({sendReasoning:r.z.boolean().optional(),thinking:r.z.object({type:r.z.union([r.z.literal(`enabled`),r.z.literal(`disabled`)]),budgetTokens:r.z.number().optional()}).optional(),disableParallelToolUse:r.z.boolean().optional(),cacheControl:r.z.object({type:r.z.literal(`ephemeral`),ttl:r.z.union([r.z.literal(`5m`),r.z.literal(`1h`)]).optional()}).optional()});function Pe(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Fe=r.z.object({maxCharacters:r.z.number().optional()}),Ie=ve({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),Le=(e={})=>Ie(e),Re=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),userLocation:r.z.object({type:r.z.literal(`approximate`),city:r.z.string().optional(),region:r.z.string().optional(),country:r.z.string().optional(),timezone:r.z.string().optional()}).optional()}),ze=r.z.array(r.z.object({url:r.z.string(),title:r.z.string(),pageAge:r.z.string().nullable(),encryptedContent:r.z.string(),type:r.z.literal(`web_search_result`)})),Be=ye({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:r.z.object({query:r.z.string()}),outputSchema:ze}),Ve=(e={})=>Be(e),He=r.z.object({maxUses:r.z.number().optional(),allowedDomains:r.z.array(r.z.string()).optional(),blockedDomains:r.z.array(r.z.string()).optional(),citations:r.z.object({enabled:r.z.boolean()}).optional(),maxContentTokens:r.z.number().optional()}),Ue=r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.union([r.z.object({type:r.z.literal(`base64`),mediaType:r.z.literal(`application/pdf`),data:r.z.string()}),r.z.object({type:r.z.literal(`text`),mediaType:r.z.literal(`text/plain`),data:r.z.string()})])}),retrievedAt:r.z.string().nullable()}),We=ye({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:r.z.object({url:r.z.string()}),outputSchema:Ue}),Ge=(e={})=>We(e);function Ke({tools:e,toolChoice:n,disableParallelToolUse:r}){e=e?.length?e:void 0;let i=[],a=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};let o=[];for(let t of e)switch(t.type){case`function`:{let e=Pe(t.providerOptions);o.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break}case`provider-defined`:switch(t.id){case`anthropic.code_execution_20250522`:a.add(`code-execution-2025-05-22`),o.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:a.add(`computer-use-2025-01-24`),o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Fe.parse(t.args);o.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:a.add(`computer-use-2025-01-24`),o.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:a.add(`computer-use-2024-10-22`),o.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{a.add(`web-fetch-2025-09-10`);let e=He.parse(t.args);o.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens});break}case`anthropic.web_search_20250305`:{let e=Re.parse(t.args);o.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}default:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:i,betas:a};let s=n.type;switch(s){case`auto`:return{tools:o,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`required`:return{tools:o,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:i,betas:a};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case`tool`:return{tools:o,toolChoice:{type:`tool`,name:n.toolName,disable_parallel_tool_use:r},toolWarnings:i,betas:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var qe=r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),Je=ye({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:r.z.object({code:r.z.string()}),outputSchema:qe}),Ye=(e={})=>Je(e);function Xe(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new t.UnsupportedFunctionalityError({functionality:`URL-based text documents are not supported for citations`}):new t.UnsupportedFunctionalityError({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Ze({prompt:e,sendReasoning:n,warnings:r}){let i=new Set,a=Qe(e),o,s=[];async function c(e){return(await pe({provider:`anthropic`,providerOptions:e,schema:U}))?.citations?.enabled??!1}async function l(e){let t=await pe({provider:`anthropic`,providerOptions:e,schema:U});return{title:t?.title,context:t?.context}}for(let e=0;e<a.length;e++){let u=a[e],d=e===a.length-1,f=u.type;switch(f){case`system`:if(o!=null)throw new t.UnsupportedFunctionalityError({functionality:`Multiple system messages that are separated by user/assistant messages`});o=u.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pe(t)}));break;case`user`:{let e=[];for(let n of u.messages){let{role:r,content:a}=n;switch(r){case`user`:for(let r=0;r<a.length;r++){let o=a[r],s=r===a.length-1,u=Pe(o.providerOptions)??(s?Pe(n.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:Oe(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){i.add(`pdfs-2024-09-25`);let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Oe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await c(o.providerOptions),n=await l(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xe(o.data)},title:n.title??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new t.UnsupportedFunctionalityError({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let r=0;r<a.length;r++){let i=a[r],o=r===a.length-1,s=Pe(i.providerOptions)??(o?Pe(n.providerOptions):void 0),c=i.output,l;switch(c.type){case`content`:l=c.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new t.UnsupportedFunctionalityError({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:s})}break;default:{let e=r;throw Error(`Unsupported role: ${e}`)}}}s.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let t=0;t<u.messages.length;t++){let i=u.messages[t],a=t===u.messages.length-1,{content:o}=i;for(let t=0;t<o.length;t++){let s=o[t],c=t===o.length-1,l=Pe(s.providerOptions)??(c?Pe(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:d&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(n){let t=await pe({provider:`anthropic`,providerOptions:s.providerOptions,schema:st});t==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:l}):e.push({type:`thinking`,thinking:s.text,signature:t.signature,cache_control:l})}else r.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(s.providerExecuted){s.toolName===`code_execution`||s.toolName===`web_fetch`||s.toolName===`web_search`?e.push({type:`server_tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l}):r.push({type:`other`,message:`provider executed tool call for tool ${s.toolName} is not supported`});break}e.push({type:`tool_use`,id:s.toolCallId,name:s.toolName,input:s.input,cache_control:l});break;case`tool-result`:if(s.toolName===`code_execution`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=qe.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=Ue.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let n=ze.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}r.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}s.push({role:`assistant`,content:e});break}default:{let e=f;throw Error(`content type: ${e}`)}}}return{prompt:{system:o,messages:s},betas:i}}function Qe(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function $e({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var et={webSearchResult:r.z.object({type:r.z.literal(`web_search_result_location`),cited_text:r.z.string(),url:r.z.string(),title:r.z.string(),encrypted_index:r.z.string()}),pageLocation:r.z.object({type:r.z.literal(`page_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_page_number:r.z.number(),end_page_number:r.z.number()}),charLocation:r.z.object({type:r.z.literal(`char_location`),cited_text:r.z.string(),document_index:r.z.number(),document_title:r.z.string().nullable(),start_char_index:r.z.number(),end_char_index:r.z.number()})},tt=r.z.discriminatedUnion(`type`,[et.webSearchResult,et.pageLocation,et.charLocation]);r.z.discriminatedUnion(`type`,[et.pageLocation,et.charLocation]);function nt(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rt(e,t,n);i&&r(i)}}function rt(e,t,n){let r=t[e.document_index];if(!r)return null;let i=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:i}}}var it=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??ee}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:n=4096,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[];o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),u!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),l?.type===`json`&&(l.schema==null?m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):d!=null&&m.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let h=l?.type===`json`&&l.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,g=await pe({provider:`anthropic`,providerOptions:p,schema:Ne}),{prompt:_,betas:v}=await Ze({prompt:e,sendReasoning:g?.sendReasoning??!0,warnings:m}),y=g?.thinking?.type===`enabled`,b=g?.thinking?.budgetTokens,x={model:this.modelId,max_tokens:n,temperature:r,top_k:a,top_p:i,stop_sequences:c,...y&&{thinking:{type:`enabled`,budget_tokens:b}},system:_.system,messages:_.messages};if(y){if(b==null)throw new t.UnsupportedFunctionalityError({functionality:`thinking requires a budget`});x.temperature!=null&&(x.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(x.top_k=void 0,m.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(x.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),x.max_tokens=n+b}let{tools:S,toolChoice:C,toolWarnings:w,betas:T}=Ke(h==null?{tools:d??[],toolChoice:f,disableParallelToolUse:g?.disableParallelToolUse}:{tools:[h],toolChoice:{type:`tool`,toolName:h.name},disableParallelToolUse:!0});return{args:{...x,tools:S,tool_choice:C},warnings:[...m,...w],betas:new Set([...v,...T]),usesJsonResponseTool:h!=null}}async getHeaders({betas:e,headers:t}){return O(await be(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),{responseHeaders:o,value:s,rawValue:c}=await he({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:Me,successfulResponseHandler:Se(at),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];for(let e of s.content)switch(e.type){case`text`:if(!i&&(l.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)nt(t,a,this.generateId,e=>l.push(e));break;case`thinking`:l.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:l.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:l.push(i?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`)&&l.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}},providerExecuted:!0}):e.content.type===`web_fetch_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)l.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&l.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:l,finishReason:$e({finishReason:s.stop_reason,isJsonResponseFromTool:i}),usage:{inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens,totalTokens:s.usage.input_tokens+s.usage.output_tokens,cachedInputTokens:s.usage.cache_read_input_tokens??void 0},request:{body:t},response:{id:s.id??void 0,modelId:s.model??void 0,headers:o,body:c},warnings:n,providerMetadata:{anthropic:{usage:s.usage,cacheCreationInputTokens:s.usage.cache_creation_input_tokens??null,stopSequence:s.stop_sequence??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await he({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:Me,successfulResponseHandler:xe(ot),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p=null,m=null,h,g=this.generateId;return{stream:c.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 r=t.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block.type;switch(h=e,e){case`text`:d[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:d[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:r.content_block.data}}});return;case`tool_use`:d[r.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(r.index)}:{type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name});return;case`server_tool_use`:(r.content_block.name===`web_fetch`||r.content_block.name===`web_search`||r.content_block.name===`code_execution`)&&(d[r.index]={type:`tool-call`,toolCallId:r.content_block.id,toolName:r.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:r.content_block.id,toolName:r.content_block.name,providerExecuted:!0}));return;case`web_fetch_tool_result`:{let e=r.content_block;e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_fetch`,isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`web_search_tool_result`:{let e=r.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type})),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:g(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=r.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[r.index]!=null){let e=d[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[r.index]}h=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:h===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=d[r.index],t=r.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=r.delta.citation;nt(e,a,g,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=r.message.usage.input_tokens,u.cachedInputTokens=r.message.usage.cache_read_input_tokens??void 0,f={...r.message.usage},p=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:u.outputTokens=r.usage.output_tokens,u.totalTokens=(u.inputTokens??0)+(r.usage.output_tokens??0),l=$e({finishReason:r.delta.stop_reason,isJsonResponseFromTool:i}),m=r.delta.stop_sequence??null,f={...f,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:{anthropic:{usage:f??null,cacheCreationInputTokens:p,stopSequence:m}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},at=r.z.object({type:r.z.literal(`message`),id:r.z.string().nullish(),model:r.z.string().nullish(),content:r.z.array(r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string(),citations:r.z.array(tt).optional()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string(),signature:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.unknown()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])),stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})}),ot=r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`message_start`),message:r.z.object({id:r.z.string().nullish(),model:r.z.string().nullish(),usage:r.z.looseObject({input_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish(),cache_read_input_tokens:r.z.number().nullish()})})}),r.z.object({type:r.z.literal(`content_block_start`),index:r.z.number(),content_block:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`text`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`tool_use`),id:r.z.string(),name:r.z.string()}),r.z.object({type:r.z.literal(`redacted_thinking`),data:r.z.string()}),r.z.object({type:r.z.literal(`server_tool_use`),id:r.z.string(),name:r.z.string(),input:r.z.record(r.z.string(),r.z.unknown()).nullish()}),r.z.object({type:r.z.literal(`web_fetch_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`web_fetch_result`),url:r.z.string(),retrieved_at:r.z.string(),content:r.z.object({type:r.z.literal(`document`),title:r.z.string().nullable(),citations:r.z.object({enabled:r.z.boolean()}).optional(),source:r.z.object({type:r.z.literal(`text`),media_type:r.z.string(),data:r.z.string()})})}),r.z.object({type:r.z.literal(`web_fetch_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`web_search_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.array(r.z.object({type:r.z.literal(`web_search_result`),url:r.z.string(),title:r.z.string(),encrypted_content:r.z.string(),page_age:r.z.string().nullish()})),r.z.object({type:r.z.literal(`web_search_tool_result_error`),error_code:r.z.string()})])}),r.z.object({type:r.z.literal(`code_execution_tool_result`),tool_use_id:r.z.string(),content:r.z.union([r.z.object({type:r.z.literal(`code_execution_result`),stdout:r.z.string(),stderr:r.z.string(),return_code:r.z.number()}),r.z.object({type:r.z.literal(`code_execution_tool_result_error`),error_code:r.z.string()})])})])}),r.z.object({type:r.z.literal(`content_block_delta`),index:r.z.number(),delta:r.z.discriminatedUnion(`type`,[r.z.object({type:r.z.literal(`input_json_delta`),partial_json:r.z.string()}),r.z.object({type:r.z.literal(`text_delta`),text:r.z.string()}),r.z.object({type:r.z.literal(`thinking_delta`),thinking:r.z.string()}),r.z.object({type:r.z.literal(`signature_delta`),signature:r.z.string()}),r.z.object({type:r.z.literal(`citations_delta`),citation:tt})])}),r.z.object({type:r.z.literal(`content_block_stop`),index:r.z.number()}),r.z.object({type:r.z.literal(`error`),error:r.z.object({type:r.z.string(),message:r.z.string()})}),r.z.object({type:r.z.literal(`message_delta`),delta:r.z.object({stop_reason:r.z.string().nullish(),stop_sequence:r.z.string().nullish()}),usage:r.z.looseObject({output_tokens:r.z.number(),cache_creation_input_tokens:r.z.number().nullish()})}),r.z.object({type:r.z.literal(`message_stop`)}),r.z.object({type:r.z.literal(`ping`)})]),st=r.z.object({signature:r.z.string().optional(),redactedData:r.z.string().optional()}),ct=ve({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),lt=ve({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:r.default.object({command:r.default.string(),restart:r.default.boolean().optional()})}),ut=ve({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:r.z.array(r.z.number().int()).optional(),text:r.z.string().optional()})}),dt=ve({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:r.z.object({action:r.z.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),duration:r.z.number().optional(),scroll_amount:r.z.number().optional(),scroll_direction:r.z.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:r.z.tuple([r.z.number().int(),r.z.number().int()]).optional(),text:r.z.string().optional()})}),ft=ve({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),pt=ve({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),mt=ve({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:r.z.object({command:r.z.enum([`view`,`create`,`str_replace`,`insert`]),path:r.z.string(),file_text:r.z.string().optional(),insert_line:r.z.number().int().optional(),new_str:r.z.string().optional(),old_str:r.z.string().optional(),view_range:r.z.array(r.z.number().int()).optional()})}),ht={bash_20241022:ct,bash_20250124:lt,codeExecution_20250522:Ye,computer_20241022:ut,computer_20250124:dt,textEditor_20241022:ft,textEditor_20250124:pt,textEditor_20250429:mt,textEditor_20250728:Le,webFetch_20250910:Ge,webSearch_20250305:Ve};function gt(e={}){let n=ke(e.baseURL)??`https://api.anthropic.com/v1`,r=()=>M({"anthropic-version":`2023-06-01`,"x-api-key":L({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${Ae}`),i=t=>new it(t,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:e.generateId??ee,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new t.NoSuchModelError({modelId:e,modelType:`imageModel`})},a.tools=ht,a}var _t=gt();function vt(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yt(e){return Object.fromEntries([...e.headers])}function bt(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 xt(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function St(e,...t){let n=xt(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ct=({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()}`},wt=Ct();function Tt(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Et=[`fetch failed`,`failed to fetch`];function Dt({error:e,url:n,requestBodyValues:r}){if(Tt(e))return e;if(e instanceof TypeError&&Et.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 Ot=`3.0.10`;function kt({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 At=/"__proto__"\s*:/,jt=/"constructor"\s*:/;function Mt(e){let t=JSON.parse(e);return typeof t!=`object`||!t||At.test(e)===!1&&jt.test(e)===!1?t:Nt(t)}function Nt(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 Pt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Mt(e)}finally{Error.stackTraceLimit=t}}var Ft=Symbol.for(`vercel.ai.validator`);function It(e){return{[Ft]:!0,validate:e}}function Lt(e){return typeof e==`object`&&!!e&&Ft in e&&e[Ft]===!0&&`validate`in e}function Rt(e){return Lt(e)?e:zt(e)}function zt(e){return It(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 Bt({value:e,schema:n}){let r=await Vt({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function Vt({value:e,schema:n}){let r=Rt(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 Ht({text:e,schema:n}){try{let t=Pt(e);return n==null?t:Bt({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 Ut({text:e,schema:n}){try{let t=Pt(e);return n==null?{success:!0,value:t,rawValue:t}:await Vt({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 Wt({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 Ut({text:e,schema:n}))}}))}async function Gt({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await Vt({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 Kt=()=>globalThis.fetch,qt=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Jt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Jt=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=Kt()})=>{try{let c=await s(e,{method:`POST`,headers:St(n,`ai-sdk/provider-utils/${Ot}`,bt()),body:r.content,signal:o}),l=yt(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw Tt(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&&(Tt(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 Dt({error:t,url:e,requestBodyValues:r.values})}};function Yt(e){return e}function Xt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Yt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Zt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Yt({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function Qt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var $t=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=yt(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 Ht({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)})}}},en=e=>async({response:n})=>{let r=yt(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:Wt({stream:n.body,schema:e})}},tn=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await Ut({text:a,schema:e}),s=yt(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}},nn=Symbol(`Let zodToJsonSchema decide on which parser to use`),rn=Symbol.for(`vercel.ai.schema`),{btoa:an,atob:on}=globalThis;function sn(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return an(t)}function cn(e){return e instanceof Uint8Array?sn(e):e}function ln(e){return e?.replace(/\/$/,``)}var un=`2.0.17`,dn=r.z.object({error:r.z.object({code:r.z.number().nullable(),message:r.z.string(),status:r.z.string()})}),fn=$t({errorSchema:dn,errorToMessage:e=>e.error.message}),pn=r.z.object({outputDimensionality:r.z.number().optional(),taskType:r.z.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),mn=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}){let a=await Gt({provider:`google`,providerOptions:i,schema:pn});if(e.length>this.maxEmbeddingsPerCall)throw new t.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=vt(await Qt(this.config.headers),n);if(e.length===1){let{responseHeaders:t,value:n,rawValue:i}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:fn,successfulResponseHandler:tn(gn),abortSignal:r,fetch:this.config.fetch});return{embeddings:[n.embedding.values],usage:void 0,response:{headers:t,body:i}}}let{responseHeaders:s,value:c,rawValue:l}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}))},failedResponseHandler:fn,successfulResponseHandler:tn(hn),abortSignal:r,fetch:this.config.fetch});return{embeddings:c.embeddings.map(e=>e.values),usage:void 0,response:{headers:s,body:l}}}},hn=r.z.object({embeddings:r.z.array(r.z.object({values:r.z.array(r.z.number())}))}),gn=r.z.object({embedding:r.z.object({values:r.z.array(r.z.number())})});function _n(e){if(e==null||vn(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=_n(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(_n):_n(a)),o&&(p.allOf=o.map(_n)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=_n(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(_n),p.nullable=!0}else p.anyOf=s.map(_n);return c&&(p.oneOf=c.map(_n)),d!==void 0&&(p.minLength=d),p}function vn(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function yn(e,n){let r=[],i=[],a=!0,o=n?.isGemmaModel??!1;for(let{role:n,content:o}of e)switch(n){case`system`:if(!a)throw new t.UnsupportedFunctionalityError({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:cn(t.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:e.providerOptions?.google?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new t.UnsupportedFunctionalityError({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:cn(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:e.providerOptions?.google?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
|
|
2
2
|
|
|
3
3
|
`);i[0].parts.unshift({text:e+`
|
|
4
4
|
|
|
5
|
-
`})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function Ne(e){return e.includes(`/`)?e:`models/${e}`}var Pe=r.z.object({responseModalities:r.z.array(r.z.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:r.z.object({thinkingBudget:r.z.number().optional(),includeThoughts:r.z.boolean().optional()}).optional(),cachedContent:r.z.string().optional(),structuredOutputs:r.z.boolean().optional(),safetySettings:r.z.array(r.z.object({category:r.z.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:r.z.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:r.z.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:r.z.boolean().optional(),labels:r.z.record(r.z.string(),r.z.string()).optional()});function Fe({tools:e,toolChoice:n,modelId:r}){e=e?.length?e:void 0;let i=[],a=r.includes(`gemini-2`),o=r.includes(`gemini-1.5-flash`)&&!r.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:i};let s=e.some(e=>e.type===`function`),c=e.some(e=>e.type===`provider-defined`);if(s&&c&&i.push({type:`unsupported-tool`,tool:e.find(e=>e.type===`function`),details:`Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both.`}),c){let t={};return e.filter(e=>e.type===`provider-defined`).forEach(e=>{switch(e.id){case`google.google_search`:a?t.googleSearch={}:o?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:a?t.urlContext={}:i.push({type:`unsupported-tool`,tool:e,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:a?t.codeExecution={}:i.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:i.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:i}}let l=[];for(let t of e)switch(t.type){case`function`:l.push({name:t.name,description:t.description??``,parameters:G(t.inputSchema)});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:{functionDeclarations:l},toolConfig:void 0,toolWarnings:i};let u=n.type;switch(u){case`auto`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:i};case`none`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:i};case`required`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:i};case`tool`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[n.toolName]}},toolWarnings:i};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${u}`})}}function Ie({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`FINISH_REASON_UNSPECIFIED`:case`OTHER`:return`other`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`unknown`}}var Le=r.z.object({web:r.z.object({uri:r.z.string(),title:r.z.string()}).nullish(),retrievedContext:r.z.object({uri:r.z.string(),title:r.z.string()}).nullish()}),Re=r.z.object({webSearchQueries:r.z.array(r.z.string()).nullish(),retrievalQueries:r.z.array(r.z.string()).nullish(),searchEntryPoint:r.z.object({renderedContent:r.z.string()}).nullish(),groundingChunks:r.z.array(Le).nullish(),groundingSupports:r.z.array(r.z.object({segment:r.z.object({startIndex:r.z.number().nullish(),endIndex:r.z.number().nullish(),text:r.z.string().nullish()}),segment_text:r.z.string().nullish(),groundingChunkIndices:r.z.array(r.z.number()).nullish(),supportChunkIndices:r.z.array(r.z.number()).nullish(),confidenceScores:r.z.array(r.z.number()).nullish(),confidenceScore:r.z.array(r.z.number()).nullish()})).nullish(),retrievalMetadata:r.z.union([r.z.object({webDynamicRetrievalScore:r.z.number()}),r.z.object({})]).nullish()}),ze=t.createProviderDefinedToolFactory({id:`google.google_search`,name:`google_search`,inputSchema:r.z.object({mode:r.z.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:r.z.number().default(1)})}),Be=r.z.object({retrievedUrl:r.z.string(),urlRetrievalStatus:r.z.string()}),Ve=r.z.object({urlMetadata:r.z.array(Be)}),He=t.createProviderDefinedToolFactory({id:`google.url_context`,name:`url_context`,inputSchema:r.z.object({})}),Ue=class{constructor(e,n){this.specificationVersion=`v2`,this.modelId=e,this.config=n,this.generateId=n.generateId??t.generateId}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:n,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[],h=await t.parseProviderOptions({provider:`google`,providerOptions:p,schema:Pe});h?.thinkingConfig?.includeThoughts===!0&&!this.config.provider.startsWith(`google.vertex.`)&&m.push({type:`other`,message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let g=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:_,systemInstruction:v}=Me(e,{isGemmaModel:g}),{tools:y,toolConfig:b,toolWarnings:x}=Fe({tools:d,toolChoice:f,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:n,temperature:r,topK:a,topP:i,frequencyPenalty:o,presencePenalty:s,stopSequences:c,seed:u,responseMimeType:l?.type===`json`?`application/json`:void 0,responseSchema:l?.type===`json`&&l.schema!=null&&(h?.structuredOutputs??!0)?G(l.schema):void 0,...h?.audioTimestamp&&{audioTimestamp:h.audioTimestamp},responseModalities:h?.responseModalities,thinkingConfig:h?.thinkingConfig},contents:_,systemInstruction:g?void 0:v,safetySettings:h?.safetySettings,tools:y,toolConfig:b,cachedContent:h?.cachedContent,labels:h?.labels},warnings:[...m,...x]}}async doGenerate(e){let{args:n,warnings:r}=await this.getArgs(e),i=JSON.stringify(n),a=t.combineHeaders(await t.resolve(this.config.headers),e.headers),{responseHeaders:o,value:s,rawValue:c}=await t.postJsonToApi({url:`${this.config.baseURL}/${Ne(this.modelId)}:generateContent`,headers:a,body:n,failedResponseHandler:W,successfulResponseHandler:t.createJsonResponseHandler(Xe),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.candidates[0],u=[],d=l.content?.parts??[],f=s.usageMetadata,p;for(let e of d)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();p=t,u.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else `codeExecutionResult`in e&&e.codeExecutionResult?(u.push({type:`tool-result`,toolCallId:p,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output},providerExecuted:!0}),p=void 0):`text`in e&&e.text!=null&&e.text.length>0?u.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`functionCall`in e?u.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`inlineData`in e&&u.push({type:`file`,data:e.inlineData.data,mediaType:e.inlineData.mimeType});let m=Ke({groundingMetadata:l.groundingMetadata,generateId:this.config.generateId})??[];for(let e of m)u.push(e);return{content:u,finishReason:Ie({finishReason:l.finishReason,hasToolCalls:u.some(e=>e.type===`tool-call`)}),usage:{inputTokens:f?.promptTokenCount??void 0,outputTokens:f?.candidatesTokenCount??void 0,totalTokens:f?.totalTokenCount??void 0,reasoningTokens:f?.thoughtsTokenCount??void 0,cachedInputTokens:f?.cachedContentTokenCount??void 0},warnings:r,providerMetadata:{google:{promptFeedback:s.promptFeedback??null,groundingMetadata:l.groundingMetadata??null,urlContextMetadata:l.urlContextMetadata??null,safetyRatings:l.safetyRatings??null,usageMetadata:f??null}},request:{body:i},response:{headers:o,body:c}}}async doStream(e){let{args:n,warnings:r}=await this.getArgs(e),i=JSON.stringify(n),a=t.combineHeaders(await t.resolve(this.config.headers),e.headers),{responseHeaders:o,value:s}=await t.postJsonToApi({url:`${this.config.baseURL}/${Ne(this.modelId)}:streamGenerateContent?alt=sse`,headers:a,body:n,failedResponseHandler:W,successfulResponseHandler:t.createEventSourceResponseHandler(Ze),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=`unknown`,l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u,d=this.config.generateId,f=!1,p=null,m=null,h=0,g=new Set,_;return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,i=r.usageMetadata;i!=null&&(l.inputTokens=i.promptTokenCount??void 0,l.outputTokens=i.candidatesTokenCount??void 0,l.totalTokens=i.totalTokenCount??void 0,l.reasoningTokens=i.thoughtsTokenCount??void 0,l.cachedInputTokens=i.cachedContentTokenCount??void 0);let a=r.candidates?.[0];if(a==null)return;let o=a.content,s=Ke({groundingMetadata:a.groundingMetadata,generateId:d});if(s!=null)for(let e of s)e.sourceType===`url`&&!g.has(e.url)&&(g.add(e.url),n.enqueue(e));if(o!=null){let e=o.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=d();_=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0}),f=!0}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=_;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output},providerExecuted:!0}),_=void 0)}else `text`in t&&t.text!=null&&t.text.length>0&&(t.thought===!0?(p!==null&&(n.enqueue({type:`text-end`,id:p}),p=null),m===null&&(m=String(h++),n.enqueue({type:`reasoning-start`,id:m,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`reasoning-delta`,id:m,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})):(m!==null&&(n.enqueue({type:`reasoning-end`,id:m}),m=null),p===null&&(p=String(h++),n.enqueue({type:`text-start`,id:p,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`text-delta`,id:p,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})));let t=Ge(o.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=We({parts:o.parts,generateId:d});if(r!=null)for(let e of r)n.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.args,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,providerMetadata:e.providerMetadata}),f=!0}a.finishReason!=null&&(c=Ie({finishReason:a.finishReason,hasToolCalls:f}),u={google:{promptFeedback:r.promptFeedback??null,groundingMetadata:a.groundingMetadata??null,urlContextMetadata:a.urlContextMetadata??null,safetyRatings:a.safetyRatings??null}},i!=null&&(u.google.usageMetadata=i))},flush(e){p!==null&&e.enqueue({type:`text-end`,id:p}),m!==null&&e.enqueue({type:`reasoning-end`,id:m}),e.enqueue({type:`finish`,finishReason:c,usage:l,providerMetadata:u})}})),response:{headers:o},request:{body:i}}}};function We({parts:e,generateId:t}){let n=e?.filter(e=>`functionCall`in e);return n==null||n.length===0?void 0:n.map(e=>({type:`tool-call`,toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}function Ge(e){return e?.filter(e=>`inlineData`in e)}function Ke({groundingMetadata:e,generateId:t}){return(e?.groundingChunks)?.filter(e=>e.web!=null).map(e=>({type:`source`,sourceType:`url`,id:t(),url:e.web.uri,title:e.web.title}))}var qe=r.z.object({parts:r.z.array(r.z.union([r.z.object({functionCall:r.z.object({name:r.z.string(),args:r.z.unknown()}),thoughtSignature:r.z.string().nullish()}),r.z.object({inlineData:r.z.object({mimeType:r.z.string(),data:r.z.string()})}),r.z.object({executableCode:r.z.object({language:r.z.string(),code:r.z.string()}).nullish(),codeExecutionResult:r.z.object({outcome:r.z.string(),output:r.z.string()}).nullish(),text:r.z.string().nullish(),thought:r.z.boolean().nullish(),thoughtSignature:r.z.string().nullish()})])).nullish()}),Je=r.z.object({category:r.z.string().nullish(),probability:r.z.string().nullish(),probabilityScore:r.z.number().nullish(),severity:r.z.string().nullish(),severityScore:r.z.number().nullish(),blocked:r.z.boolean().nullish()}),Ye=r.z.object({cachedContentTokenCount:r.z.number().nullish(),thoughtsTokenCount:r.z.number().nullish(),promptTokenCount:r.z.number().nullish(),candidatesTokenCount:r.z.number().nullish(),totalTokenCount:r.z.number().nullish()}),Xe=r.z.object({candidates:r.z.array(r.z.object({content:qe.nullish().or(r.z.object({}).strict()),finishReason:r.z.string().nullish(),safetyRatings:r.z.array(Je).nullish(),groundingMetadata:Re.nullish(),urlContextMetadata:Ve.nullish()})),usageMetadata:Ye.nullish(),promptFeedback:r.z.object({blockReason:r.z.string().nullish(),safetyRatings:r.z.array(Je).nullish()}).nullish()}),Ze=r.z.object({candidates:r.z.array(r.z.object({content:qe.nullish(),finishReason:r.z.string().nullish(),safetyRatings:r.z.array(Je).nullish(),groundingMetadata:Re.nullish(),urlContextMetadata:Ve.nullish()})).nullish(),usageMetadata:Ye.nullish(),promptFeedback:r.z.object({blockReason:r.z.string().nullish(),safetyRatings:r.z.array(Je).nullish()}).nullish()}),Qe=t.createProviderDefinedToolFactoryWithOutputSchema({id:`google.code_execution`,name:`code_execution`,inputSchema:r.z.object({language:r.z.string().describe(`The programming language of the code.`),code:r.z.string().describe(`The code to be executed.`)}),outputSchema:r.z.object({outcome:r.z.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:r.z.string().describe(`The output from the code execution.`)})}),$e={googleSearch:ze,urlContext:He,codeExecution:Qe},et=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v2`}get maxImagesPerCall(){return this.settings.maxImagesPerCall??4}get provider(){return this.config.provider}async doGenerate(e){var n;let{prompt:r,n:i=1,size:a=`1024x1024`,aspectRatio:o=`1:1`,seed:s,providerOptions:c,headers:l,abortSignal:u}=e,d=[];a!=null&&d.push({type:`unsupported-setting`,setting:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),s!=null&&d.push({type:`unsupported-setting`,setting:`seed`,details:"This model does not support the `seed` option through this provider."});let f=await t.parseProviderOptions({provider:`google`,providerOptions:c,schema:nt}),p=((n=this.config._internal)?.currentDate)?.call(n)??new Date,m={sampleCount:i};o!=null&&(m.aspectRatio=o),f&&Object.assign(m,f);let h={instances:[{prompt:r}],parameters:m},{responseHeaders:g,value:_}=await t.postJsonToApi({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:t.combineHeaders(await t.resolve(this.config.headers),l),body:h,failedResponseHandler:W,successfulResponseHandler:t.createJsonResponseHandler(tt),abortSignal:u,fetch:this.config.fetch});return{images:_.predictions.map(e=>e.bytesBase64Encoded),warnings:d??[],providerMetadata:{google:{images:_.predictions.map(e=>({}))}},response:{timestamp:p,modelId:this.modelId,headers:g}}}},tt=r.z.object({predictions:r.z.array(r.z.object({bytesBase64Encoded:r.z.string()})).default([])}),nt=r.z.object({personGeneration:r.z.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:r.z.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function rt(e={}){let n=t.withoutTrailingSlash(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,r=()=>t.withUserAgentSuffix({"x-goog-api-key":t.loadApiKey({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${Te}`),i=i=>new Ue(i,{provider:`google.generative-ai`,baseURL:n,headers:r,generateId:e.generateId??t.generateId,supportedUrls:()=>({"*":[RegExp(`^${n}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),a=t=>new Oe(t,{provider:`google.generative-ai`,baseURL:n,headers:r,fetch:e.fetch}),o=(t,i={})=>new et(t,i,{provider:`google.generative-ai`,baseURL:n,headers:r,fetch:e.fetch}),s=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return i(e)};return s.languageModel=i,s.chat=i,s.generativeAI=i,s.embedding=a,s.textEmbedding=a,s.textEmbeddingModel=a,s.image=o,s.imageModel=o,s.tools=$e,s}var it=rt(),at=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()})}),ot=t.createJsonErrorResponseHandler({errorSchema:at,errorToMessage:e=>e.error.message});function st({prompt:e,systemMessageMode:n=`system`}){let r=[],i=[];for(let{role:a,content:o}of e)switch(a){case`system`:switch(n){case`system`:r.push({role:`system`,content:o});break;case`developer`:r.push({role:`developer`,content:o});break;case`remove`:i.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`:if(o.length===1&&o[0].type===`text`){r.push({role:`user`,content:o[0].text});break}r.push({role:`user`,content:o.map((e,n)=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let n=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${n};base64,${t.convertToBase64(e.data)}`,detail:e.providerOptions?.openai?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:t.convertToBase64(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:t.convertToBase64(e.data),format:`mp3`}};default:throw new t.UnsupportedFunctionalityError({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`PDF file parts with URLs`});return{type:`file`,file:typeof e.data==`string`&&e.data.startsWith(`file-`)?{file_id:e.data}:{filename:e.filename??`part-${n}.pdf`,file_data:`data:application/pdf;base64,${t.convertToBase64(e.data)}`}}}else throw new t.UnsupportedFunctionalityError({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of o)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}r.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of o){let t=e.output,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}r.push({role:`tool`,tool_call_id:e.toolCallId,content:n})}break;default:{let e=a;throw Error(`Unsupported role: ${e}`)}}return{messages:r,warnings:i}}function ct({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 lt(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 ut=r.z.object({logitBias:r.z.record(r.z.coerce.number(),r.z.number()).optional(),logprobs:r.z.union([r.z.boolean(),r.z.number()]).optional(),parallelToolCalls:r.z.boolean().optional(),user:r.z.string().optional(),reasoningEffort:r.z.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:r.z.number().optional(),store:r.z.boolean().optional(),metadata:r.z.record(r.z.string().max(64),r.z.string().max(512)).optional(),prediction:r.z.record(r.z.string(),r.z.any()).optional(),structuredOutputs:r.z.boolean().optional(),serviceTier:r.z.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:r.z.boolean().optional(),textVerbosity:r.z.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:r.z.string().optional(),safetyIdentifier:r.z.string().optional()});function dt({tools:e,toolChoice:n,structuredOutputs:r,strictJsonSchema:i}){e=e?.length?e:void 0;let a=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};let o=[];for(let t of e)switch(t.type){case`function`:o.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:r?i:void 0}});break;default:a.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:void 0,toolWarnings:a};let s=n.type;switch(s){case`auto`:case`none`:case`required`:return{tools:o,toolChoice:s,toolWarnings:a};case`tool`:return{tools:o,toolChoice:{type:`function`,function:{name:n.toolName}},toolWarnings:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var ft=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:n,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,providerOptions:p}){let m=[],h=await t.parseProviderOptions({provider:`openai`,providerOptions:p,schema:ut})??{},g=h.structuredOutputs??!0;a!=null&&m.push({type:`unsupported-setting`,setting:`topK`}),l?.type===`json`&&l.schema!=null&&!g&&m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is only supported with structuredOutputs`});let{messages:_,warnings:v}=st({prompt:e,systemMessageMode:yt(this.modelId)});m.push(...v);let y=h.strictJsonSchema??!1,b={model:this.modelId,logit_bias:h.logitBias,logprobs:h.logprobs===!0||typeof h.logprobs==`number`?!0:void 0,top_logprobs:typeof h.logprobs==`number`?h.logprobs:typeof h.logprobs==`boolean`&&h.logprobs?0:void 0,user:h.user,parallel_tool_calls:h.parallelToolCalls,max_tokens:n,temperature:r,top_p:i,frequency_penalty:o,presence_penalty:s,response_format:l?.type===`json`?g&&l.schema!=null?{type:`json_schema`,json_schema:{schema:l.schema,strict:y,name:l.name??`response`,description:l.description}}:{type:`json_object`}:void 0,stop:c,seed:u,verbosity:h.textVerbosity,max_completion_tokens:h.maxCompletionTokens,store:h.store,metadata:h.metadata,prediction:h.prediction,reasoning_effort:h.reasoningEffort,service_tier:h.serviceTier,prompt_cache_key:h.promptCacheKey,safety_identifier:h.safetyIdentifier,messages:_};gt(this.modelId)?(b.temperature!=null&&(b.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),b.top_p!=null&&(b.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`})),b.frequency_penalty!=null&&(b.frequency_penalty=void 0,m.push({type:`unsupported-setting`,setting:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),b.presence_penalty!=null&&(b.presence_penalty=void 0,m.push({type:`unsupported-setting`,setting:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),b.logit_bias!=null&&(b.logit_bias=void 0,m.push({type:`other`,message:`logitBias is not supported for reasoning models`})),b.logprobs!=null&&(b.logprobs=void 0,m.push({type:`other`,message:`logprobs is not supported for reasoning models`})),b.top_logprobs!=null&&(b.top_logprobs=void 0,m.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),b.max_tokens!=null&&(b.max_completion_tokens??=b.max_tokens,b.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&b.temperature!=null&&(b.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),h.serviceTier===`flex`&&!_t(this.modelId)&&(m.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),b.service_tier=void 0),h.serviceTier===`priority`&&!vt(this.modelId)&&(m.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`}),b.service_tier=void 0);let{tools:x,toolChoice:S,toolWarnings:C}=dt({tools:d,toolChoice:f,structuredOutputs:g,strictJsonSchema:y});return{args:{...b,tools:x,tool_choice:S},warnings:[...m,...C]}}async doGenerate(e){let{args:n,warnings:r}=await this.getArgs(e),{responseHeaders:i,value:a,rawValue:o}=await t.postJsonToApi({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:t.combineHeaders(this.config.headers(),e.headers),body:n,failedResponseHandler:ot,successfulResponseHandler:t.createJsonResponseHandler(mt),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=a.choices[0],c=[],l=s.message.content;l!=null&&l.length>0&&c.push({type:`text`,text:l});for(let e of s.message.tool_calls??[])c.push({type:`tool-call`,toolCallId:e.id??t.generateId(),toolName:e.function.name,input:e.function.arguments});for(let e of s.message.annotations??[])c.push({type:`source`,sourceType:`url`,id:t.generateId(),url:e.url,title:e.title});let u=a.usage?.completion_tokens_details,d=a.usage?.prompt_tokens_details,f={openai:{}};return u?.accepted_prediction_tokens!=null&&(f.openai.acceptedPredictionTokens=u?.accepted_prediction_tokens),u?.rejected_prediction_tokens!=null&&(f.openai.rejectedPredictionTokens=u?.rejected_prediction_tokens),s.logprobs?.content!=null&&(f.openai.logprobs=s.logprobs.content),{content:c,finishReason:lt(s.finish_reason),usage:{inputTokens:a.usage?.prompt_tokens??void 0,outputTokens:a.usage?.completion_tokens??void 0,totalTokens:a.usage?.total_tokens??void 0,reasoningTokens:u?.reasoning_tokens??void 0,cachedInputTokens:d?.cached_tokens??void 0},request:{body:n},response:{...ct(a),headers:i,body:o},warnings:r,providerMetadata:f}}async doStream(e){let{args:n,warnings:r}=await this.getArgs(e),i={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:a,value:o}=await t.postJsonToApi({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:t.combineHeaders(this.config.headers(),e.headers),body:i,failedResponseHandler:ot,successfulResponseHandler:t.createEventSourceResponseHandler(ht),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[],c=`unknown`,l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=!0,d=!1,f={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(n,r){if(e.includeRawChunks&&r.enqueue({type:`raw`,rawValue:n.rawValue}),!n.success){c=`error`,r.enqueue({type:`error`,error:n.error});return}let i=n.value;if(`error`in i){c=`error`,r.enqueue({type:`error`,error:i.error});return}u&&(u=!1,r.enqueue({type:`response-metadata`,...ct(i)})),i.usage!=null&&(l.inputTokens=i.usage.prompt_tokens??void 0,l.outputTokens=i.usage.completion_tokens??void 0,l.totalTokens=i.usage.total_tokens??void 0,l.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0,l.cachedInputTokens=i.usage.prompt_tokens_details?.cached_tokens??void 0,i.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(f.openai.acceptedPredictionTokens=i.usage.completion_tokens_details?.accepted_prediction_tokens),i.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(f.openai.rejectedPredictionTokens=i.usage.completion_tokens_details?.rejected_prediction_tokens));let a=i.choices[0];if(a?.finish_reason!=null&&(c=lt(a.finish_reason)),a?.logprobs?.content!=null&&(f.openai.logprobs=a.logprobs.content),a?.delta==null)return;let o=a.delta;if(o.content!=null&&(d||=(r.enqueue({type:`text-start`,id:`0`}),!0),r.enqueue({type:`text-delta`,id:`0`,delta:o.content})),o.tool_calls!=null)for(let e of o.tool_calls){let n=e.index;if(s[n]==null){if(e.type!==`function`)throw new t.InvalidResponseDataError({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new t.InvalidResponseDataError({data:e,message:`Expected 'id' to be a string.`});if(e.function?.name==null)throw new t.InvalidResponseDataError({data:e,message:`Expected 'function.name' to be a string.`});r.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),s[n]={id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments??``},hasFinished:!1};let i=s[n];i.function?.name!=null&&i.function?.arguments!=null&&(i.function.arguments.length>0&&r.enqueue({type:`tool-input-delta`,id:i.id,delta:i.function.arguments}),t.isParsableJson(i.function.arguments)&&(r.enqueue({type:`tool-input-end`,id:i.id}),r.enqueue({type:`tool-call`,toolCallId:i.id??t.generateId(),toolName:i.function.name,input:i.function.arguments}),i.hasFinished=!0));continue}let i=s[n];i.hasFinished||(e.function?.arguments!=null&&(i.function.arguments+=e.function?.arguments??``),r.enqueue({type:`tool-input-delta`,id:i.id,delta:e.function.arguments??``}),i.function?.name!=null&&i.function?.arguments!=null&&t.isParsableJson(i.function.arguments)&&(r.enqueue({type:`tool-input-end`,id:i.id}),r.enqueue({type:`tool-call`,toolCallId:i.id??t.generateId(),toolName:i.function.name,input:i.function.arguments}),i.hasFinished=!0))}if(o.annotations!=null)for(let e of o.annotations)r.enqueue({type:`source`,sourceType:`url`,id:t.generateId(),url:e.url,title:e.title})},flush(e){d&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:c,usage:l,...f==null?{}:{providerMetadata:f}})}})),request:{body:i},response:{headers:a}}}},pt=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(),mt=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(),tool_calls:r.z.array(r.z.object({id:r.z.string().nullish(),type:r.z.literal(`function`),function:r.z.object({name:r.z.string(),arguments:r.z.string()})})).nullish(),annotations:r.z.array(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()})).nullish()}),index:r.z.number(),logprobs:r.z.object({content: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()}))})).nullish()}).nullish(),finish_reason:r.z.string().nullish()})),usage:pt}),ht=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({delta:r.z.object({role:r.z.enum([`assistant`]).nullish(),content:r.z.string().nullish(),tool_calls:r.z.array(r.z.object({index:r.z.number(),id:r.z.string().nullish(),type:r.z.literal(`function`).nullish(),function:r.z.object({name:r.z.string().nullish(),arguments:r.z.string().nullish()})})).nullish(),annotations:r.z.array(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()})).nullish()}).nullish(),logprobs:r.z.object({content: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()}))})).nullish()}).nullish(),finish_reason:r.z.string().nullish(),index:r.z.number()})),usage:pt}),at]);function gt(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function _t(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function vt(e){return 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`)}function yt(e){return gt(e)?bt[e]?.systemMessageMode??`developer`:`system`}var bt={"o1-mini":{systemMessageMode:`remove`},"o1-mini-2024-09-12":{systemMessageMode:`remove`},"o1-preview":{systemMessageMode:`remove`},"o1-preview-2024-09-12":{systemMessageMode:`remove`},o3:{systemMessageMode:`developer`},"o3-2025-04-16":{systemMessageMode:`developer`},"o3-mini":{systemMessageMode:`developer`},"o3-mini-2025-01-31":{systemMessageMode:`developer`},"o4-mini":{systemMessageMode:`developer`},"o4-mini-2025-04-16":{systemMessageMode:`developer`}};function xt({prompt:e,user:n=`user`,assistant:r=`assistant`}){let i=``;e[0].role===`system`&&(i+=`${e[0].content}
|
|
5
|
+
`})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function bn(e){return e.includes(`/`)?e:`models/${e}`}var xn=r.z.object({responseModalities:r.z.array(r.z.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:r.z.object({thinkingBudget:r.z.number().optional(),includeThoughts:r.z.boolean().optional()}).optional(),cachedContent:r.z.string().optional(),structuredOutputs:r.z.boolean().optional(),safetySettings:r.z.array(r.z.object({category:r.z.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:r.z.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:r.z.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:r.z.boolean().optional(),labels:r.z.record(r.z.string(),r.z.string()).optional()});function Sn({tools:e,toolChoice:n,modelId:r}){e=e?.length?e:void 0;let i=[],a=r.includes(`gemini-2`),o=r.includes(`gemini-1.5-flash`)&&!r.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:i};let s=e.some(e=>e.type===`function`),c=e.some(e=>e.type===`provider-defined`);if(s&&c&&i.push({type:`unsupported-tool`,tool:e.find(e=>e.type===`function`),details:`Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both.`}),c){let t={};return e.filter(e=>e.type===`provider-defined`).forEach(e=>{switch(e.id){case`google.google_search`:a?t.googleSearch={}:o?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:a?t.urlContext={}:i.push({type:`unsupported-tool`,tool:e,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:a?t.codeExecution={}:i.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:i.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:i}}let l=[];for(let t of e)switch(t.type){case`function`:l.push({name:t.name,description:t.description??``,parameters:_n(t.inputSchema)});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:{functionDeclarations:l},toolConfig:void 0,toolWarnings:i};let u=n.type;switch(u){case`auto`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:i};case`none`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:i};case`required`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:i};case`tool`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[n.toolName]}},toolWarnings:i};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${u}`})}}function Cn({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`FINISH_REASON_UNSPECIFIED`:case`OTHER`:return`other`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`unknown`}}var wn=r.z.object({web:r.z.object({uri:r.z.string(),title:r.z.string()}).nullish(),retrievedContext:r.z.object({uri:r.z.string(),title:r.z.string()}).nullish()}),Tn=r.z.object({webSearchQueries:r.z.array(r.z.string()).nullish(),retrievalQueries:r.z.array(r.z.string()).nullish(),searchEntryPoint:r.z.object({renderedContent:r.z.string()}).nullish(),groundingChunks:r.z.array(wn).nullish(),groundingSupports:r.z.array(r.z.object({segment:r.z.object({startIndex:r.z.number().nullish(),endIndex:r.z.number().nullish(),text:r.z.string().nullish()}),segment_text:r.z.string().nullish(),groundingChunkIndices:r.z.array(r.z.number()).nullish(),supportChunkIndices:r.z.array(r.z.number()).nullish(),confidenceScores:r.z.array(r.z.number()).nullish(),confidenceScore:r.z.array(r.z.number()).nullish()})).nullish(),retrievalMetadata:r.z.union([r.z.object({webDynamicRetrievalScore:r.z.number()}),r.z.object({})]).nullish()}),En=Xt({id:`google.google_search`,name:`google_search`,inputSchema:r.z.object({mode:r.z.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:r.z.number().default(1)})}),Dn=r.z.object({retrievedUrl:r.z.string(),urlRetrievalStatus:r.z.string()}),On=r.z.object({urlMetadata:r.z.array(Dn)}),kn=Xt({id:`google.url_context`,name:`url_context`,inputSchema:r.z.object({})}),An=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??wt}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await Gt({provider:`google`,providerOptions:f,schema:xn});m?.thinkingConfig?.includeThoughts===!0&&!this.config.provider.startsWith(`google.vertex.`)&&p.push({type:`other`,message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let h=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:g,systemInstruction:_}=yn(e,{isGemmaModel:h}),{tools:v,toolConfig:y,toolWarnings:b}=Sn({tools:u,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(m?.structuredOutputs??!0)?_n(c.schema):void 0,...m?.audioTimestamp&&{audioTimestamp:m.audioTimestamp},responseModalities:m?.responseModalities,thinkingConfig:m?.thinkingConfig},contents:g,systemInstruction:h?void 0:_,safetySettings:m?.safetySettings,tools:v,toolConfig:y,cachedContent:m?.cachedContent,labels:m?.labels},warnings:[...p,...b]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=vt(await Qt(this.config.headers),e.headers),{responseHeaders:a,value:o,rawValue:s}=await qt({url:`${this.config.baseURL}/${bn(this.modelId)}:generateContent`,headers:i,body:t,failedResponseHandler:fn,successfulResponseHandler:tn(Ln),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=o.candidates[0],l=[],u=c.content?.parts??[],d=o.usageMetadata,f;for(let e of u)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();f=t,l.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else `codeExecutionResult`in e&&e.codeExecutionResult?(l.push({type:`tool-result`,toolCallId:f,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output},providerExecuted:!0}),f=void 0):`text`in e&&e.text!=null&&e.text.length>0?l.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`functionCall`in e?l.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`inlineData`in e&&l.push({type:`file`,data:e.inlineData.data,mediaType:e.inlineData.mimeType});let p=Nn({groundingMetadata:c.groundingMetadata,generateId:this.config.generateId})??[];for(let e of p)l.push(e);return{content:l,finishReason:Cn({finishReason:c.finishReason,hasToolCalls:l.some(e=>e.type===`tool-call`)}),usage:{inputTokens:d?.promptTokenCount??void 0,outputTokens:d?.candidatesTokenCount??void 0,totalTokens:d?.totalTokenCount??void 0,reasoningTokens:d?.thoughtsTokenCount??void 0,cachedInputTokens:d?.cachedContentTokenCount??void 0},warnings:n,providerMetadata:{google:{promptFeedback:o.promptFeedback??null,groundingMetadata:c.groundingMetadata??null,urlContextMetadata:c.urlContextMetadata??null,safetyRatings:c.safetyRatings??null,usageMetadata:d??null}},request:{body:r},response:{headers:a,body:s}}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=vt(await Qt(this.config.headers),e.headers),{responseHeaders:a,value:o}=await qt({url:`${this.config.baseURL}/${bn(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:fn,successfulResponseHandler:en(Rn),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l,u=this.config.generateId,d=!1,f=null,p=null,m=0,h=new Set,g;return{stream:o.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 r=t.value,i=r.usageMetadata;i!=null&&(c.inputTokens=i.promptTokenCount??void 0,c.outputTokens=i.candidatesTokenCount??void 0,c.totalTokens=i.totalTokenCount??void 0,c.reasoningTokens=i.thoughtsTokenCount??void 0,c.cachedInputTokens=i.cachedContentTokenCount??void 0);let a=r.candidates?.[0];if(a==null)return;let o=a.content,_=Nn({groundingMetadata:a.groundingMetadata,generateId:u});if(_!=null)for(let e of _)e.sourceType===`url`&&!h.has(e.url)&&(h.add(e.url),n.enqueue(e));if(o!=null){let e=o.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=u();g=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0}),d=!0}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=g;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else `text`in t&&t.text!=null&&t.text.length>0&&(t.thought===!0?(f!==null&&(n.enqueue({type:`text-end`,id:f}),f=null),p===null&&(p=String(m++),n.enqueue({type:`reasoning-start`,id:p,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`reasoning-delta`,id:p,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})):(p!==null&&(n.enqueue({type:`reasoning-end`,id:p}),p=null),f===null&&(f=String(m++),n.enqueue({type:`text-start`,id:f,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`text-delta`,id:f,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})));let t=Mn(o.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=jn({parts:o.parts,generateId:u});if(r!=null)for(let e of r)n.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.args,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,providerMetadata:e.providerMetadata}),d=!0}a.finishReason!=null&&(s=Cn({finishReason:a.finishReason,hasToolCalls:d}),l={google:{promptFeedback:r.promptFeedback??null,groundingMetadata:a.groundingMetadata??null,urlContextMetadata:a.urlContextMetadata??null,safetyRatings:a.safetyRatings??null}},i!=null&&(l.google.usageMetadata=i))},flush(e){f!==null&&e.enqueue({type:`text-end`,id:f}),p!==null&&e.enqueue({type:`reasoning-end`,id:p}),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:l})}})),response:{headers:a},request:{body:r}}}};function jn({parts:e,generateId:t}){let n=e?.filter(e=>`functionCall`in e);return n==null||n.length===0?void 0:n.map(e=>({type:`tool-call`,toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}function Mn(e){return e?.filter(e=>`inlineData`in e)}function Nn({groundingMetadata:e,generateId:t}){return(e?.groundingChunks)?.filter(e=>e.web!=null).map(e=>({type:`source`,sourceType:`url`,id:t(),url:e.web.uri,title:e.web.title}))}var Pn=r.z.object({parts:r.z.array(r.z.union([r.z.object({functionCall:r.z.object({name:r.z.string(),args:r.z.unknown()}),thoughtSignature:r.z.string().nullish()}),r.z.object({inlineData:r.z.object({mimeType:r.z.string(),data:r.z.string()})}),r.z.object({executableCode:r.z.object({language:r.z.string(),code:r.z.string()}).nullish(),codeExecutionResult:r.z.object({outcome:r.z.string(),output:r.z.string()}).nullish(),text:r.z.string().nullish(),thought:r.z.boolean().nullish(),thoughtSignature:r.z.string().nullish()})])).nullish()}),Fn=r.z.object({category:r.z.string().nullish(),probability:r.z.string().nullish(),probabilityScore:r.z.number().nullish(),severity:r.z.string().nullish(),severityScore:r.z.number().nullish(),blocked:r.z.boolean().nullish()}),In=r.z.object({cachedContentTokenCount:r.z.number().nullish(),thoughtsTokenCount:r.z.number().nullish(),promptTokenCount:r.z.number().nullish(),candidatesTokenCount:r.z.number().nullish(),totalTokenCount:r.z.number().nullish()}),Ln=r.z.object({candidates:r.z.array(r.z.object({content:Pn.nullish().or(r.z.object({}).strict()),finishReason:r.z.string().nullish(),safetyRatings:r.z.array(Fn).nullish(),groundingMetadata:Tn.nullish(),urlContextMetadata:On.nullish()})),usageMetadata:In.nullish(),promptFeedback:r.z.object({blockReason:r.z.string().nullish(),safetyRatings:r.z.array(Fn).nullish()}).nullish()}),Rn=r.z.object({candidates:r.z.array(r.z.object({content:Pn.nullish(),finishReason:r.z.string().nullish(),safetyRatings:r.z.array(Fn).nullish(),groundingMetadata:Tn.nullish(),urlContextMetadata:On.nullish()})).nullish(),usageMetadata:In.nullish(),promptFeedback:r.z.object({blockReason:r.z.string().nullish(),safetyRatings:r.z.array(Fn).nullish()}).nullish()}),zn=Zt({id:`google.code_execution`,name:`code_execution`,inputSchema:r.z.object({language:r.z.string().describe(`The programming language of the code.`),code:r.z.string().describe(`The code to be executed.`)}),outputSchema:r.z.object({outcome:r.z.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:r.z.string().describe(`The output from the code execution.`)})}),Bn={googleSearch:En,urlContext:kn,codeExecution:zn},Vn=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v2`}get maxImagesPerCall(){return this.settings.maxImagesPerCall??4}get provider(){return this.config.provider}async doGenerate(e){var t;let{prompt:n,n:r=1,size:i=`1024x1024`,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l}=e,u=[];i!=null&&u.push({type:`unsupported-setting`,setting:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&u.push({type:`unsupported-setting`,setting:`seed`,details:"This model does not support the `seed` option through this provider."});let d=await Gt({provider:`google`,providerOptions:s,schema:Un}),f=((t=this.config._internal)?.currentDate)?.call(t)??new Date,p={sampleCount:r};a!=null&&(p.aspectRatio=a),d&&Object.assign(p,d);let m={instances:[{prompt:n}],parameters:p},{responseHeaders:h,value:g}=await qt({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:vt(await Qt(this.config.headers),c),body:m,failedResponseHandler:fn,successfulResponseHandler:tn(Hn),abortSignal:l,fetch:this.config.fetch});return{images:g.predictions.map(e=>e.bytesBase64Encoded),warnings:u??[],providerMetadata:{google:{images:g.predictions.map(e=>({}))}},response:{timestamp:f,modelId:this.modelId,headers:h}}}},Hn=r.z.object({predictions:r.z.array(r.z.object({bytesBase64Encoded:r.z.string()})).default([])}),Un=r.z.object({personGeneration:r.z.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:r.z.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function Wn(e={}){let t=ln(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=()=>St({"x-goog-api-key":kt({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${un}`),r=r=>new An(r,{provider:`google.generative-ai`,baseURL:t,headers:n,generateId:e.generateId??wt,supportedUrls:()=>({"*":[RegExp(`^${t}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch}),i=r=>new mn(r,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),a=(r,i={})=>new Vn(r,i,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),o=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return r(e)};return o.languageModel=r,o.chat=r,o.generativeAI=r,o.embedding=i,o.textEmbedding=i,o.textEmbeddingModel=i,o.image=a,o.imageModel=a,o.tools=Bn,o}var Gn=Wn();function Kn(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function qn(e){return Object.fromEntries([...e.headers])}function Jn(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 Yn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Xn(e,...t){let n=Yn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Zn=({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()}`},Qn=Zn();function $n(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var er=[`fetch failed`,`failed to fetch`];function tr({error:e,url:n,requestBodyValues:r}){if($n(e))return e;if(e instanceof TypeError&&er.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 nr=`3.0.10`;function rr({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}function ir({settingValue:e,environmentVariableName:t}){if(typeof e==`string`||!(e!=null||typeof process>`u`)&&(e=process.env[t],!(e==null||typeof e!=`string`)))return e}function ar(e){let[t,n=``]=e.toLowerCase().split(`/`);return{mpeg:`mp3`,"x-wav":`wav`,opus:`ogg`,mp4:`m4a`,"x-m4a":`m4a`}[n]??n}var or=/"__proto__"\s*:/,sr=/"constructor"\s*:/;function cr(e){let t=JSON.parse(e);return typeof t!=`object`||!t||or.test(e)===!1&&sr.test(e)===!1?t:lr(t)}function lr(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 ur(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return cr(e)}finally{Error.stackTraceLimit=t}}var dr=Symbol.for(`vercel.ai.validator`);function fr(e){return{[dr]:!0,validate:e}}function pr(e){return typeof e==`object`&&!!e&&dr in e&&e[dr]===!0&&`validate`in e}function mr(e){return pr(e)?e:hr(e)}function hr(e){return fr(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 gr({value:e,schema:n}){let r=await _r({value:e,schema:n});if(!r.success)throw t.TypeValidationError.wrap({value:e,cause:r.error});return r.value}async function _r({value:e,schema:n}){let r=mr(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 vr({text:e,schema:n}){try{let t=ur(e);return n==null?t:gr({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 yr({text:e,schema:n}){try{let t=ur(e);return n==null?{success:!0,value:t,rawValue:t}:await _r({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 br(e){try{return ur(e),!0}catch{return!1}}function xr({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 yr({text:e,schema:n}))}}))}async function Sr({provider:e,providerOptions:n,schema:r}){if(n?.[e]==null)return;let i=await _r({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 Cr=()=>globalThis.fetch,wr=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Er({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Tr=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Er({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Er=async({url:e,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=Cr()})=>{try{let c=await s(e,{method:`POST`,headers:Xn(n,`ai-sdk/provider-utils/${nr}`,Jn()),body:r.content,signal:o}),l=qn(c);if(!c.ok){let n;try{n=await a({response:c,url:e,requestBodyValues:r.values})}catch(n){throw $n(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&&($n(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 tr({error:t,url:e,requestBodyValues:r.values})}};function Dr(e){return e}function Or({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Dr({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function kr({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Dr({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}var Ar=({errorSchema:e,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=qn(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 vr({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)})}}},jr=e=>async({response:n})=>{let r=qn(n);if(n.body==null)throw new t.EmptyResponseBodyError({});return{responseHeaders:r,value:xr({stream:n.body,schema:e})}},Mr=e=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await yr({text:a,schema:e}),s=qn(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}},Nr=()=>async({response:e,url:n,requestBodyValues:r})=>{let i=qn(e);if(!e.body)throw new t.APICallError({message:`Response body is empty`,url:n,requestBodyValues:r,statusCode:e.status,responseHeaders:i,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:i,value:new Uint8Array(t)}}catch(a){throw new t.APICallError({message:`Failed to read response as array buffer`,url:n,requestBodyValues:r,statusCode:e.status,responseHeaders:i,responseBody:void 0,cause:a})}},Pr=Symbol(`Let zodToJsonSchema decide on which parser to use`),Fr=Symbol.for(`vercel.ai.schema`),{btoa:Ir,atob:Lr}=globalThis;function Rr(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=Lr(t);return Uint8Array.from(n,e=>e.codePointAt(0))}function zr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Ir(t)}function Br(e){return e instanceof Uint8Array?zr(e):e}function Vr(e){return e?.replace(/\/$/,``)}var Hr=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()})}),Ur=Ar({errorSchema:Hr,errorToMessage:e=>e.error.message});function Wr({prompt:e,systemMessageMode:n=`system`}){let r=[],i=[];for(let{role:a,content:o}of e)switch(a){case`system`:switch(n){case`system`:r.push({role:`system`,content:o});break;case`developer`:r.push({role:`developer`,content:o});break;case`remove`:i.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`:if(o.length===1&&o[0].type===`text`){r.push({role:`user`,content:o[0].text});break}r.push({role:`user`,content:o.map((e,n)=>{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,${Br(e.data)}`,detail:e.providerOptions?.openai?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:Br(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:Br(e.data),format:`mp3`}};default:throw new t.UnsupportedFunctionalityError({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new t.UnsupportedFunctionalityError({functionality:`PDF file parts with URLs`});return{type:`file`,file:typeof e.data==`string`&&e.data.startsWith(`file-`)?{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 o)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}r.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of o){let t=e.output,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}r.push({role:`tool`,tool_call_id:e.toolCallId,content:n})}break;default:{let e=a;throw Error(`Unsupported role: ${e}`)}}return{messages:r,warnings:i}}function Gr({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 Kr(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 qr=r.z.object({logitBias:r.z.record(r.z.coerce.number(),r.z.number()).optional(),logprobs:r.z.union([r.z.boolean(),r.z.number()]).optional(),parallelToolCalls:r.z.boolean().optional(),user:r.z.string().optional(),reasoningEffort:r.z.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:r.z.number().optional(),store:r.z.boolean().optional(),metadata:r.z.record(r.z.string().max(64),r.z.string().max(512)).optional(),prediction:r.z.record(r.z.string(),r.z.any()).optional(),structuredOutputs:r.z.boolean().optional(),serviceTier:r.z.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:r.z.boolean().optional(),textVerbosity:r.z.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:r.z.string().optional(),safetyIdentifier:r.z.string().optional()});function Jr({tools:e,toolChoice:n,structuredOutputs:r,strictJsonSchema:i}){e=e?.length?e:void 0;let a=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};let o=[];for(let t of e)switch(t.type){case`function`:o.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:r?i:void 0}});break;default:a.push({type:`unsupported-tool`,tool:t});break}if(n==null)return{tools:o,toolChoice:void 0,toolWarnings:a};let s=n.type;switch(s){case`auto`:case`none`:case`required`:return{tools:o,toolChoice:s,toolWarnings:a};case`tool`:return{tools:o,toolChoice:{type:`function`,function:{name:n.toolName}},toolWarnings:a};default:throw new t.UnsupportedFunctionalityError({functionality:`tool choice type: ${s}`})}}var Yr=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,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await Sr({provider:`openai`,providerOptions:f,schema:qr})??{},h=m.structuredOutputs??!0;i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),c?.type===`json`&&c.schema!=null&&!h&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is only supported with structuredOutputs`});let{messages:g,warnings:_}=Wr({prompt:e,systemMessageMode:ni(this.modelId)});p.push(..._);let v=m.strictJsonSchema??!1,y={model:this.modelId,logit_bias:m.logitBias,logprobs:m.logprobs===!0||typeof m.logprobs==`number`?!0:void 0,top_logprobs:typeof m.logprobs==`number`?m.logprobs:typeof m.logprobs==`boolean`&&m.logprobs?0:void 0,user:m.user,parallel_tool_calls:m.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?h&&c.schema!=null?{type:`json_schema`,json_schema:{schema:c.schema,strict:v,name:c.name??`response`,description:c.description}}:{type:`json_object`}:void 0,stop:s,seed:l,verbosity:m.textVerbosity,max_completion_tokens:m.maxCompletionTokens,store:m.store,metadata:m.metadata,prediction:m.prediction,reasoning_effort:m.reasoningEffort,service_tier:m.serviceTier,prompt_cache_key:m.promptCacheKey,safety_identifier:m.safetyIdentifier,messages:g};$r(this.modelId)?(y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),y.top_p!=null&&(y.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`})),y.frequency_penalty!=null&&(y.frequency_penalty=void 0,p.push({type:`unsupported-setting`,setting:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),y.presence_penalty!=null&&(y.presence_penalty=void 0,p.push({type:`unsupported-setting`,setting:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),y.logit_bias!=null&&(y.logit_bias=void 0,p.push({type:`other`,message:`logitBias is not supported for reasoning models`})),y.logprobs!=null&&(y.logprobs=void 0,p.push({type:`other`,message:`logprobs is not supported for reasoning models`})),y.top_logprobs!=null&&(y.top_logprobs=void 0,p.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),y.max_tokens!=null&&(y.max_completion_tokens??=y.max_tokens,y.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),m.serviceTier===`flex`&&!ei(this.modelId)&&(p.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),y.service_tier=void 0),m.serviceTier===`priority`&&!ti(this.modelId)&&(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`}),y.service_tier=void 0);let{tools:b,toolChoice:x,toolWarnings:S}=Jr({tools:u,toolChoice:d,structuredOutputs:h,strictJsonSchema:v});return{args:{...y,tools:b,tool_choice:x},warnings:[...p,...S]}}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:`/chat/completions`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),body:t,failedResponseHandler:Ur,successfulResponseHandler:Mr(Zr),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=i.choices[0],s=[],c=o.message.content;c!=null&&c.length>0&&s.push({type:`text`,text:c});for(let e of o.message.tool_calls??[])s.push({type:`tool-call`,toolCallId:e.id??Qn(),toolName:e.function.name,input:e.function.arguments});for(let e of o.message.annotations??[])s.push({type:`source`,sourceType:`url`,id:Qn(),url:e.url,title:e.title});let l=i.usage?.completion_tokens_details,u=i.usage?.prompt_tokens_details,d={openai:{}};return l?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=l?.accepted_prediction_tokens),l?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=l?.rejected_prediction_tokens),o.logprobs?.content!=null&&(d.openai.logprobs=o.logprobs.content),{content:s,finishReason:Kr(o.finish_reason),usage:{inputTokens:i.usage?.prompt_tokens??void 0,outputTokens:i.usage?.completion_tokens??void 0,totalTokens:i.usage?.total_tokens??void 0,reasoningTokens:l?.reasoning_tokens??void 0,cachedInputTokens:u?.cached_tokens??void 0},request:{body:t},response:{...Gr(i),headers:r,body:a},warnings:n,providerMetadata:d}}async doStream(e){let{args:n,warnings:r}=await this.getArgs(e),i={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:a,value:o}=await wr({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:Kn(this.config.headers(),e.headers),body:i,failedResponseHandler:Ur,successfulResponseHandler:jr(Qr),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=[],c=`unknown`,l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=!0,d=!1,f={openai:{}};return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(n,r){if(e.includeRawChunks&&r.enqueue({type:`raw`,rawValue:n.rawValue}),!n.success){c=`error`,r.enqueue({type:`error`,error:n.error});return}let i=n.value;if(`error`in i){c=`error`,r.enqueue({type:`error`,error:i.error});return}u&&(u=!1,r.enqueue({type:`response-metadata`,...Gr(i)})),i.usage!=null&&(l.inputTokens=i.usage.prompt_tokens??void 0,l.outputTokens=i.usage.completion_tokens??void 0,l.totalTokens=i.usage.total_tokens??void 0,l.reasoningTokens=i.usage.completion_tokens_details?.reasoning_tokens??void 0,l.cachedInputTokens=i.usage.prompt_tokens_details?.cached_tokens??void 0,i.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(f.openai.acceptedPredictionTokens=i.usage.completion_tokens_details?.accepted_prediction_tokens),i.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(f.openai.rejectedPredictionTokens=i.usage.completion_tokens_details?.rejected_prediction_tokens));let a=i.choices[0];if(a?.finish_reason!=null&&(c=Kr(a.finish_reason)),a?.logprobs?.content!=null&&(f.openai.logprobs=a.logprobs.content),a?.delta==null)return;let o=a.delta;if(o.content!=null&&(d||=(r.enqueue({type:`text-start`,id:`0`}),!0),r.enqueue({type:`text-delta`,id:`0`,delta:o.content})),o.tool_calls!=null)for(let e of o.tool_calls){let n=e.index;if(s[n]==null){if(e.type!==`function`)throw new t.InvalidResponseDataError({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new t.InvalidResponseDataError({data:e,message:`Expected 'id' to be a string.`});if(e.function?.name==null)throw new t.InvalidResponseDataError({data:e,message:`Expected 'function.name' to be a string.`});r.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),s[n]={id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments??``},hasFinished:!1};let i=s[n];i.function?.name!=null&&i.function?.arguments!=null&&(i.function.arguments.length>0&&r.enqueue({type:`tool-input-delta`,id:i.id,delta:i.function.arguments}),br(i.function.arguments)&&(r.enqueue({type:`tool-input-end`,id:i.id}),r.enqueue({type:`tool-call`,toolCallId:i.id??Qn(),toolName:i.function.name,input:i.function.arguments}),i.hasFinished=!0));continue}let i=s[n];i.hasFinished||(e.function?.arguments!=null&&(i.function.arguments+=e.function?.arguments??``),r.enqueue({type:`tool-input-delta`,id:i.id,delta:e.function.arguments??``}),i.function?.name!=null&&i.function?.arguments!=null&&br(i.function.arguments)&&(r.enqueue({type:`tool-input-end`,id:i.id}),r.enqueue({type:`tool-call`,toolCallId:i.id??Qn(),toolName:i.function.name,input:i.function.arguments}),i.hasFinished=!0))}if(o.annotations!=null)for(let e of o.annotations)r.enqueue({type:`source`,sourceType:`url`,id:Qn(),url:e.url,title:e.title})},flush(e){d&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:c,usage:l,...f==null?{}:{providerMetadata:f}})}})),request:{body:i},response:{headers:a}}}},Xr=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(),Zr=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(),tool_calls:r.z.array(r.z.object({id:r.z.string().nullish(),type:r.z.literal(`function`),function:r.z.object({name:r.z.string(),arguments:r.z.string()})})).nullish(),annotations:r.z.array(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()})).nullish()}),index:r.z.number(),logprobs:r.z.object({content: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()}))})).nullish()}).nullish(),finish_reason:r.z.string().nullish()})),usage:Xr}),Qr=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({delta:r.z.object({role:r.z.enum([`assistant`]).nullish(),content:r.z.string().nullish(),tool_calls:r.z.array(r.z.object({index:r.z.number(),id:r.z.string().nullish(),type:r.z.literal(`function`).nullish(),function:r.z.object({name:r.z.string().nullish(),arguments:r.z.string().nullish()})})).nullish(),annotations:r.z.array(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()})).nullish()}).nullish(),logprobs:r.z.object({content: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()}))})).nullish()}).nullish(),finish_reason:r.z.string().nullish(),index:r.z.number()})),usage:Xr}),Hr]);function $r(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function ei(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function ti(e){return 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`)}function ni(e){return $r(e)?ri[e]?.systemMessageMode??`developer`:`system`}var ri={"o1-mini":{systemMessageMode:`remove`},"o1-mini-2024-09-12":{systemMessageMode:`remove`},"o1-preview":{systemMessageMode:`remove`},"o1-preview-2024-09-12":{systemMessageMode:`remove`},o3:{systemMessageMode:`developer`},"o3-2025-04-16":{systemMessageMode:`developer`},"o3-mini":{systemMessageMode:`developer`},"o3-mini-2025-01-31":{systemMessageMode:`developer`},"o4-mini":{systemMessageMode:`developer`},"o4-mini-2025-04-16":{systemMessageMode:`developer`}};function ii({prompt:e,user:n=`user`,assistant:r=`assistant`}){let i=``;e[0].role===`system`&&(i+=`${e[0].content}
|
|
6
6
|
|
|
7
7
|
`,e=e.slice(1));for(let{role:a,content:o}of e)switch(a){case`system`:throw new t.InvalidPromptError({message:"Unexpected system message in prompt: ${content}",prompt:e});case`user`:{let e=o.map(e=>{switch(e.type){case`text`:return e.text}}).filter(Boolean).join(``);i+=`${n}:
|
|
8
8
|
${e}
|
|
@@ -12,168 +12,167 @@ ${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 St({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 Ct(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 wt=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()}),Tt=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:n,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,tools:u,toolChoice:d,seed:f,providerOptions:p}){let m=[],h={...await t.parseProviderOptions({provider:`openai`,providerOptions:p,schema:wt}),...await t.parseProviderOptions({provider:this.providerOptionsName,providerOptions:p,schema:wt})};a!=null&&m.push({type:`unsupported-setting`,setting:`topK`}),u?.length&&m.push({type:`unsupported-setting`,setting:`tools`}),d!=null&&m.push({type:`unsupported-setting`,setting:`toolChoice`}),l!=null&&l.type!==`text`&&m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:g,stopSequences:_}=xt({prompt:e}),v=[..._??[],...c??[]];return{args:{model:this.modelId,echo:h.echo,logit_bias:h.logitBias,logprobs:h?.logprobs===!0?0:h?.logprobs===!1?void 0:h?.logprobs,suffix:h.suffix,user:h.user,max_tokens:n,temperature:r,top_p:i,frequency_penalty:o,presence_penalty:s,seed:f,prompt:g,stop:v.length>0?v:void 0},warnings:m}}async doGenerate(e){let{args:n,warnings:r}=await this.getArgs(e),{responseHeaders:i,value:a,rawValue:o}=await t.postJsonToApi({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:t.combineHeaders(this.config.headers(),e.headers),body:n,failedResponseHandler:ot,successfulResponseHandler:t.createJsonResponseHandler(Dt),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=a.choices[0],c={openai:{}};return s.logprobs!=null&&(c.openai.logprobs=s.logprobs),{content:[{type:`text`,text:s.text}],usage:{inputTokens:a.usage?.prompt_tokens,outputTokens:a.usage?.completion_tokens,totalTokens:a.usage?.total_tokens},finishReason:Ct(s.finish_reason),request:{body:n},response:{...St(a),headers:i,body:o},providerMetadata:c,warnings:r}}async doStream(e){let{args:n,warnings:r}=await this.getArgs(e),i={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:a,value:o}=await t.postJsonToApi({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:t.combineHeaders(this.config.headers(),e.headers),body:i,failedResponseHandler:ot,successfulResponseHandler:t.createEventSourceResponseHandler(Ot),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=!0;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){s=`error`,n.enqueue({type:`error`,error:r.error});return}u&&(u=!1,n.enqueue({type:`response-metadata`,...St(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(l.inputTokens=r.usage.prompt_tokens,l.outputTokens=r.usage.completion_tokens,l.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(s=Ct(i.finish_reason)),i?.logprobs!=null&&(c.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){u||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,providerMetadata:c,usage:l})}})),request:{body:i},response:{headers:a}}}},Et=r.z.object({prompt_tokens:r.z.number(),completion_tokens:r.z.number(),total_tokens:r.z.number()}),Dt=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:Et.nullish()}),Ot=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:Et.nullish()}),at]),kt=r.z.object({dimensions:r.z.number().optional(),user:r.z.string().optional()}),At=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 t.parseProviderOptions({provider:`openai`,providerOptions:i,schema:kt})??{},{responseHeaders:o,value:s,rawValue:c}=await t.postJsonToApi({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:t.combineHeaders(this.config.headers(),n),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:a.dimensions,user:a.user},failedResponseHandler:ot,successfulResponseHandler:t.createJsonResponseHandler(jt),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}}}},jt=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()}),Mt={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Nt=new Set([`gpt-image-1`]),Pt=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return Mt[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n,size:r,aspectRatio:i,seed:a,providerOptions:o,headers:s,abortSignal:c}){var l;let u=[];i!=null&&u.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),a!=null&&u.push({type:`unsupported-setting`,setting:`seed`});let d=((l=this.config._internal)?.currentDate)?.call(l)??new Date,{value:f,responseHeaders:p}=await t.postJsonToApi({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:t.combineHeaders(this.config.headers(),s),body:{model:this.modelId,prompt:e,n,size:r,...o.openai??{},...Nt.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:ot,successfulResponseHandler:t.createJsonResponseHandler(Ft),abortSignal:c,fetch:this.config.fetch});return{images:f.data.map(e=>e.b64_json),warnings:u,response:{timestamp:d,modelId:this.modelId,headers:p},providerMetadata:{openai:{images:f.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},Ft=r.z.object({data:r.z.array(r.z.object({b64_json:r.z.string(),revised_prompt:r.z.string().optional()}))}),It=r.z.object({code:r.z.string().nullish(),containerId:r.z.string()}),Lt=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()}),Rt=r.z.object({container:r.z.union([r.z.string(),r.z.object({fileIds:r.z.array(r.z.string()).optional()})]).optional()}),zt=t.createProviderDefinedToolFactoryWithOutputSchema({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:It,outputSchema:Lt}),Bt=(e={})=>zt(e),Vt=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()])}),Ht=r.z.object({type:r.z.enum([`and`,`or`]),filters:r.z.array(r.z.union([Vt,r.z.lazy(()=>Ht)]))}),Ut=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([Vt,Ht]).optional()}),Wt=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()}),Gt=t.createProviderDefinedToolFactoryWithOutputSchema({id:`openai.file_search`,name:`file_search`,inputSchema:r.z.object({}),outputSchema:Wt}),Kt=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(),qt=r.z.object({result:r.z.string()}),Jt=t.createProviderDefinedToolFactoryWithOutputSchema({id:`openai.image_generation`,name:`image_generation`,inputSchema:r.z.object({}),outputSchema:qt}),Yt=(e={})=>Jt(e),Xt=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()})}),Zt=r.z.object({output:r.z.string()}),Qt=t.createProviderDefinedToolFactoryWithOutputSchema({id:`openai.local_shell`,name:`local_shell`,inputSchema:Xt,outputSchema:Zt}),$t=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()}),en=t.createProviderDefinedToolFactory({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()})}),tn=(e={})=>en(e),nn=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()}),rn=t.createProviderDefinedToolFactory({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()})}),an={codeInterpreter:Bt,fileSearch:Gt,imageGeneration:Yt,localShell:Qt,webSearchPreview:rn,webSearch:tn};function on(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function sn({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 n=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&on(e.data,r)?{file_id:e.data}:{image_url:`data:${n};base64,${t.convertToBase64(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`&&on(e.data,r)?{file_id:e.data}:{filename:e.filename??`part-${n}.pdf`,file_data:`data:application/pdf;base64,${t.convertToBase64(e.data)}`}};else throw new t.UnsupportedFunctionalityError({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},n={};for(let r of l)switch(r.type){case`text`:o.push({role:`assistant`,content:[{type:`output_text`,text:r.text}],id:r.providerOptions?.openai?.itemId??void 0});break;case`tool-call`:if(n[r.toolCallId]=r,r.providerExecuted)break;if(a&&r.toolName===`local_shell`){let e=Xt.parse(r.input);o.push({type:`local_shell_call`,call_id:r.toolCallId,id:r.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:r.toolCallId,name:r.toolName,arguments:JSON.stringify(r.input),id:r.providerOptions?.openai?.itemId??void 0});break;case`tool-result`:i?o.push({type:`item_reference`,id:r.toolCallId}):s.push({type:`other`,message:`Results for OpenAI tool ${r.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let n=await t.parseProviderOptions({provider:`openai`,providerOptions:r.providerOptions,schema:cn}),a=n?.itemId;if(a!=null){let t=e[a];if(i)t===void 0&&(o.push({type:`item_reference`,id:a}),e[a]={type:`reasoning`,id:a,summary:[]});else{let i=[];r.text.length>0?i.push({type:`summary_text`,text:r.text}):t!==void 0&&s.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(r)}.`}),t===void 0?(e[a]={type:`reasoning`,id:a,encrypted_content:n?.reasoningEncryptedContent,summary:i},o.push(e[a])):t.summary.push(...i)}}else s.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(r)}.`});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:Zt.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 cn=r.z.object({itemId:r.z.string().nullish(),reasoningEncryptedContent:r.z.string().nullish()});function ln({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 un({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=Ut.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=nn.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=$t.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=Rt.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=Kt.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 dn=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()}),fn=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()}),pn=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()}),mn=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()})}),hn=r.z.object({type:r.z.literal(`image_generation_call`),id:r.z.string(),result:r.z.string()}),gn=20,_n=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()}))})),vn=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:n,stopSequences:r,topP:i,topK:a,presencePenalty:o,frequencyPenalty:s,seed:c,prompt:l,providerOptions:u,tools:d,toolChoice:f,responseFormat:p}){let m=[],h=qn(this.modelId);a!=null&&m.push({type:`unsupported-setting`,setting:`topK`}),c!=null&&m.push({type:`unsupported-setting`,setting:`seed`}),o!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),r!=null&&m.push({type:`unsupported-setting`,setting:`stopSequences`});let g=await t.parseProviderOptions({provider:`openai`,providerOptions:u,schema:Jn}),{input:_,warnings:v}=await sn({prompt:l,systemMessageMode:h.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:g?.store??!0,hasLocalShellTool:S(`openai.local_shell`)});m.push(...v);let y=g?.strictJsonSchema??!1,b=g?.include;function x(e){b=b==null?[e]:[...b,e]}function S(e){return d?.find(t=>t.type===`provider-defined`&&t.id===e)!=null}let C=typeof g?.logprobs==`number`?g?.logprobs:g?.logprobs===!0?gn:void 0;C&&x(`message.output_text.logprobs`);let w=d?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;w&&x(`web_search_call.action.sources`),S(`openai.code_interpreter`)&&x(`code_interpreter_call.outputs`);let T={model:this.modelId,input:_,temperature:n,top_p:i,max_output_tokens:e,...(p?.type===`json`||g?.textVerbosity)&&{text:{...p?.type===`json`&&{format:p.schema==null?{type:`json_object`}:{type:`json_schema`,strict:y,name:p.name??`response`,description:p.description,schema:p.schema}},...g?.textVerbosity&&{verbosity:g.textVerbosity}}},max_tool_calls:g?.maxToolCalls,metadata:g?.metadata,parallel_tool_calls:g?.parallelToolCalls,previous_response_id:g?.previousResponseId,store:g?.store,user:g?.user,instructions:g?.instructions,service_tier:g?.serviceTier,include:b,prompt_cache_key:g?.promptCacheKey,safety_identifier:g?.safetyIdentifier,top_logprobs:C,...h.isReasoningModel&&(g?.reasoningEffort!=null||g?.reasoningSummary!=null)&&{reasoning:{...g?.reasoningEffort!=null&&{effort:g.reasoningEffort},...g?.reasoningSummary!=null&&{summary:g.reasoningSummary}}},...h.requiredAutoTruncation&&{truncation:`auto`}};h.isReasoningModel?(T.temperature!=null&&(T.temperature=void 0,m.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),T.top_p!=null&&(T.top_p=void 0,m.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(g?.reasoningEffort!=null&&m.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),g?.reasoningSummary!=null&&m.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),g?.serviceTier===`flex`&&!h.supportsFlexProcessing&&(m.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete T.service_tier),g?.serviceTier===`priority`&&!h.supportsPriorityProcessing&&(m.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 T.service_tier);let{tools:E,toolChoice:D,toolWarnings:O}=un({tools:d,toolChoice:f,strictJsonSchema:y});return{webSearchToolName:w,args:{...T,tools:E,tool_choice:D},warnings:[...m,...O]}}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 t.postJsonToApi({url:c,headers:t.combineHeaders(this.config.headers(),e.headers),body:a,failedResponseHandler:ot,successfulResponseHandler:t.createJsonResponseHandler(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:_n.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`)})]))}))}),dn,fn,pn,hn,mn,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:yn})),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 r of u.output)switch(r.type){case`reasoning`:r.summary.length===0&&r.summary.push({type:`summary_text`,text:``});for(let e of r.summary)f.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:r.id,reasoningEncryptedContent:r.encrypted_content??null}}});break;case`image_generation_call`:f.push({type:`tool-call`,toolCallId:r.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:r.id,toolName:`image_generation`,result:{result:r.result},providerExecuted:!0});break;case`local_shell_call`:f.push({type:`tool-call`,toolCallId:r.call_id,toolName:`local_shell`,input:JSON.stringify({action:r.action}),providerMetadata:{openai:{itemId:r.id}}});break;case`message`:for(let a of r.content){e.providerOptions?.openai?.logprobs&&a.logprobs&&p.push(a.logprobs),f.push({type:`text`,text:a.text,providerMetadata:{openai:{itemId:r.id}}});for(let e of a.annotations)e.type===`url_citation`?f.push({type:`source`,sourceType:`url`,id:(n=this.config).generateId?.call(n)??t.generateId(),url:e.url,title:e.title}):e.type===`file_citation`&&f.push({type:`source`,sourceType:`document`,id:(i=this.config).generateId?.call(i)??t.generateId(),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:r.call_id,toolName:r.name,input:r.arguments,providerMetadata:{openai:{itemId:r.id}}});break;case`web_search_call`:f.push({type:`tool-call`,toolCallId:r.id,toolName:s??`web_search`,input:JSON.stringify({action:r.action}),providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:r.id,toolName:s??`web_search`,result:{status:r.status},providerExecuted:!0});break;case`computer_call`:f.push({type:`tool-call`,toolCallId:r.id,toolName:`computer_use`,input:``,providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:r.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:r.status||`completed`},providerExecuted:!0});break;case`file_search_call`:f.push({type:`tool-call`,toolCallId:r.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:r.id,toolName:`file_search`,result:{queries:r.queries,results:r.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:r.id,toolName:`code_interpreter`,input:JSON.stringify({code:r.code,containerId:r.container_id}),providerExecuted:!0}),f.push({type:`tool-result`,toolCallId:r.id,toolName:`code_interpreter`,result:{outputs:r.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:ln({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:n,warnings:r,webSearchToolName:i}=await this.getArgs(e),{responseHeaders:a,value:o}=await t.postJsonToApi({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:t.combineHeaders(this.config.headers(),e.headers),body:{...n,stream:!0},failedResponseHandler:ot,successfulResponseHandler:t.createEventSourceResponseHandler(Mn),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=this,c=`unknown`,l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=[],d=null,f={},p=!1,m={},h;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(n,r){var a,o,g;if(e.includeRawChunks&&r.enqueue({type:`raw`,rawValue:n.rawValue}),!n.success){c=`error`,r.enqueue({type:`error`,error:n.error});return}let _=n.value;if(Vn(_))_.item.type===`function_call`?(f[_.output_index]={toolName:_.item.name,toolCallId:_.item.call_id},r.enqueue({type:`tool-input-start`,id:_.item.call_id,toolName:_.item.name})):_.item.type===`web_search_call`?(f[_.output_index]={toolName:i??`web_search`,toolCallId:_.item.id},r.enqueue({type:`tool-input-start`,id:_.item.id,toolName:i??`web_search`})):_.item.type===`computer_call`?(f[_.output_index]={toolName:`computer_use`,toolCallId:_.item.id},r.enqueue({type:`tool-input-start`,id:_.item.id,toolName:`computer_use`})):_.item.type===`code_interpreter_call`?(f[_.output_index]={toolName:`code_interpreter`,toolCallId:_.item.id,codeInterpreter:{containerId:_.item.container_id}},r.enqueue({type:`tool-input-start`,id:_.item.id,toolName:`code_interpreter`}),r.enqueue({type:`tool-input-delta`,id:_.item.id,delta:`{"containerId":"${_.item.container_id}","code":"`})):_.item.type===`file_search_call`?r.enqueue({type:`tool-call`,toolCallId:_.item.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}):_.item.type===`image_generation_call`?r.enqueue({type:`tool-call`,toolCallId:_.item.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}):_.item.type===`message`?r.enqueue({type:`text-start`,id:_.item.id,providerMetadata:{openai:{itemId:_.item.id}}}):Hn(_)&&(m[_.item.id]={encryptedContent:_.item.encrypted_content,summaryParts:[0]},r.enqueue({type:`reasoning-start`,id:`${_.item.id}:0`,providerMetadata:{openai:{itemId:_.item.id,reasoningEncryptedContent:_.item.encrypted_content??null}}}));else if(Pn(_)){if(_.item.type===`function_call`)f[_.output_index]=void 0,p=!0,r.enqueue({type:`tool-input-end`,id:_.item.call_id}),r.enqueue({type:`tool-call`,toolCallId:_.item.call_id,toolName:_.item.name,input:_.item.arguments,providerMetadata:{openai:{itemId:_.item.id}}});else if(_.item.type===`web_search_call`)f[_.output_index]=void 0,r.enqueue({type:`tool-input-end`,id:_.item.id}),r.enqueue({type:`tool-call`,toolCallId:_.item.id,toolName:`web_search`,input:JSON.stringify({action:_.item.action}),providerExecuted:!0}),r.enqueue({type:`tool-result`,toolCallId:_.item.id,toolName:`web_search`,result:{status:_.item.status},providerExecuted:!0});else if(_.item.type===`computer_call`)f[_.output_index]=void 0,r.enqueue({type:`tool-input-end`,id:_.item.id}),r.enqueue({type:`tool-call`,toolCallId:_.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),r.enqueue({type:`tool-result`,toolCallId:_.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:_.item.status||`completed`},providerExecuted:!0});else if(_.item.type===`file_search_call`)f[_.output_index]=void 0,r.enqueue({type:`tool-result`,toolCallId:_.item.id,toolName:`file_search`,result:{queries:_.item.queries,results:_.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(_.item.type===`code_interpreter_call`)f[_.output_index]=void 0,r.enqueue({type:`tool-result`,toolCallId:_.item.id,toolName:`code_interpreter`,result:{outputs:_.item.outputs},providerExecuted:!0});else if(_.item.type===`image_generation_call`)r.enqueue({type:`tool-result`,toolCallId:_.item.id,toolName:`image_generation`,result:{result:_.item.result},providerExecuted:!0});else if(_.item.type===`local_shell_call`)f[_.output_index]=void 0,r.enqueue({type:`tool-call`,toolCallId:_.item.call_id,toolName:`local_shell`,input:JSON.stringify({action:{type:`exec`,command:_.item.action.command,timeoutMs:_.item.action.timeout_ms,user:_.item.action.user,workingDirectory:_.item.action.working_directory,env:_.item.action.env}}),providerMetadata:{openai:{itemId:_.item.id}}});else if(_.item.type===`message`)r.enqueue({type:`text-end`,id:_.item.id});else if(Fn(_)){let e=m[_.item.id];for(let t of e.summaryParts)r.enqueue({type:`reasoning-end`,id:`${_.item.id}:${t}`,providerMetadata:{openai:{itemId:_.item.id,reasoningEncryptedContent:_.item.encrypted_content??null}}});delete m[_.item.id]}}else if(Rn(_)){let e=f[_.output_index];e!=null&&r.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:_.delta})}else if(zn(_)){let e=f[_.output_index];e!=null&&r.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(_.delta).slice(1,-1)})}else if(Bn(_)){let e=f[_.output_index];e!=null&&(r.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),r.enqueue({type:`tool-input-end`,id:e.toolCallId}),r.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:`code_interpreter`,input:JSON.stringify({code:_.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else Ln(_)?(d=_.response.id,r.enqueue({type:`response-metadata`,id:_.response.id,timestamp:new Date(_.response.created_at*1e3),modelId:_.response.model})):Nn(_)?(r.enqueue({type:`text-delta`,id:_.item_id,delta:_.delta}),e.providerOptions?.openai?.logprobs&&_.logprobs&&u.push(_.logprobs)):Wn(_)?_.summary_index>0&&((a=m[_.item_id])==null||a.summaryParts.push(_.summary_index),r.enqueue({type:`reasoning-start`,id:`${_.item_id}:${_.summary_index}`,providerMetadata:{openai:{itemId:_.item_id,reasoningEncryptedContent:m[_.item_id]?.encryptedContent??null}}})):Gn(_)?r.enqueue({type:`reasoning-delta`,id:`${_.item_id}:${_.summary_index}`,delta:_.delta,providerMetadata:{openai:{itemId:_.item_id}}}):In(_)?(c=ln({finishReason:_.response.incomplete_details?.reason,hasFunctionCall:p}),l.inputTokens=_.response.usage.input_tokens,l.outputTokens=_.response.usage.output_tokens,l.totalTokens=_.response.usage.input_tokens+_.response.usage.output_tokens,l.reasoningTokens=_.response.usage.output_tokens_details?.reasoning_tokens??void 0,l.cachedInputTokens=_.response.usage.input_tokens_details?.cached_tokens??void 0,typeof _.response.service_tier==`string`&&(h=_.response.service_tier)):Un(_)?_.annotation.type===`url_citation`?r.enqueue({type:`source`,sourceType:`url`,id:(o=s.config).generateId?.call(o)??t.generateId(),url:_.annotation.url,title:_.annotation.title}):_.annotation.type===`file_citation`&&r.enqueue({type:`source`,sourceType:`document`,id:(g=s.config).generateId?.call(g)??t.generateId(),mediaType:`text/plain`,title:_.annotation.quote??_.annotation.filename??`Document`,filename:_.annotation.filename??_.annotation.file_id}):Kn(_)&&r.enqueue({type:`error`,error:_})},flush(e){let t={openai:{responseId:d}};u.length>0&&(t.openai.logprobs=u),h!==void 0&&(t.openai.serviceTier=h),e.enqueue({type:`finish`,finishReason:c,usage:l,providerMetadata:t})}})),request:{body:n},response:{headers:a}}}},yn=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()}),bn=r.z.object({type:r.z.literal(`response.output_text.delta`),item_id:r.z.string(),delta:r.z.string(),logprobs:_n.nullish()}),xn=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()}),Sn=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:yn,service_tier:r.z.string().nullish()})}),Cn=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()})}),wn=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()})])}),Tn=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`)}),pn,hn,dn,fn,mn,r.z.object({type:r.z.literal(`computer_call`),id:r.z.string(),status:r.z.literal(`completed`)})])}),En=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()}),Dn=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()}),On=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()}),kn=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()})])}),An=r.z.object({type:r.z.literal(`response.reasoning_summary_part.added`),item_id:r.z.string(),summary_index:r.z.number()}),jn=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()}),Mn=r.z.union([bn,Sn,Cn,wn,Tn,En,Dn,On,kn,An,jn,xn,r.z.object({type:r.z.string()}).loose()]);function Nn(e){return e.type===`response.output_text.delta`}function Pn(e){return e.type===`response.output_item.done`}function Fn(e){return Pn(e)&&e.item.type===`reasoning`}function In(e){return e.type===`response.completed`||e.type===`response.incomplete`}function Ln(e){return e.type===`response.created`}function Rn(e){return e.type===`response.function_call_arguments.delta`}function zn(e){return e.type===`response.code_interpreter_call_code.delta`}function Bn(e){return e.type===`response.code_interpreter_call_code.done`}function Vn(e){return e.type===`response.output_item.added`}function Hn(e){return Vn(e)&&e.item.type===`reasoning`}function Un(e){return e.type===`response.output_text.annotation.added`}function Wn(e){return e.type===`response.reasoning_summary_part.added`}function Gn(e){return e.type===`response.reasoning_summary_text.delta`}function Kn(e){return e.type===`error`}function qn(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 Jn=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(gn)]).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()}),Yn=r.z.object({instructions:r.z.string().nullish(),speed:r.z.number().min(.25).max(4).default(1).nullish()}),Xn=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:n=`alloy`,outputFormat:r=`mp3`,speed:i,instructions:a,language:o,providerOptions:s}){let c=[],l=await t.parseProviderOptions({provider:`openai`,providerOptions:s,schema:Yn}),u={model:this.modelId,input:e,voice:n,response_format:`mp3`,speed:i,instructions:a};if(r&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(r)?u.response_format=r:c.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){let e={};for(let t in e){let n=e[t];n!==void 0&&(u[t]=n)}}return o&&c.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${o}" was ignored.`}),{requestBody:u,warnings:c}}async doGenerate(e){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,{requestBody:i,warnings:a}=await this.getArgs(e),{value:o,responseHeaders:s,rawValue:c}=await t.postJsonToApi({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:t.combineHeaders(this.config.headers(),e.headers),body:i,failedResponseHandler:ot,successfulResponseHandler:t.createBinaryResponseHandler(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:o,warnings:a,request:{body:JSON.stringify(i)},response:{timestamp:r,modelId:this.modelId,headers:s,body:c}}}},Zn=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()}),Qn={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`},$n=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:n,providerOptions:r}){let i=[],a=await t.parseProviderOptions({provider:`openai`,providerOptions:r,schema:Zn}),o=new FormData,s=e instanceof Uint8Array?new Blob([e]):new Blob([t.convertBase64ToUint8Array(e)]);o.append(`model`,this.modelId);let c=t.mediaTypeToExtension(n);if(o.append(`file`,new File([s],`audio`,{type:n}),`audio.${c}`),a){let e={include:a.include,language:a.language,prompt:a.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:a.temperature,timestamp_granularities:a.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)o.append(`${t}[]`,String(e));else o.append(t,String(n))}return{formData:o,warnings:i}}async doGenerate(e){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,{formData:i,warnings:a}=await this.getArgs(e),{value:o,responseHeaders:s,rawValue:c}=await t.postFormDataToApi({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:t.combineHeaders(this.config.headers(),e.headers),formData:i,failedResponseHandler:ot,successfulResponseHandler:t.createJsonResponseHandler(er),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=o.language!=null&&o.language in Qn?Qn[o.language]:void 0;return{text:o.text,segments:o.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??o.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:l,durationInSeconds:o.duration??void 0,warnings:a,response:{timestamp:r,modelId:this.modelId,headers:s,body:c}}}},er=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()}),tr=`2.0.42`;function nr(e={}){let n=t.withoutTrailingSlash(t.loadOptionalSetting({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,r=e.name??`openai`,i=()=>t.withUserAgentSuffix({Authorization:`Bearer ${t.loadApiKey({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${tr}`),a=t=>new ft(t,{provider:`${r}.chat`,url:({path:e})=>`${n}${e}`,headers:i,fetch:e.fetch}),o=t=>new Tt(t,{provider:`${r}.completion`,url:({path:e})=>`${n}${e}`,headers:i,fetch:e.fetch}),s=t=>new At(t,{provider:`${r}.embedding`,url:({path:e})=>`${n}${e}`,headers:i,fetch:e.fetch}),c=t=>new Pt(t,{provider:`${r}.image`,url:({path:e})=>`${n}${e}`,headers:i,fetch:e.fetch}),l=t=>new $n(t,{provider:`${r}.transcription`,url:({path:e})=>`${n}${e}`,headers:i,fetch:e.fetch}),u=t=>new Xn(t,{provider:`${r}.speech`,url:({path:e})=>`${n}${e}`,headers:i,fetch:e.fetch}),d=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return f(e)},f=t=>new vn(t,{provider:`${r}.responses`,url:({path:e})=>`${n}${e}`,headers:i,fetch:e.fetch,fileIdPrefixes:[`file-`]}),p=function(e){return d(e)};return p.languageModel=d,p.chat=a,p.completion=o,p.responses=f,p.embedding=s,p.textEmbedding=s,p.textEmbeddingModel=s,p.image=c,p.imageModel=c,p.transcription=l,p.transcriptionModel=l,p.speech=u,p.speechModel=u,p.tools=an,p}var rr=nr(),ir=r.z.object({user:r.z.string().optional(),reasoningEffort:r.z.string().optional()}),ar={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},or=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(),sr=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:or}),cr=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()}),lr=r.z.object({prompt_tokens:r.z.number(),completion_tokens:r.z.number(),total_tokens:r.z.number()}),ur=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:lr.nullish()}),dr=r.z.object({dimensions:r.z.number().optional(),user:r.z.string().optional()}),fr=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()}),pr=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,size:r,aspectRatio:i,seed:a,providerOptions:o,headers:s,abortSignal:c}){var l;let u=[];i!=null&&u.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),a!=null&&u.push({type:`unsupported-setting`,setting:`seed`});let d=((l=this.config._internal)?.currentDate)?.call(l)??new Date,{value:f,responseHeaders:p}=await t.postJsonToApi({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:t.combineHeaders(this.config.headers(),s),body:{model:this.modelId,prompt:e,n,size:r,...o.openai??{},response_format:`b64_json`},failedResponseHandler:t.createJsonErrorResponseHandler(this.config.errorStructure??ar),successfulResponseHandler:t.createJsonResponseHandler(mr),abortSignal:c,fetch:this.config.fetch});return{images:f.data.map(e=>e.b64_json),warnings:u,response:{timestamp:d,modelId:this.modelId,headers:p}}}},mr=r.z.object({data:r.z.array(r.z.object({b64_json:r.z.string()}))});function hr(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 n=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${n};base64,${t.convertToBase64(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 gr({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 _r(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 vr=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()}),yr=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()}),br=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()}),xr=r.z.object({type:r.z.literal(`rss`),links:r.z.array(r.z.string().url()).max(1)}),Sr=r.z.discriminatedUnion(`type`,[vr,yr,br,xr]),Cr=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(Sr).optional()}).optional()}),wr=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()})}),Tr=t.createJsonErrorResponseHandler({errorSchema:wr,errorToMessage:e=>e.error.message});function Er({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 Dr=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:n,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,seed:l,responseFormat:u,providerOptions:d,tools:f,toolChoice:p}){let m=[],h=await t.parseProviderOptions({provider:`xai`,providerOptions:d,schema:Cr})??{};a!=null&&m.push({type:`unsupported-setting`,setting:`topK`}),o!=null&&m.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),s!=null&&m.push({type:`unsupported-setting`,setting:`presencePenalty`}),c!=null&&m.push({type:`unsupported-setting`,setting:`stopSequences`}),u!=null&&u.type===`json`&&u.schema!=null&&m.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:g,warnings:_}=hr(e);m.push(..._);let{tools:v,toolChoice:y,toolWarnings:b}=Er({tools:f,toolChoice:p});return m.push(...b),{args:{model:this.modelId,max_tokens:n,temperature:r,top_p:i,seed:l,reasoning_effort:h.reasoningEffort,response_format:u?.type===`json`?u.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:u.name??`response`,schema:u.schema,strict:!0}}:void 0,search_parameters:h.searchParameters?{mode:h.searchParameters.mode,return_citations:h.searchParameters.returnCitations,from_date:h.searchParameters.fromDate,to_date:h.searchParameters.toDate,max_search_results:h.searchParameters.maxSearchResults,sources:h.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:g,tools:v,tool_choice:y},warnings:m}}async doGenerate(e){let{args:n,warnings:r}=await this.getArgs(e),{responseHeaders:i,value:a,rawValue:o}=await t.postJsonToApi({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:t.combineHeaders(this.config.headers(),e.headers),body:n,failedResponseHandler:Tr,successfulResponseHandler:t.createJsonResponseHandler(kr),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=a.choices[0],c=[];if(s.message.content!=null&&s.message.content.length>0){let e=s.message.content,t=n.messages[n.messages.length-1];t?.role===`assistant`&&e===t.content&&(e=``),e.length>0&&c.push({type:`text`,text:e})}if(s.message.reasoning_content!=null&&s.message.reasoning_content.length>0&&c.push({type:`reasoning`,text:s.message.reasoning_content}),s.message.tool_calls!=null)for(let e of s.message.tool_calls)c.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(a.citations!=null)for(let e of a.citations)c.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:c,finishReason:_r(s.finish_reason),usage:{inputTokens:a.usage.prompt_tokens,outputTokens:a.usage.completion_tokens,totalTokens:a.usage.total_tokens,reasoningTokens:a.usage.completion_tokens_details?.reasoning_tokens??void 0},request:{body:n},response:{...gr(a),headers:i,body:o},warnings:r}}async doStream(e){let{args:n,warnings:r}=await this.getArgs(e),i={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:a,value:o}=await t.postJsonToApi({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:t.combineHeaders(this.config.headers(),e.headers),body:i,failedResponseHandler:Tr,successfulResponseHandler:t.createEventSourceResponseHandler(Ar),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0,u={},d={},f=this;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(l&&=(n.enqueue({type:`response-metadata`,...gr(r)}),!1),r.citations!=null)for(let e of r.citations)n.enqueue({type:`source`,sourceType:`url`,id:f.config.generateId(),url:e});r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens,c.reasoningTokens=r.usage.completion_tokens_details?.reasoning_tokens??void 0);let a=r.choices[0];if(a?.finish_reason!=null&&(s=_r(a.finish_reason)),a?.delta==null)return;let o=a.delta,p=a.index;if(o.content!=null&&o.content.length>0){let e=o.content,t=i.messages[i.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let a=`text-${r.id||p}`;u[a]??(u[a]={type:`text`},n.enqueue({type:`text-start`,id:a})),n.enqueue({type:`text-delta`,id:a,delta:e})}if(o.reasoning_content!=null&&o.reasoning_content.length>0){let e=`reasoning-${r.id||p}`;if(d[e]===o.reasoning_content)return;d[e]=o.reasoning_content,u[e]??(u[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:o.reasoning_content})}if(o.tool_calls!=null)for(let e of o.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(u))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:s,usage:c})}})),request:{body:i},response:{headers:a}}}},Or=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()}),kr=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:Or,citations:r.z.array(r.z.string().url()).nullish()}),Ar=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:Or.nullish(),citations:r.z.array(r.z.string().url()).nullish()}),jr=`2.0.23`,Mr={errorSchema:wr,errorToMessage:e=>e.error.message};function Nr(e={}){let n=t.withoutTrailingSlash(e.baseURL??`https://api.x.ai/v1`),r=()=>t.withUserAgentSuffix({Authorization:`Bearer ${t.loadApiKey({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${jr}`),i=i=>new Dr(i,{provider:`xai.chat`,baseURL:n,headers:r,generateId:t.generateId,fetch:e.fetch}),a=t=>new pr(t,{provider:`xai.image`,url:({path:e})=>`${n}${e}`,headers:r,fetch:e.fetch,errorStructure:Mr}),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 Pr=Nr();function Fr(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,p.streamText)({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(n){case`openai-chat`:return r(nr({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return r(nr({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return r(Ce({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return r(rt({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return r(Nr({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${n}`)}}var Ir=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),Fr(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 Lr(e){let[n,r]=(0,g.useState)(void 0),[i,a]=(0,g.useState)([]),[o,s]=(0,g.useState)(void 0),[c,l]=(0,g.useState)(e.buildResult),[u,d]=(0,g.useState)(e.env),[f,p]=(0,g.useState)(e.apiServerUrl),[m,_]=(0,g.useState)(void 0);return(0,g.useEffect)(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),(0,g.useEffect)(()=>{if(!c||`error`in c){r(void 0),a([]),s(void 0),_(void 0);return}let e=new AbortController,n=!1;return s(void 0),r(void 0),_(void 0),(async()=>{let n=await Rr(),i=(0,h.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 Ir({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();_(l),r(s)})().catch(e=>{n||s(e instanceof Error?e:Error(String(e)))}),()=>{n=!0,e.abort()}},[c,u,f]),(0,g.useMemo)(()=>({agent:n,logs:i,error:o,capabilities:m}),[n,i,o,m])}async function Rr(){let e=(0,u.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var zr=Object.getOwnPropertyNames,K=(e,t)=>function(){return t||(0,e[zr(e)[0]])((t={exports:{}}).exports,t),t.exports},q=(0,_.createRequire)(require(`url`).pathToFileURL(__filename).href);v.z.object({email:v.z.string().email(),password:v.z.string().min(8)}),v.z.object({email:v.z.string().email(),code:v.z.string()}),v.z.object({email:v.z.string().email(),password:v.z.string().min(8)});var Br=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))}})}},Vr=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 Hr(e){}function Ur(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Hr,onError:n=Hr,onRetry:r=Hr,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Wr(`${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}`)}}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 qs(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new qs(`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 Xs(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: ${Zr(t)}`,cause:t}),this[di]=!0,this.value=e}static isInstance(e){return Xr.hasMarker(e,li)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};di=ui;var pi=fi,mi=({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 ni({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`};mi();var hi=/"__proto__"\s*:/,gi=/"constructor"\s*:/;function _i(e){let t=JSON.parse(e);return typeof t!=`object`||!t||hi.test(e)===!1&&gi.test(e)===!1?t:vi(t)}function vi(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 yi(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return _i(e)}finally{Error.stackTraceLimit=t}}var bi=Symbol.for(`vercel.ai.validator`);function xi(e){return{[bi]:!0,validate:e}}function Si(e){return typeof e==`object`&&!!e&&bi in e&&e[bi]===!0&&`validate`in e}function Ci(e){return Si(e)?e:wi(e)}function wi(e){return xi(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new pi({value:t,cause:n.issues})}})}async function Ti({value:e,schema:t}){let n=Ci(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:pi.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:pi.wrap({value:e,cause:t}),rawValue:e}}}async function Ei({text:e,schema:t}){try{let n=yi(e);return t==null?{success:!0,value:n,rawValue:n}:await Ti({value:n,schema:t})}catch(t){return{success:!1,error:si.isInstance(t)?t:new si({text:e,cause:t}),rawValue:void 0}}}var{btoa:Di,atob:Oi}=globalThis;function ki(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 J=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}`)}}},Ai=v.z.object({per_page:v.z.number().int().positive().max(100).default(10).optional(),page:v.z.number().int().nonnegative().default(0).optional()}),ji=e=>v.z.object({has_more:v.z.boolean(),items:v.z.array(e)}),Mi=v.z.object({limit:v.z.number().int().positive().max(100).default(10).optional(),cursor:v.z.string().optional()}),Ni=e=>v.z.object({next_cursor:v.z.string().nullable(),items:v.z.array(e)}),Pi=v.z.any().nullable().refine(e=>e?Object.keys(e).length<=16:!0,{message:`Metadata must contain at most 16 keys`}),Fi=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,Ii=(e,t)=>{let n=new Gr;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(n.writable).catch(e=>{}),Li(n.readable,t)},Li=(e,t)=>{let n=e.pipeThrough(new TransformStream({async transform(e,n){let r=await Ei({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 ki(n)},Ri=v.z.union([v.z.object({agent_id:v.z.uuid(),deployment_id:v.z.uuid()}),v.z.object({agent_id:v.z.uuid(),deployment_number:v.z.number().int().positive()})]),zi=v.z.object({agent_id:v.z.uuid(),deployment_id:v.z.uuid()}),Bi=v.z.object({path:v.z.string(),id:v.z.uuid()}),Vi=Bi.or(v.z.object({path:v.z.string(),data:v.z.string().max(1024*1024*5)})),Hi=v.z.enum([`production`,`preview`]),Ui=v.z.object({agent_id:v.z.uuid(),output_files:v.z.array(Vi).optional(),source_files:v.z.array(Vi).optional(),files:v.z.array(Vi).optional(),target:Hi,entrypoint:v.z.string().optional(),message:v.z.string().max(128).optional()}).transform(e=>e.files&&!e.output_files?{...e,output_files:e.files,files:void 0}:e),Wi=v.z.object({id:v.z.uuid(),number:v.z.number().int().positive(),created_at:v.z.iso.datetime(),updated_at:v.z.iso.datetime(),created_by:v.z.uuid().nullable(),created_from:v.z.enum([`cli`]),agent_id:v.z.uuid(),source_files:v.z.array(Bi),output_files:v.z.array(Bi),status:v.z.enum([`success`,`failed`,`deploying`,`pending`]),target:Hi,error_message:v.z.string().nullable(),user_message:v.z.string().nullable(),platform:v.z.enum([`lambda`]),platform_memory_mb:v.z.number().int().positive(),platform_region:v.z.string().nullable()}),Gi=v.z.object({id:v.z.uuid(),created_at:v.z.string().datetime(),updated_at:v.z.string().datetime(),agent_id:v.z.uuid(),deployment_id:v.z.uuid(),level:v.z.enum([`log`,`info`,`warning`,`error`]),message:v.z.string()}),Ki=Ai.extend({agent_id:v.z.uuid(),order:v.z.enum([`asc`,`desc`]).default(`asc`).optional()}),qi=ji(Wi);var Ji=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 J(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 J(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 J(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);await J(t,200)}};v.z.object({agent_id:v.z.uuid(),target:Hi.array().optional()}),v.z.object({id:v.z.uuid(),created_at:v.z.date(),updated_at:v.z.date(),created_by:v.z.uuid(),updated_by:v.z.uuid(),key:v.z.string(),value:v.z.string().nullable(),secret:v.z.boolean(),target:Hi.array()});const Yi=v.z.object({key:v.z.string(),value:v.z.string(),secret:v.z.boolean(),target:Hi.array().optional(),upsert:v.z.boolean().optional()});Yi.extend({agent_id:v.z.uuid()}),v.z.object({agent_id:v.z.uuid(),id:v.z.uuid()}),v.z.object({agent_id:v.z.uuid(),id:v.z.uuid(),key:v.z.string().optional(),value:v.z.string().optional(),secret:v.z.boolean().optional(),target:Hi.array().default([`preview`,`production`]).optional()});var Xi=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 J(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 J(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/env/${e.id}`);await J(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 J(t,200),t.json()}};const Zi=v.z.object({id:v.z.string(),agent_id:v.z.uuid(),agent_deployment_id:v.z.uuid(),received_at:v.z.date(),request_method:v.z.string(),request_handler_location:v.z.string().nullable(),duration_ms:v.z.number().nullable(),error:v.z.string().nullable(),response_status:v.z.number().nullable()});Zi.extend({request_headers:v.z.record(v.z.string(),v.z.string()),request_headers_redacted:v.z.boolean(),request_body:v.z.string().nullable(),request_body_redacted:v.z.boolean(),response_headers:v.z.record(v.z.string(),v.z.string()).nullable(),response_headers_redacted:v.z.boolean(),response_body:v.z.string().nullable(),response_body_redacted:v.z.boolean()}),Mi.extend({agent_id:v.z.string(),agent_deployment_id:v.z.number().optional()}),Ni(Zi);var Qi=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 J(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 J(n,200),n.json()}};Mi.extend({agent_id:v.z.uuid(),agent_deployment_id:v.z.uuid().optional()}),v.z.object({agent_id:v.z.uuid(),run_id:v.z.uuid()});var $i=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 J(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 J(t,200),t.json()}};const ea=v.z.enum([`streaming`,`stalled`,`completed`,`interrupted`,`error`]),ta=v.z.enum([`tool_call`,`queued_message`]),na=v.z.object({id:v.z.uuid(),number:v.z.number().int().positive(),chat_id:v.z.uuid(),chat_run_id:v.z.uuid(),agent_id:v.z.uuid(),agent_deployment_id:v.z.uuid(),started_at:v.z.string().datetime(),status:ea,error:v.z.string().nullable(),continuation_reason:ta.nullable(),response_status:v.z.number().nullable(),response_message_id:v.z.uuid().nullable(),time_to_first_token_micros:v.z.number().nullable()});na.extend({heartbeat_at:v.z.date(),completed_at:v.z.date().nullable(),interrupted_at:v.z.date().nullable(),first_message_id:v.z.uuid().nullable(),last_message_id:v.z.uuid().nullable(),response_headers:v.z.record(v.z.string(),v.z.string()).nullable(),response_headers_redacted:v.z.boolean(),response_body:v.z.string().nullable(),response_body_redacted:v.z.boolean(),usage_model:v.z.string().nullable(),usage_total_input_tokens:v.z.number().nullable(),usage_total_output_tokens:v.z.number().nullable(),usage_total_tokens:v.z.number().nullable(),usage_total_cached_input_tokens:v.z.number().nullable(),usage_cost_usd:v.z.number().nullable()}),Mi.extend({chat_id:v.z.uuid(),run_id:v.z.uuid().optional()}),Ni(na);var ra=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 J(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 J(t,200),t.json()}};Mi.extend({agent_id:v.z.uuid(),agent_deployment_id:v.z.uuid().optional(),chat_id:v.z.uuid().optional(),run_id:v.z.uuid().optional(),status:ea.optional()}),Ni(na);var ia=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 J(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 J(t,200),t.json()}};const aa=v.z.object({type:v.z.literal(`eq`),key:v.z.string(),value:v.z.string()}),oa=v.z.object({type:v.z.literal(`and`),get filters(){return v.z.array(v.z.union([aa,oa]))}}),sa=v.z.object({start_time:v.z.iso.datetime().pipe(v.z.coerce.date()),end_time:v.z.iso.datetime().pipe(v.z.coerce.date()),filters:v.z.string().transform(e=>JSON.parse(e)).pipe(oa),limit:v.z.string().pipe(v.z.coerce.number().min(1).max(1e4)).optional()});var ca=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 J(n,200),await n.json()}};v.default.object({start_time:v.default.iso.datetime().pipe(v.default.coerce.date()),end_time:v.default.iso.datetime().pipe(v.default.coerce.date()),message_pattern:v.default.string().optional(),filters:v.default.string().transform(e=>JSON.parse(e)).pipe(oa).optional(),limit:v.default.string().pipe(v.default.coerce.number().min(1).max(1e4)).optional()});const la=v.default.object({timestamp:v.default.iso.datetime().pipe(v.default.coerce.date()),message:v.default.string(),level:v.default.enum([`info`,`error`,`warn`])}),ua=v.default.object({logs:v.default.array(la)});var da=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 J(n,200);let r=await n.json();return ua.parse(r)}};const fa=v.z.enum([`private`,`public`]),pa=v.z.object({organization_id:v.z.uuid(),name:v.z.string().regex(Fi),description:v.z.string().optional(),visibility:fa.default(`private`).optional(),source_files:v.z.array(Vi).optional(),output_files:v.z.array(Vi).optional(),entrypoint:v.z.string().optional(),env:v.z.array(Yi).optional(),request_id:v.z.uuid().optional()}),ma=v.z.object({id:v.z.uuid(),organization_id:v.z.uuid(),created_at:v.z.iso.datetime(),updated_at:v.z.iso.datetime(),created_by:v.z.uuid(),name:v.z.string().regex(Fi),description:v.z.string().nullable(),avatar_url:v.z.string().nullable(),visibility:fa,active_deployment_id:v.z.uuid().nullable(),pinned:v.z.boolean().default(!1),request_url:v.z.url().nullable().describe(`The URL for the agent requests. Only visible to owners.`)}),ha=v.z.object({id:v.z.uuid(),name:v.z.string().regex(Fi).optional(),description:v.z.string().optional(),visibility:fa.optional(),active_deployment_id:v.z.uuid().optional(),avatar_file_id:v.z.uuid().nullable().optional()}),ga=Ai.extend({organization_id:v.z.uuid().optional(),pinned:v.z.boolean().optional()}),_a=ji(ma),va=v.z.object({agent_id:v.z.uuid(),input:v.z.string(),caret:v.z.number().optional(),selection:v.z.tuple([v.z.number(),v.z.number()]).optional(),chat_id:v.z.uuid().optional(),agent_deployment_id:v.z.uuid().optional()}),ya=v.z.object({text:v.z.string(),caret:v.z.number().optional(),selection:v.z.tuple([v.z.number(),v.z.number()]).optional()}),ba=v.z.object({agent_id:v.z.uuid(),agent_deployment_id:v.z.uuid().optional(),selected:v.z.record(v.z.string(),v.z.string()).optional()}),xa=v.z.object({agent_id:v.z.uuid(),start_time:v.z.iso.datetime().pipe(v.z.coerce.date()),end_time:v.z.iso.datetime().pipe(v.z.coerce.date())}),Sa=v.z.object({seconds:v.z.string()});var Ca=class{constructor(e){this.client=e,this.deployments=new Ji(e),this.env=new Xi(e),this.webhook=new Qi(e),this.runs=new $i(e),this.steps=new ia(e),this.logs=new da(e),this.traces=new ca(e)}async create(e){let t=await this.client.request(`POST`,`/api/agents`,JSON.stringify(e));return await J(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/agents/${e.id}`,JSON.stringify(e));return await J(t,200),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e}`);return await J(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 J(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}`);await J(t,204)}async completions(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/completions`,JSON.stringify(e));if(await J(t,200),t.headers.get(`content-type`)===`application/json`){let e=await t.json();return ki(new ReadableStream({start(t){t.enqueue(e),t.close()}}))}return Ii(t,ya)}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 J(n,200),n.json()}async pin(e){let t=await this.client.request(`POST`,`/api/agents/${e}/pin`);await J(t,204)}async unpin(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}/pin`);await J(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 J(n,200),n.json()}},wa=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 J(n,201),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/files/${e}`);return await J(t,200),new File([await t.blob()],``)}};const Ta=v.z.enum([`owner`,`admin`,`billing_admin`,`member`]),Ea=v.z.object({user_id:v.z.uuid(),organization_id:v.z.uuid(),role:Ta,created_at:v.z.date(),updated_at:v.z.date()}),Da=v.z.object({id:v.z.uuid(),created_at:v.z.date(),updated_at:v.z.date(),display_name:v.z.string().nullable(),email:v.z.email(),avatar_url:v.z.url().nullable(),username:v.z.string()}),Oa=Ea.extend({user:Da});Ai.extend({organization_id:v.z.uuid()}),ji(Oa),v.z.object({organization_id:v.z.uuid(),user_id:v.z.uuid()}),v.z.object({role:v.z.enum([`owner`,`admin`,`member`,`billing_admin`]).optional()}).extend({organization_id:v.z.uuid(),user_id:v.z.uuid()});var ka=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 J(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 J(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);await J(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 J(t,200),t.json()}},Aa=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 J(t,200),t.json()}};const ja=v.z.object({id:v.z.uuid(),name:v.z.string(),created_at:v.z.date(),updated_at:v.z.date(),membership:Ea.nullable(),members_url:v.z.url(),invites_url:v.z.url(),avatar_url:v.z.url().nullable()}),Ma=v.z.object({name:v.z.string().regex(Fi)}),Na=v.z.object({name:v.z.string().max(100).optional(),avatar_file_id:v.z.string().nullable().optional(),avatar_url:v.z.string().url().nullable().optional()});var Pa=class{constructor(e){this.client=e,this.members=new ka(e),this.agents=new Aa(e)}async list(){let e=await this.client.request(`GET`,`/api/organizations`);return await J(e,200),e.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e}`);return await J(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/organizations`,JSON.stringify(e));return await J(t,201),t.json()}async update(e,t){let n=await this.client.request(`PATCH`,`/api/organizations/${e}`,JSON.stringify(t));return await J(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e}`);await J(t,204)}};const Fa=v.default.object({id:v.default.uuid(),created_at:v.default.date(),updated_at:v.default.date(),email:v.default.string().email(),email_verified:v.default.boolean(),display_name:v.default.string(),username:v.default.string(),organization_id:v.default.uuid(),avatar_url:v.default.string().url().nullable()}),Ia=v.default.object({display_name:v.default.string().max(100).optional(),username:v.default.string().regex(Fi).optional(),avatar_file_id:v.default.string().nullable().optional()}),La=v.default.object({provider:v.default.enum([`github`,`google`]),provider_account_id:v.default.string()}),Ra=v.default.object({github:v.default.array(La),google:v.default.array(La)});var za=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 J(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/users/me`,JSON.stringify(e));return await J(t,200),t.json()}async accounts(){let e=await this.client.request(`GET`,`/api/users/me/accounts`);return await J(e,200),e.json()}async unlinkProvider(e,t){let n=await this.client.request(`DELETE`,`/api/users/me/accounts/${e}/${t}`);await J(n,204)}async delete(){let e=await this.client.request(`DELETE`,`/api/users/me`);await J(e,204)}};const Ba=v.z.enum([`ai-sdk`]),Va=v.z.array(v.z.custom()),Ha=v.z.enum([`user`,`assistant`,`system`]),Ua=v.z.object({id:v.z.uuid(),created_at:v.z.string().datetime(),chat_id:v.z.uuid(),metadata:Pi}).extend({format:v.z.literal(`ai-sdk`),parts:Va,role:Ha}),Wa=v.z.discriminatedUnion(`format`,[Ua]),Ga=Mi.extend({chat_id:v.z.uuid(),format:Ba.default(`ai-sdk`).optional()}),Ka=Ni(Wa),qa=v.z.object({chat_id:v.z.uuid(),message_id:v.z.uuid()}),Ja=v.z.object({id:v.z.uuid().optional(),role:Ha,parts:Va,metadata:Pi.optional(),format:v.z.literal(`ai-sdk`).optional()}),Ya=v.z.object({message_id:v.z.uuid(),metadata:Pi.optional(),role:Ha.optional(),parts:Va.optional(),format:v.z.literal(`ai-sdk`).optional(),behavior:v.z.enum([`interrupt`,`enqueue`,`none`]).optional()}),Xa=v.z.enum([`enqueue`,`interrupt`,`append`]),Za=v.z.object({chat_id:v.z.uuid(),behavior:Xa.optional(),messages:v.z.array(Ja).min(1)}),Qa=v.z.object({messages:v.z.array(Wa)});var $a=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 J(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/messages/${e}`);await J(t,204)}async get(e){let t=await this.client.request(`GET`,`/api/messages/${e}`);return await J(t,200),t.json()}async update(e){let t=await this.client.request(`PUT`,`/api/messages/${e.message_id}`,JSON.stringify(e));await J(t,200)}async send(e){let t=await this.client.request(`POST`,`/api/messages`,JSON.stringify(e));return await J(t,201),t.json()}};Mi.extend({chat_id:v.z.uuid()});const eo=v.z.object({id:v.z.uuid(),started_at:v.z.date(),agent_id:v.z.uuid(),agent_deployment_id:v.z.uuid().nullable(),chat_id:v.z.uuid(),step_count:v.z.number().int().positive(),status:ea.nullable(),error:v.z.string().nullable()});Ni(eo);var to=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 J(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 J(t,200),t.json()}};const no=v.z.enum([`streaming`,`idle`,`error`,`interrupted`]),ro=v.z.enum([`private`,`organization`,`public`]),io=v.z.object({id:v.z.uuid(),created_at:v.z.iso.datetime(),updated_at:v.z.iso.datetime(),created_by:v.z.uuid().nullable(),organization_id:v.z.uuid(),title:v.z.string().nullable(),visibility:ro,metadata:Pi,archived:v.z.boolean(),status:no,error:v.z.string().nullable(),agent_deployment_id:v.z.uuid().nullable(),agent:ma}),ao=v.z.enum([`websocket`,`sse`]),oo=v.z.object({organization_id:v.z.uuid(),title:v.z.string().optional(),visibility:ro.default(`private`).optional(),metadata:Pi.optional(),agent_id:v.z.uuid(),agent_deployment_id:v.z.uuid().optional(),messages:v.z.array(Ja).optional()}),so=oo.extend({stream:v.z.literal(!0)}),co=oo.extend({stream:v.z.literal(!1).optional()}),lo=v.z.union([so,co]),uo=v.z.union([Mi.extend({organization_id:v.z.uuid()}),Mi.extend({agent_id:v.z.uuid()})]),fo=io.extend({messages:v.z.array(Wa)}),po=Ni(io),mo=v.z.discriminatedUnion(`event`,[v.z.strictObject({event:v.z.literal(`chat.updated`),data:io}),v.z.strictObject({event:v.z.literal(`message.created`),data:Wa}),v.z.strictObject({event:v.z.literal(`message.updated`),data:Wa}),v.z.strictObject({event:v.z.literal(`message.deleted`),data:v.z.object({id:v.z.uuid()})}),v.z.strictObject({event:v.z.literal(`message.chunk.added`),data:v.z.object({id:v.z.uuid(),chunk:v.z.custom()})})]),ho=v.z.strictObject({event:v.z.literal(`chat.created`),data:fo});var go=class{constructor(e){this.client=e,this.runs=new to(e),this.steps=new ra(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 J(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=Ii(n,v.z.discriminatedUnion(`event`,[mo,ho])),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 J(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 J(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/chats/${e}`);await J(t,204)}async stop(e){let t=await this.client.request(`POST`,`/api/chats/${e}/stop`);await J(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 J(n,200),Ii(n,mo)}streamWS(e,t){let n=this.client.websocket(`/api/chats/${e}/stream`),r=new Gr,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(()=>{})}),Li(r.readable,mo)}};const _o=v.z.object({id:v.z.uuid(),organization_id:v.z.uuid(),role:Ta,invited_by:v.z.uuid(),expires_at:v.z.date(),created_at:v.z.date(),updated_at:v.z.date(),reusable:v.z.boolean(),accepted_at:v.z.date().nullable(),email:v.z.string().email().nullable()}),vo=v.z.object({organization_id:v.z.uuid(),role:Ta,email:v.z.string().email().optional(),reusable:v.z.boolean().optional()}),yo=v.z.object({organization_id:v.z.uuid()}),bo=v.z.object({organization_id:v.z.uuid(),invite_id:v.z.uuid()}),xo=v.z.object({code:v.z.string()}),So=xo.extend({invite_id:v.z.uuid()});var Co=class{constructor(e){this.client=e}async create(e){let t=await this.client.request(`POST`,`/api/invites`,JSON.stringify(e));return await J(t,201),t.json()}async list(e){let t=await this.client.request(`GET`,`/api/invites?organization_id=${e.organization_id}`);return await J(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/invites/${e.invite_id}`);await J(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 J(t,201),t.json()}},wo=class{constructor(e){this.chats=new go(this),this.runs=new to(this),this.agents=new Ca(this),this.files=new wa(this),this.organizations=new Pa(this),this.invites=new Co(this),this.users=new za(this),this.messages=new $a(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 Br(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())}},To=K({"../../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=q(`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}})})}),Eo=K({"../../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:()=>{}}})}),Do=K({"../../node_modules/ws/lib/buffer-util.js":((e,t)=>{let{EMPTY_BUFFER:n}=Eo(),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=q(`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{}})}),Oo=K({"../../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])}}}})}),ko=K({"../../node_modules/ws/lib/permessage-deflate.js":((e,t)=>{let n=q(`zlib`),r=Do(),i=Oo(),{kStatusCode:a}=Eo(),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)}})}),Ao=K({"../../node_modules/ws/lib/validation.js":((e,t)=>{let{isUtf8:n}=q(`buffer`),{hasBlob:r}=Eo(),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=q(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})}),jo=K({"../../node_modules/ws/lib/receiver.js":((e,t)=>{let{Writable:n}=q(`stream`),r=ko(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Eo(),{concat:c,toArrayBuffer:l,unmask:u}=Do(),{isValidStatusCode:d,isValidUTF8:f}=Ao(),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}}})}),Mo=K({"../../node_modules/ws/lib/sender.js":((e,t)=>{let{Duplex:n}=q(`stream`),{randomFillSync:r}=q(`crypto`),i=ko(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Eo(),{isBlob:c,isValidStatusCode:l}=Ao(),{mask:u,toBuffer:d}=Do(),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)}})}),No=K({"../../node_modules/ws/lib/event-target.js":((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Eo(),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)}})}),Po=K({"../../node_modules/ws/lib/extension.js":((e,t)=>{let{tokenChars:n}=Ao();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}})}),Fo=K({"../../node_modules/ws/lib/websocket.js":((e,t)=>{let n=q(`events`),r=q(`https`),i=q(`http`),a=q(`net`),o=q(`tls`),{randomBytes:s,createHash:c}=q(`crypto`),{Duplex:l,Readable:u}=q(`stream`),{URL:d}=q(`url`),f=ko(),p=jo(),m=Mo(),{isBlob:h}=Ao(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=Eo(),{EventTarget:{addEventListener:w,removeEventListener:T}}=No(),{format:E,parse:D}=Po(),{toBuffer:O}=Do(),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`,H),t.on(`end`,le),t.on(`error`,ue),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`,H),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`,H),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`,H),this.removeListener(`end`,le),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 H(e){this[S]._receiver.write(e)||this.pause()}function le(){let e=this[S];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function ue(){let e=this[S];this.removeListener(`error`,ue),this.on(`error`,C),e&&(e._readyState=N.CLOSING,this.destroy())}})}),Io=K({"../../node_modules/ws/lib/stream.js":((e,t)=>{Fo();let{Duplex:n}=q(`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})}),Lo=K({"../../node_modules/ws/lib/subprotocol.js":((e,t)=>{let{tokenChars:n}=Ao();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}})}),Ro=K({"../../node_modules/ws/lib/websocket-server.js":((e,t)=>{let n=q(`events`),r=q(`http`),{Duplex:i}=q(`stream`),{createHash:a}=q(`crypto`),o=Po(),s=ko(),c=Lo(),l=Fo(),{GUID:u,kWebSocket:d}=Eo(),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 Zs=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Ys({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)}})}},Qs=`vercel.ai.error`,$s=Symbol.for(Qs),ec,tc=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[ec]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Qs)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};ec=$s;var nc=tc;function rc(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var ic=`AI_InvalidArgumentError`,ac=`vercel.ai.error.${ic}`,oc=Symbol.for(ac),sc,cc=class extends nc{constructor({message:e,cause:t,argument:n}){super({name:ic,message:e,cause:t}),this[sc]=!0,this.argument=n}static isInstance(e){return nc.hasMarker(e,ac)}};sc=oc;var lc=`AI_JSONParseError`,uc=`vercel.ai.error.${lc}`,dc=Symbol.for(uc),fc,pc=class extends nc{constructor({text:e,cause:t}){super({name:lc,message:`JSON parsing failed: Text: ${e}.
|
|
20
|
+
Error message: ${rc(t)}`,cause:t}),this[fc]=!0,this.text=e}static isInstance(e){return nc.hasMarker(e,uc)}};fc=dc;var mc=`AI_TypeValidationError`,hc=`vercel.ai.error.${mc}`,gc=Symbol.for(hc),_c,vc=class e extends nc{constructor({value:e,cause:t}){super({name:mc,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
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
|
|
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)}})}),zo=K({"../../node_modules/ws/index.js":((e,t)=>{let n=Fo();n.createWebSocketStream=Io(),n.Server=Ro(),n.Receiver=jo(),n.Sender=Mo(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})}),Bo=K({"../../node_modules/@blink-sdk/compute-protocol/dist/server-BAzD0QDI.cjs":(e=>{var t,n,r,i;let a=To(),o=q(`node:fs/promises`);o=a.__toESM(o);let s=q(`module`);s=a.__toESM(s);let c=q(`fs/promises`);c=a.__toESM(c);let l=q(`child_process`);l=a.__toESM(l);let u=zo();u=a.__toESM(u);let d=q(`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,H=Uint16Array,le=Int32Array,ue=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]),de=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]),fe=new V([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),pe=function(e,t){for(var n=new H(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new le(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}},me=pe(ue,2),he=me.b,ge=me.r;he[28]=258,ge[258]=28;var _e=pe(de,0),ve=_e.b;_e.r;for(var ye=new H(32768),U=0;U<32768;++U){var be=(U&43690)>>1|(U&21845)<<1;be=(be&52428)>>2|(be&13107)<<2,be=(be&61680)>>4|(be&3855)<<4,ye[U]=((be&65280)>>8|(be&255)<<8)>>1}for(var xe=(function(e,t,n){for(var r=e.length,i=0,a=new H(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new H(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new H(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[ye[d]>>c]=l}else for(s=new H(r),i=0;i<r;++i)e[i]&&(s[i]=ye[o[e[i]-1]++]>>15-e[i]);return s}),Se=new V(288),U=0;U<144;++U)Se[U]=8;for(var U=144;U<256;++U)Se[U]=9;for(var U=256;U<280;++U)Se[U]=7;for(var U=280;U<288;++U)Se[U]=8;for(var Ce=new V(32),U=0;U<32;++U)Ce[U]=5;var we=xe(Se,9,1),Te=xe(Ce,5,1),Ee=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},W=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},De=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Oe=function(e){return(e+7)/8|0},ke=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))},Ae=[`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`],G=function(e,t,n){var r=Error(t||Ae[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,G),!n)throw r;return r},je=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=W(e,d,1);var v=W(e,d+1,3);if(d+=3,v)if(v==1)p=we,m=Te,h=9,g=5;else if(v==2){var y=W(e,d,31)+257,b=W(e,d+10,15)+4,x=y+W(e,d+5,31)+1;d+=14;for(var S=new V(x),C=new V(19),w=0;w<b;++w)C[fe[w]]=W(e,d+w*3,7);d+=b*3;for(var T=Ee(C),E=(1<<T)-1,D=xe(C,T,1),w=0;w<x;){var O=D[W(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+W(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+W(e,d,7),d+=3):k==18&&(j=11+W(e,d,127),d+=7);j--;)S[w++]=A}}var M=S.subarray(0,y),N=S.subarray(y);h=Ee(M),g=Ee(N),p=xe(M,h,1),m=xe(N,g,1)}else G(1);else{var k=Oe(d)+4,ee=e[k-4]|e[k-3]<<8,P=k+ee;if(P>i){c&&G(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&&G(0);break}}s&&l(f+131072);for(var F=(1<<h)-1,te=(1<<g)-1,I=d;;I=d){var A=p[De(e,d)&F],L=A>>4;if(d+=A&15,d>_){c&&G(0);break}if(A||G(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=ue[w];R=W(e,d,(1<<ne)-1)+he[w],d+=ne}var z=m[De(e,d)&te],re=z>>4;z||G(3),d+=z&15;var N=ve[re];if(re>3){var ne=de[re];N+=De(e,d)&(1<<ne)-1,d+=ne}if(d>_){c&&G(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&&G(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?ke(n,0,f):n.subarray(0,f)},Me=new V(0),Ne=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&G(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)},Pe=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},Fe=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&G(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&G(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function Ie(e,t){return je(e,{i:2},t&&t.out,t&&t.dictionary)}function Le(e,t){var n=Ne(e);return n+8>e.length&&G(6,`invalid gzip data`),je(e.subarray(n,-8),{i:2},t&&t.out||new V(Pe(e)),t&&t.dictionary)}function Re(e,t){return je(e.subarray(Fe(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function ze(e,t){return e[0]==31&&e[1]==139&&e[2]==8?Le(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?Ie(e,t):Re(e,t)}var Be=typeof TextDecoder<`u`&&new TextDecoder;try{Be.decode(Me,{stream:!0})}catch{}var Ve=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`:``)}})}),He=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=Ve(),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})}),Ue=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=He()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),We=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)}})}),Ge=a.__commonJS({"../../node_modules/supports-color/index.js":((e,t)=>{let n=q(`os`),r=q(`tty`),i=We(),{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)))}})}),Ke=a.__commonJS({"../../node_modules/debug/src/node.js":((e,t)=>{let n=q(`tty`),r=q(`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=Ge();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)}})}),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(`
|
|
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
|
-
`)}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=
|
|
30
|
-
`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})}),qe=a.__commonJS({"../../node_modules/debug/src/index.js":((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=Ue():t.exports=Ke()})});let Je={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Ye={get(e){return z.get(e,6),{signature:B.get(e,0),compressedSize:B.get(e,8),uncompressedSize:B.get(e,12)}},len:16},Xe={get(e){let t=z.get(e,6);return{signature:B.get(e,0),minVersion:z.get(e,4),dataDescriptor:!!(t&8),compressedMethod:z.get(e,8),compressedSize:B.get(e,18),uncompressedSize:B.get(e,22),filenameLength:z.get(e,26),extraFieldLength:z.get(e,28),filename:null}},len:30},Ze={get(e){return{signature:B.get(e,0),nrOfThisDisk:z.get(e,4),nrOfThisDiskWithTheStart:z.get(e,6),nrOfEntriesOnThisDisk:z.get(e,8),nrOfEntriesOfSize:z.get(e,10),sizeOfCd:B.get(e,12),offsetOfStartOfCd:B.get(e,16),zipFileCommentLength:z.get(e,20)}},len:22},Qe={get(e){let t=z.get(e,8);return{signature:B.get(e,0),minVersion:z.get(e,6),dataDescriptor:!!(t&8),compressedMethod:z.get(e,10),compressedSize:B.get(e,20),uncompressedSize:B.get(e,24),filenameLength:z.get(e,28),extraFieldLength:z.get(e,30),fileCommentLength:z.get(e,32),relativeOffsetOfLocalHeader:B.get(e,42),filename:null}},len:46};var $e=a.__toESM(qe(),1);function et(e){let t=new Uint8Array(B.len);return B.put(t,0,e),t}let tt=(0,$e.default)(`tokenizer:inflate`),nt=256*1024,rt=et(Je.DataDescriptor),it=et(Je.EndOfCentralDirectory);var at=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(nt)}async isZip(){return await this.peekSignature()===Je.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(B)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===it[0]&&n[r+1]===it[1]&&n[r+2]===it[2]&&n[r+3]===it[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){tt(`Cannot reading central-directory without random-read support`);return}tt(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){tt(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(Ze,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(Qe);if(t.signature!==Je.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new se(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),tt(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=nt;tt(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===nt;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=ot(this.syncBuffer.subarray(0,n),rt);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}tt(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,st(e),r.handler)}else r.handler?(tt(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(tt(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(tt(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(Ye)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Ye.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}inflate(e,t,n){if(e.compressedMethod===0)return n(t);tt(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let r=ze(t);return n(r)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(B);if(e===Je.LocalFileHeader){let e=await this.tokenizer.readToken(Xe);return e.filename=await this.tokenizer.readToken(new se(e.filenameLength,`utf-8`)),e}if(e===Je.CentralFileHeader)return!1;throw e===3759263696?Error(`Encrypted ZIP`):Error(`Unexpected signature`)}};function ot(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function st(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function ct(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function lt(e){return[...e].map(e=>e.charCodeAt(0))}function ut(e,t=0){let n=Number.parseInt(new se(6).get(e,148).replace(/\0.*$/,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}let dt={get:(e,t)=>e[t+3]&127|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},ft=4100;async function pt(e,t){return new gt(t).fromBuffer(e)}function mt(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function ht(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}var gt=class{constructor(e){this.detectConfident=async e=>{if(this.buffer=new Uint8Array(ft),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return{ext:`gz`,mime:`application/gzip`};if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await e.ignore(6);let t=await e.readToken(dt);return e.position+t>e.fileInfo.size?{ext:`mp3`,mime:`audio/mpeg`}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4])){let t;return await new at(e).unzip(e=>{switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return{async handler(e){let n=new TextDecoder(`utf-8`).decode(e).trim();t=mt(n)},stop:!0};case`[Content_Types].xml`:return{async handler(e){let n=new TextDecoder(`utf-8`).decode(e),r=n.indexOf(`.main+xml"`);if(r===-1){let e=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;n.includes(`ContentType="${e}"`)&&(t=mt(e))}else{n=n.slice(0,Math.max(0,r));let e=n.lastIndexOf(`"`),i=n.slice(Math.max(0,e+1));t=mt(i)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}}),t??{ext:`zip`,mime:`application/zip`}}if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),ht(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:ht(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:ht(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:ht(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:ht(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:ht(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/x-lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163])){async function t(){let t=await e.peekNumber(ne),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await e.readBuffer(i),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:ct(i),len:ct(a)}}async function r(t){for(;t>0;){let r=await n();if(r.id===17026)return(await e.readToken(new se(r.len))).replaceAll(/\00.*$/g,``);await e.ignore(r.len),--t}}let i=await n();switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:return}}if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(`{\\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190]))return{ext:`class`,mime:`application/java-vm`};if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/vnd.google.draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new se(4,`latin1`).get(this.buffer,2);if(e.match(`^d*`)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new se(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
|
|
31
|
-
`,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(ae),type:await e.readToken(new se(4,`latin1`))}}do{let n=await t();if(n.length<0)return;switch(n.type){case`IDAT`:return{ext:`png`,mime:`image/png`};case`acTL`:return{ext:`apng`,mime:`image/apng`};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:`png`,mime:`image/png`}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new se(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(oe))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),r=n.size-24;if(ht(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(r-=await e.readBuffer(t),ht(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(ht(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}await e.ignore(r)}return{ext:`asf`,mime:`application/vnd.ms-asf`}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new se(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x.ms.shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x.apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x.autodesk.fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&ut(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:`xml`,mime:`application/xml`}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:void 0;if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}},this.detectImprecise=async e=>{if(this.buffer=new Uint8Array(ft),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}},this.options={mpegOffsetTolerance:0,...e},this.detectors=[...e?.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let r=await n.detect(e);if(r)return r;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(j(t,this.tokenizerOptions))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){let t=await A(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=ft}=t,r,i,a=e.getReader({mode:`byob`});try{let{value:e,done:t}=await a.read(new Uint8Array(n));if(i=e,!t&&e)try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof b))throw e;r=void 0}i=e}finally{a.releaseLock()}let o=new TransformStream({async start(e){e.enqueue(i)},transform(e,t){t.enqueue(e)}}),s=e.pipeThrough(o);return s.fileType=r,s}check(e,t){return ht(this.buffer,e,t)}checkString(e,t){return this.check(lt(e),t)}async readTiffTag(e){let t=await this.tokenizer.readToken(e?re:z);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?re:z);for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t=(e?re:z).get(this.buffer,2),n=(e?ie:B).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(n>=8){let t=(e?re:z).get(this.buffer,8),n=(e?re:z).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:`tif`,mime:`image/tiff`}}if(t===43)return{ext:`tif`,mime:`image/tiff`}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}},_t=a.__commonJS({"../../node_modules/@xterm/addon-serialize/lib/addon-serialize.js":((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.SerializeAddon=r():n.SerializeAddon=r()})(e,(()=>(()=>{var e={930:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ColorContrastCache=void 0;let r=n(485);t.ColorContrastCache=class{constructor(){this._color=new r.TwoKeyMap,this._css=new r.TwoKeyMap}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}}},997:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.ThemeService=t.DEFAULT_ANSI_COLORS=void 0;let a=n(930),o=n(160),s=n(345),c=n(859),l=n(97),u=o.css.toColor(`#ffffff`),d=o.css.toColor(`#000000`),f=o.css.toColor(`#ffffff`),p=o.css.toColor(`#000000`),m={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117};t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{let e=[o.css.toColor(`#2e3436`),o.css.toColor(`#cc0000`),o.css.toColor(`#4e9a06`),o.css.toColor(`#c4a000`),o.css.toColor(`#3465a4`),o.css.toColor(`#75507b`),o.css.toColor(`#06989a`),o.css.toColor(`#d3d7cf`),o.css.toColor(`#555753`),o.css.toColor(`#ef2929`),o.css.toColor(`#8ae234`),o.css.toColor(`#fce94f`),o.css.toColor(`#729fcf`),o.css.toColor(`#ad7fa8`),o.css.toColor(`#34e2e2`),o.css.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:o.channels.toCss(r,i,a),rgba:o.channels.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+10*t;e.push({css:o.channels.toCss(n,n,n),rgba:o.channels.toRgba(n,n,n)})}return e})());let h=t.ThemeService=class extends c.Disposable{get colors(){return this._colors}constructor(e){super(),this._optionsService=e,this._contrastCache=new a.ColorContrastCache,this._halfContrastCache=new a.ColorContrastCache,this._onChangeColors=this.register(new s.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:u,background:d,cursor:f,cursorAccent:p,selectionForeground:void 0,selectionBackgroundTransparent:m,selectionBackgroundOpaque:o.color.blend(d,m),selectionInactiveBackgroundTransparent:m,selectionInactiveBackgroundOpaque:o.color.blend(d,m),ansi:t.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange(`theme`,(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(e={}){let n=this._colors;if(n.foreground=g(e.foreground,u),n.background=g(e.background,d),n.cursor=g(e.cursor,f),n.cursorAccent=g(e.cursorAccent,p),n.selectionBackgroundTransparent=g(e.selectionBackground,m),n.selectionBackgroundOpaque=o.color.blend(n.background,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundTransparent=g(e.selectionInactiveBackground,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundOpaque=o.color.blend(n.background,n.selectionInactiveBackgroundTransparent),n.selectionForeground=e.selectionForeground?g(e.selectionForeground,o.NULL_COLOR):void 0,n.selectionForeground===o.NULL_COLOR&&(n.selectionForeground=void 0),o.color.isOpaque(n.selectionBackgroundTransparent)&&(n.selectionBackgroundTransparent=o.color.opacity(n.selectionBackgroundTransparent,.3)),o.color.isOpaque(n.selectionInactiveBackgroundTransparent)&&(n.selectionInactiveBackgroundTransparent=o.color.opacity(n.selectionInactiveBackgroundTransparent,.3)),n.ansi=t.DEFAULT_ANSI_COLORS.slice(),n.ansi[0]=g(e.black,t.DEFAULT_ANSI_COLORS[0]),n.ansi[1]=g(e.red,t.DEFAULT_ANSI_COLORS[1]),n.ansi[2]=g(e.green,t.DEFAULT_ANSI_COLORS[2]),n.ansi[3]=g(e.yellow,t.DEFAULT_ANSI_COLORS[3]),n.ansi[4]=g(e.blue,t.DEFAULT_ANSI_COLORS[4]),n.ansi[5]=g(e.magenta,t.DEFAULT_ANSI_COLORS[5]),n.ansi[6]=g(e.cyan,t.DEFAULT_ANSI_COLORS[6]),n.ansi[7]=g(e.white,t.DEFAULT_ANSI_COLORS[7]),n.ansi[8]=g(e.brightBlack,t.DEFAULT_ANSI_COLORS[8]),n.ansi[9]=g(e.brightRed,t.DEFAULT_ANSI_COLORS[9]),n.ansi[10]=g(e.brightGreen,t.DEFAULT_ANSI_COLORS[10]),n.ansi[11]=g(e.brightYellow,t.DEFAULT_ANSI_COLORS[11]),n.ansi[12]=g(e.brightBlue,t.DEFAULT_ANSI_COLORS[12]),n.ansi[13]=g(e.brightMagenta,t.DEFAULT_ANSI_COLORS[13]),n.ansi[14]=g(e.brightCyan,t.DEFAULT_ANSI_COLORS[14]),n.ansi[15]=g(e.brightWhite,t.DEFAULT_ANSI_COLORS[15]),e.extendedAnsi){let r=Math.min(n.ansi.length-16,e.extendedAnsi.length);for(let i=0;i<r;i++)n.ansi[i+16]=g(e.extendedAnsi[i],t.DEFAULT_ANSI_COLORS[i+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e!==void 0)switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}else for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e]}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function g(e,t){if(e!==void 0)try{return o.css.toColor(e)}catch{}return t}t.ThemeService=h=r([i(0,l.IOptionsService)],h)},160:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.contrastRatio=t.toPaddedHex=t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0;let n=0,r=0,i=0,a=0;var o,s,c,l,u;function d(e){let t=e.toString(16);return t.length<2?`0`+t:t}function f(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}t.NULL_COLOR={css:`#00000000`,rgba:0},function(e){e.toCss=function(e,t,n,r){return r===void 0?`#${d(e)}${d(t)}${d(n)}`:`#${d(e)}${d(t)}${d(n)}${d(r)}`},e.toRgba=function(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0},e.toColor=function(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}}(o||(t.channels=o={})),function(e){function t(e,t){return a=Math.round(255*t),[n,r,i]=u.toChannels(e.rgba),{css:o.toCss(n,r,i,a),rgba:o.toRgba(n,r,i,a)}}e.blend=function(e,t){if(a=(255&t.rgba)/255,a===1)return{css:t.css,rgba:t.rgba};let s=t.rgba>>24&255,c=t.rgba>>16&255,l=t.rgba>>8&255,u=e.rgba>>24&255,d=e.rgba>>16&255,f=e.rgba>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),{css:o.toCss(n,r,i),rgba:o.toRgba(n,r,i)}},e.isOpaque=function(e){return(255&e.rgba)==255},e.ensureContrastRatio=function(e,t,n){let r=u.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return o.toColor(r>>24&255,r>>16&255,r>>8&255)},e.opaque=function(e){let t=(255|e.rgba)>>>0;return[n,r,i]=u.toChannels(t),{css:o.toCss(n,r,i),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,n){return a=255&e.rgba,t(e,a*n/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}}(s||(t.color=s={})),function(e){let t,s;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let n=e.getContext(`2d`,{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation=`copy`,s=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),o.toColor(n,r,i);case 5:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),a=parseInt(e.slice(4,5).repeat(2),16),o.toColor(n,r,i,a);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let c=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(c)return n=parseInt(c[1]),r=parseInt(c[2]),i=parseInt(c[3]),a=Math.round(255*(c[5]===void 0?1:parseFloat(c[5]))),o.toColor(n,r,i,a);if(!t||!s||(t.fillStyle=s,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[n,r,i,a]=t.getImageData(0,0,1,1).data,a!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:o.toRgba(n,r,i,a),css:e}}}(c||(t.css=c={})),function(e){function t(e,t,n){let r=e/255,i=t/255,a=n/255;return .2126*(r<=.03928?r/12.92:((r+.055)/1.055)**2.4)+.7152*(i<=.03928?i/12.92:((i+.055)/1.055)**2.4)+.0722*(a<=.03928?a/12.92:((a+.055)/1.055)**2.4)}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(l||(t.rgb=l={})),function(e){function t(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(.1*o)),s-=Math.max(0,Math.ceil(.1*s)),c-=Math.max(0,Math.ceil(.1*c)),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}function s(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil(.1*(255-o))),s=Math.min(255,s+Math.ceil(.1*(255-s))),c=Math.min(255,c+Math.ceil(.1*(255-c))),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.blend=function(e,t){if(a=(255&t)/255,a===1)return t;let s=t>>24&255,c=t>>16&255,l=t>>8&255,u=e>>24&255,d=e>>16&255,f=e>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),o.toRgba(n,r,i)},e.ensureContrastRatio=function(e,n,r){let i=l.relativeLuminance(e>>8),a=l.relativeLuminance(n>>8);if(f(i,a)<r){if(a<i){let a=t(e,n,r),o=f(i,l.relativeLuminance(a>>8));if(o<r){let t=s(e,n,r);return o>f(i,l.relativeLuminance(t>>8))?a:t}return a}let o=s(e,n,r),c=f(i,l.relativeLuminance(o>>8));if(c<r){let a=t(e,n,r);return c>f(i,l.relativeLuminance(a>>8))?o:a}return o}},e.reduceLuminance=t,e.increaseLuminance=s,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}}(u||(t.rgba=u={})),t.toPaddedHex=d,t.contrastRatio=f},345:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed){for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}}}),this._event}fire(e,t){let n=[];for(let e=0;e<this._listeners.length;e++)n.push(this._listeners[e]);for(let r=0;r<n.length;r++)n[r].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},859:(e,t)=>{function n(e){for(let t of e)t.dispose();e.length=0}Object.defineProperty(t,`__esModule`,{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){let t=this._disposables.indexOf(e);t!==-1&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=n,t.getDisposeArrayDisposable=function(e){return{dispose:()=>n(e)}}},485:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class n{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}}t.TwoKeyMap=n,t.FourKeyMap=class{constructor(){this._data=new n}set(e,t,r,i,a){this._data.get(e,t)||this._data.set(e,t,new n),this._data.get(e,t).set(r,i,a)}get(e,t,n,r){return this._data.get(e,t)?.get(n,r)}clear(){this._data.clear()}}},726:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;let n=`di$target`,r=`di$dependencies`;t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[r]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);let i=function(e,t,a){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);(function(e,t,i){t[n]===t?t[r].push({id:e,index:i}):(t[r]=[{id:e,index:i}],t[n]=t)})(i,e,a)};return i.toString=()=>e,t.serviceRegistry.set(e,i),i}},97:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;let r=n(726);var i;t.IBufferService=(0,r.createDecorator)(`BufferService`),t.ICoreMouseService=(0,r.createDecorator)(`CoreMouseService`),t.ICoreService=(0,r.createDecorator)(`CoreService`),t.ICharsetService=(0,r.createDecorator)(`CharsetService`),t.IInstantiationService=(0,r.createDecorator)(`InstantiationService`),function(e){e[e.TRACE=0]=`TRACE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARN=3]=`WARN`,e[e.ERROR=4]=`ERROR`,e[e.OFF=5]=`OFF`}(i||(t.LogLevelEnum=i={})),t.ILogService=(0,r.createDecorator)(`LogService`),t.IOptionsService=(0,r.createDecorator)(`OptionsService`),t.IOscLinkService=(0,r.createDecorator)(`OscLinkService`),t.IUnicodeService=(0,r.createDecorator)(`UnicodeService`),t.IDecorationService=(0,r.createDecorator)(`DecorationService`)}},t={};function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}var r={};return(()=>{var e=r;Object.defineProperty(e,`__esModule`,{value:!0}),e.HTMLSerializeHandler=e.SerializeAddon=void 0;let t=n(997);function i(e,t,n){return Math.max(t,Math.min(e,n))}class a{constructor(e){this._buffer=e}serialize(e,t){let n=this._buffer.getNullCell(),r=this._buffer.getNullCell(),i=n,a=e.start.y,o=e.end.y,s=e.start.x,c=e.end.x;this._beforeSerialize(o-a,a,o);for(let t=a;t<=o;t++){let a=this._buffer.getLine(t);if(a){let o=t===e.start.y?s:0,l=t===e.end.y?c:a.length;for(let e=o;e<l;e++){let o=a.getCell(e,i===n?r:n);o?(this._nextCell(o,i,t,e),i=o):console.warn(`Can't get cell at row=${t}, col=${e}`)}}this._rowEnd(t,t===o)}return this._afterSerialize(),this._serializeString(t)}_nextCell(e,t,n,r){}_rowEnd(e,t){}_beforeSerialize(e,t,n){}_afterSerialize(){}_serializeString(e){return``}}function o(e,t){return e.getFgColorMode()===t.getFgColorMode()&&e.getFgColor()===t.getFgColor()}function s(e,t){return e.getBgColorMode()===t.getBgColorMode()&&e.getBgColor()===t.getBgColor()}function c(e,t){return e.isInverse()===t.isInverse()&&e.isBold()===t.isBold()&&e.isUnderline()===t.isUnderline()&&e.isOverline()===t.isOverline()&&e.isBlink()===t.isBlink()&&e.isInvisible()===t.isInvisible()&&e.isItalic()===t.isItalic()&&e.isDim()===t.isDim()&&e.isStrikethrough()===t.isStrikethrough()}class l extends a{constructor(e,t){super(e),this._terminal=t,this._rowIndex=0,this._allRows=[],this._allRowSeparators=[],this._currentRow=``,this._nullCellCount=0,this._cursorStyle=this._buffer.getNullCell(),this._cursorStyleRow=0,this._cursorStyleCol=0,this._backgroundCell=this._buffer.getNullCell(),this._firstRow=0,this._lastCursorRow=0,this._lastCursorCol=0,this._lastContentCursorRow=0,this._lastContentCursorCol=0,this._thisRowLastChar=this._buffer.getNullCell(),this._thisRowLastSecondChar=this._buffer.getNullCell(),this._nextRowFirstChar=this._buffer.getNullCell()}_beforeSerialize(e,t,n){this._allRows=Array(e),this._lastContentCursorRow=t,this._lastCursorRow=t,this._firstRow=t}_rowEnd(e,t){this._nullCellCount>0&&!s(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`[${this._nullCellCount}X`);let n=``;if(!t){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let t=this._buffer.getLine(e),r=this._buffer.getLine(e+1);if(r.isWrapped){n=``;let i=t.getCell(t.length-1,this._thisRowLastChar),a=t.getCell(t.length-2,this._thisRowLastSecondChar),o=r.getCell(0,this._nextRowFirstChar),c=o.getWidth()>1,l=!1;(o.getChars()&&c?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&s(i,o)&&(l=!0),c&&(a.getChars()||a.getWidth()===0)&&s(i,o)&&s(a,o)&&(l=!0)),l||(n=`-`.repeat(this._nullCellCount+1),n+=`\x1B[1D\x1B[1X`,this._nullCellCount>0&&(n+=`\x1B[A`,n+=`[${t.length-this._nullCellCount}C`,n+=`[${this._nullCellCount}X`,n+=`[${t.length-this._nullCellCount}D`,n+=`\x1B[B`),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}else n=`\r
|
|
32
|
-
`,this._lastCursorRow=e+1,this._lastCursorCol=0}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=n,this._currentRow=``,this._nullCellCount=0}_diffStyle(e,t){let n=[],r=!o(e,t),i=!s(e,t),a=!c(e,t);if(r||i||a)if(e.isAttributeDefault())t.isAttributeDefault()||n.push(0);else{if(r){let t=e.getFgColor();e.isFgRGB()?n.push(38,2,t>>>16&255,t>>>8&255,255&t):e.isFgPalette()?t>=16?n.push(38,5,t):n.push(8&t?90+(7&t):30+(7&t)):n.push(39)}if(i){let t=e.getBgColor();e.isBgRGB()?n.push(48,2,t>>>16&255,t>>>8&255,255&t):e.isBgPalette()?t>=16?n.push(48,5,t):n.push(8&t?100+(7&t):40+(7&t)):n.push(49)}a&&(e.isInverse()!==t.isInverse()&&n.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&n.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&n.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&n.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&n.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&n.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&n.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&n.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&n.push(e.isStrikethrough()?9:29))}return n}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,this._cursorStyle);if(i?!s(this._cursorStyle,e):a.length>0){this._nullCellCount>0&&(s(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r,this._currentRow+=`[${a.join(`;`)}m`;let e=this._buffer.getLine(n);e!==void 0&&(e.getCell(r,this._cursorStyle),this._cursorStyleRow=n,this._cursorStyleCol=r)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(s(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let n=``;for(let e=0;e<t;e++)n+=this._allRows[e],e+1<t&&(n+=this._allRowSeparators[e]);if(!e){let e=this._buffer.baseY+this._buffer.cursorY,t=this._buffer.cursorX;(e!==this._lastCursorRow||t!==this._lastCursorCol)&&((r=e-this._lastCursorRow)>0?n+=`[${r}B`:r<0&&(n+=`[${-r}A`),(e=>{e>0?n+=`[${e}C`:e<0&&(n+=`[${-e}D`)})(t-this._lastCursorCol))}var r;let i=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(i,this._cursorStyle);return a.length>0&&(n+=`[${a.join(`;`)}m`),n}}e.SerializeAddon=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,n){let r=t.length,a=n===void 0?r:i(n+e.rows,0,r);return this._serializeBufferByRange(e,t,{start:r-a,end:r-1},!1)}_serializeBufferByRange(e,t,n,r){return new l(t,e).serialize({start:{x:0,y:typeof n.start==`number`?n.start:n.start.line},end:{x:e.cols,y:typeof n.end==`number`?n.end:n.end.line}},r)}_serializeBufferAsHTML(e,t){let n=e.buffer.active,r=new u(n,e,t);if(!t.onlySelection){let a=n.length,o=t.scrollback,s=o===void 0?a:i(o+e.rows,0,a);return r.serialize({start:{x:0,y:a-s},end:{x:e.cols,y:a-1}})}let a=this._terminal?.getSelectionPosition();return a===void 0?``:r.serialize({start:{x:a.start.x,y:a.start.y},end:{x:a.end.x,y:a.end.y}})}_serializeModes(e){let t=``,n=e.modes;if(n.applicationCursorKeysMode&&(t+=`\x1B[?1h`),n.applicationKeypadMode&&(t+=`\x1B[?66h`),n.bracketedPasteMode&&(t+=`\x1B[?2004h`),n.insertMode&&(t+=`\x1B[4h`),n.originMode&&(t+=`\x1B[?6h`),n.reverseWraparoundMode&&(t+=`\x1B[?45h`),n.sendFocusMode&&(t+=`\x1B[?1004h`),!1===n.wraparoundMode&&(t+=`\x1B[?7l`),n.mouseTrackingMode!==`none`)switch(n.mouseTrackingMode){case`x10`:t+=`\x1B[?9h`;break;case`vt200`:t+=`\x1B[?1000h`;break;case`drag`:t+=`\x1B[?1002h`;break;case`any`:t+=`\x1B[?1003h`}return t}serialize(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);let t=e?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e?.scrollback);return e?.excludeAltBuffer||this._terminal.buffer.active.type!==`alternate`||(t+=`[?1049h[H${this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0)}`),e?.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}};class u extends a{constructor(e,n,r){super(e),this._terminal=n,this._options=r,this._currentRow=``,this._htmlContent=``,n._core._themeService?this._ansiColors=n._core._themeService.colors.ansi:this._ansiColors=t.DEFAULT_ANSI_COLORS}_padStart(e,t,n){return t>>=0,n??=` `,e.length>t?e:((t-=e.length)>n.length&&(n+=n.repeat(t/n.length)),n.slice(0,t)+e)}_beforeSerialize(e,t,n){this._htmlContent+=`<html><body><!--StartFragment--><pre>`;let r=`#000000`,i=`#ffffff`;this._options.includeGlobalBackground&&(r=this._terminal.options.theme?.foreground??`#ffffff`,i=this._terminal.options.theme?.background??`#000000`);let a=[];a.push(`color: `+r+`;`),a.push(`background-color: `+i+`;`),a.push(`font-family: `+this._terminal.options.fontFamily+`;`),a.push(`font-size: `+this._terminal.options.fontSize+`px;`),this._htmlContent+=`<div style='`+a.join(` `)+`'>`}_afterSerialize(){this._htmlContent+=`</div>`,this._htmlContent+=`</pre><!--EndFragment--></body></html>`}_rowEnd(e,t){this._htmlContent+=`<div><span>`+this._currentRow+`</span></div>`,this._currentRow=``}_getHexColor(e,t){let n=t?e.getFgColor():e.getBgColor();return(t?e.isFgRGB():e.isBgRGB())?`#`+[n>>16&255,n>>8&255,255&n].map((e=>this._padStart(e.toString(16),2,`0`))).join(``):(t?e.isFgPalette():e.isBgPalette())?this._ansiColors[n].css:void 0}_diffStyle(e,t){let n=[],r=!o(e,t),i=!s(e,t),a=!c(e,t);if(r||i||a){let t=this._getHexColor(e,!0);t&&n.push(`color: `+t+`;`);let r=this._getHexColor(e,!1);return r&&n.push(`background-color: `+r+`;`),e.isInverse()&&n.push(`color: #000000; background-color: #BFBFBF;`),e.isBold()&&n.push(`font-weight: bold;`),e.isUnderline()&&e.isOverline()?n.push(`text-decoration: overline underline;`):e.isUnderline()?n.push(`text-decoration: underline;`):e.isOverline()&&n.push(`text-decoration: overline;`),e.isBlink()&&n.push(`text-decoration: blink;`),e.isInvisible()&&n.push(`visibility: hidden;`),e.isItalic()&&n.push(`font-style: italic;`),e.isDim()&&n.push(`opacity: 0.5;`),e.isStrikethrough()&&n.push(`text-decoration: line-through;`),n}}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,t);a&&(this._currentRow+=a.length===0?`</span><span>`:`</span><span style='`+a.join(` `)+`'>`),this._currentRow+=i?` `:e.getChars()}_serializeString(){return this._htmlContent}}e.HTMLSerializeHandler=u})(),r})()))})}),vt=a.__commonJS({"../../node_modules/@xterm/headless/lib-headless/xterm-headless.js":(e=>{(()=>{var t={349:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CircularList=void 0;let r=n(460),i=n(844);class a extends i.Disposable{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this.register(new r.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new r.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new r.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}}t.CircularList=a},439:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.clone=void 0,t.clone=function e(t,n=5){if(typeof t!=`object`)return t;let r=Array.isArray(t)?[]:{};for(let i in t)r[i]=n<=1?t[i]:t[i]&&e(t[i],n-1);return r}},969:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreTerminal=void 0;let r=n(844),i=n(585),a=n(348),o=n(866),s=n(744),c=n(302),l=n(83),u=n(460),d=n(753),f=n(480),p=n(994),m=n(282),h=n(435),g=n(981),_=n(660),v=!1;class y extends r.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new u.EventEmitter),this._onScroll.event((e=>{this._onScrollApi?.fire(e.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}constructor(e){super(),this._windowsWrappingHeuristics=this.register(new r.MutableDisposable),this._onBinary=this.register(new u.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new u.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new u.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new u.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new u.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new u.EventEmitter),this._instantiationService=new a.InstantiationService,this.optionsService=this.register(new c.OptionsService(e)),this._instantiationService.setService(i.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(s.BufferService)),this._instantiationService.setService(i.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(o.LogService)),this._instantiationService.setService(i.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(l.CoreService)),this._instantiationService.setService(i.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(d.CoreMouseService)),this._instantiationService.setService(i.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(f.UnicodeService)),this._instantiationService.setService(i.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(p.CharsetService),this._instantiationService.setService(i.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_.OscLinkService),this._instantiationService.setService(i.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new h.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,u.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,u.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,u.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,u.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new g.WriteBuffer(((e,t)=>this._inputHandler.parse(e,t)))),this.register((0,u.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=i.LogLevelEnum.WARN&&!v&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),v=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,s.MINIMUM_COLS),t=Math.max(t,s.MINIMUM_ROWS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t,n){this._bufferService.scrollLines(e,t,n)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(m.updateWindowsModeWrappedState.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},(()=>((0,m.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,r.toDisposable)((()=>{for(let t of e)t.dispose()}))}}}t.CoreTerminal=y},460:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed){for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}}}),this._event}fire(e,t){let n=[];for(let e=0;e<this._listeners.length;e++)n.push(this._listeners[e]);for(let r=0;r<n.length;r++)n[r].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},435:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0;let a=n(584),o=n(116),s=n(15),c=n(844),l=n(482),u=n(437),d=n(460),f=n(643),p=n(511),m=n(734),h=n(585),g=n(480),_=n(242),v=n(351),y=n(941),b={"(":0,")":1,"*":2,"+":3,"-":1,".":2},x=131072;function S(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var C;(function(e){e[e.GET_WIN_SIZE_PIXELS=0]=`GET_WIN_SIZE_PIXELS`,e[e.GET_CELL_SIZE_PIXELS=1]=`GET_CELL_SIZE_PIXELS`})(C||(t.WindowsOptionsReportType=C={}));let w=0;class T extends c.Disposable{getAttrData(){return this._curAttrData}constructor(e,t,n,r,i,c,f,m,h=new s.EscapeSequenceParser){for(let s in super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=c,this._coreMouseService=f,this._unicodeService=m,this._parser=h,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new l.StringToUtf32,this._utf8Decoder=new l.Utf8ToUtf32,this._workCell=new p.CellData,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new d.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new d.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new d.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new d.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new d.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new d.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new d.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new d.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new d.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new d.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new d.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new d.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new E(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._parser.setCsiHandlerFallback(((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})})),this._parser.setEscHandlerFallback((e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})})),this._parser.setExecuteHandlerFallback((e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})})),this._parser.setOscHandlerFallback(((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})})),this._parser.setDcsHandlerFallback(((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})})),this._parser.setPrintHandler(((e,t,n)=>this.print(e,t,n))),this._parser.registerCsiHandler({final:`@`},(e=>this.insertChars(e))),this._parser.registerCsiHandler({intermediates:` `,final:`@`},(e=>this.scrollLeft(e))),this._parser.registerCsiHandler({final:`A`},(e=>this.cursorUp(e))),this._parser.registerCsiHandler({intermediates:` `,final:`A`},(e=>this.scrollRight(e))),this._parser.registerCsiHandler({final:`B`},(e=>this.cursorDown(e))),this._parser.registerCsiHandler({final:`C`},(e=>this.cursorForward(e))),this._parser.registerCsiHandler({final:`D`},(e=>this.cursorBackward(e))),this._parser.registerCsiHandler({final:`E`},(e=>this.cursorNextLine(e))),this._parser.registerCsiHandler({final:`F`},(e=>this.cursorPrecedingLine(e))),this._parser.registerCsiHandler({final:`G`},(e=>this.cursorCharAbsolute(e))),this._parser.registerCsiHandler({final:`H`},(e=>this.cursorPosition(e))),this._parser.registerCsiHandler({final:`I`},(e=>this.cursorForwardTab(e))),this._parser.registerCsiHandler({final:`J`},(e=>this.eraseInDisplay(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`J`},(e=>this.eraseInDisplay(e,!0))),this._parser.registerCsiHandler({final:`K`},(e=>this.eraseInLine(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`K`},(e=>this.eraseInLine(e,!0))),this._parser.registerCsiHandler({final:`L`},(e=>this.insertLines(e))),this._parser.registerCsiHandler({final:`M`},(e=>this.deleteLines(e))),this._parser.registerCsiHandler({final:`P`},(e=>this.deleteChars(e))),this._parser.registerCsiHandler({final:`S`},(e=>this.scrollUp(e))),this._parser.registerCsiHandler({final:`T`},(e=>this.scrollDown(e))),this._parser.registerCsiHandler({final:`X`},(e=>this.eraseChars(e))),this._parser.registerCsiHandler({final:`Z`},(e=>this.cursorBackwardTab(e))),this._parser.registerCsiHandler({final:"`"},(e=>this.charPosAbsolute(e))),this._parser.registerCsiHandler({final:`a`},(e=>this.hPositionRelative(e))),this._parser.registerCsiHandler({final:`b`},(e=>this.repeatPrecedingCharacter(e))),this._parser.registerCsiHandler({final:`c`},(e=>this.sendDeviceAttributesPrimary(e))),this._parser.registerCsiHandler({prefix:`>`,final:`c`},(e=>this.sendDeviceAttributesSecondary(e))),this._parser.registerCsiHandler({final:`d`},(e=>this.linePosAbsolute(e))),this._parser.registerCsiHandler({final:`e`},(e=>this.vPositionRelative(e))),this._parser.registerCsiHandler({final:`f`},(e=>this.hVPosition(e))),this._parser.registerCsiHandler({final:`g`},(e=>this.tabClear(e))),this._parser.registerCsiHandler({final:`h`},(e=>this.setMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`h`},(e=>this.setModePrivate(e))),this._parser.registerCsiHandler({final:`l`},(e=>this.resetMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`l`},(e=>this.resetModePrivate(e))),this._parser.registerCsiHandler({final:`m`},(e=>this.charAttributes(e))),this._parser.registerCsiHandler({final:`n`},(e=>this.deviceStatus(e))),this._parser.registerCsiHandler({prefix:`?`,final:`n`},(e=>this.deviceStatusPrivate(e))),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},(e=>this.softReset(e))),this._parser.registerCsiHandler({intermediates:` `,final:`q`},(e=>this.setCursorStyle(e))),this._parser.registerCsiHandler({final:`r`},(e=>this.setScrollRegion(e))),this._parser.registerCsiHandler({final:`s`},(e=>this.saveCursor(e))),this._parser.registerCsiHandler({final:`t`},(e=>this.windowOptions(e))),this._parser.registerCsiHandler({final:`u`},(e=>this.restoreCursor(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},(e=>this.insertColumns(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},(e=>this.deleteColumns(e))),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},(e=>this.selectProtected(e))),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},(e=>this.requestMode(e,!0))),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},(e=>this.requestMode(e,!1))),this._parser.setExecuteHandler(a.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(a.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(a.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(a.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(a.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(a.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(a.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(a.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(a.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new _.OscHandler((e=>(this.setTitle(e),this.setIconName(e),!0)))),this._parser.registerOscHandler(1,new _.OscHandler((e=>this.setIconName(e)))),this._parser.registerOscHandler(2,new _.OscHandler((e=>this.setTitle(e)))),this._parser.registerOscHandler(4,new _.OscHandler((e=>this.setOrReportIndexedColor(e)))),this._parser.registerOscHandler(8,new _.OscHandler((e=>this.setHyperlink(e)))),this._parser.registerOscHandler(10,new _.OscHandler((e=>this.setOrReportFgColor(e)))),this._parser.registerOscHandler(11,new _.OscHandler((e=>this.setOrReportBgColor(e)))),this._parser.registerOscHandler(12,new _.OscHandler((e=>this.setOrReportCursorColor(e)))),this._parser.registerOscHandler(104,new _.OscHandler((e=>this.restoreIndexedColor(e)))),this._parser.registerOscHandler(110,new _.OscHandler((e=>this.restoreFgColor(e)))),this._parser.registerOscHandler(111,new _.OscHandler((e=>this.restoreBgColor(e)))),this._parser.registerOscHandler(112,new _.OscHandler((e=>this.restoreCursorColor(e)))),this._parser.registerEscHandler({final:`7`},(()=>this.saveCursor())),this._parser.registerEscHandler({final:`8`},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:`D`},(()=>this.index())),this._parser.registerEscHandler({final:`E`},(()=>this.nextLine())),this._parser.registerEscHandler({final:`H`},(()=>this.tabSet())),this._parser.registerEscHandler({final:`M`},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:`=`},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:`>`},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:`c`},(()=>this.fullReset())),this._parser.registerEscHandler({final:`n`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`o`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`|`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`}`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`~`},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:`%`,final:`@`},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:`%`,final:`G`},(()=>this.selectDefaultCharset())),o.CHARSETS)this._parser.registerEscHandler({intermediates:`(`,final:s},(()=>this.selectCharset(`(`+s))),this._parser.registerEscHandler({intermediates:`)`,final:s},(()=>this.selectCharset(`)`+s))),this._parser.registerEscHandler({intermediates:`*`,final:s},(()=>this.selectCharset(`*`+s))),this._parser.registerEscHandler({intermediates:`+`,final:s},(()=>this.selectCharset(`+`+s))),this._parser.registerEscHandler({intermediates:`-`,final:s},(()=>this.selectCharset(`-`+s))),this._parser.registerEscHandler({intermediates:`.`,final:s},(()=>this.selectCharset(`.`+s))),this._parser.registerEscHandler({intermediates:`/`,final:s},(()=>this.selectCharset(`/`+s)));this._parser.registerEscHandler({intermediates:`#`,final:`8`},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((e=>(this._logService.error(`Parsing error: `,e),e))),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new v.DcsHandler(((e,t)=>this.requestStatusString(e,t))))}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=h.LogLevelEnum.WARN&&Promise.race([e,new Promise(((e,t)=>setTimeout((()=>t(`#SLOW_TIMEOUT`)),5e3)))]).catch((e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than 5000 ms`)}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>x&&(a=this._parseStack.position+x)}if(this._logService.logLevel<=h.LogLevelEnum.DEBUG&&this._logService.debug(`parsing data`+(typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,(e=>String.fromCharCode(e))).join(``)}"`),typeof e==`string`?e.split(``).map((e=>e.charCodeAt(0))):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<x&&(this._parseBuffer=new Uint32Array(Math.min(e.length,x))),o||this._dirtyRowTracker.clearRange(),e.length>x)for(let t=a;t<e.length;t+=x){let a=t+x<e.length?t+x:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}this._activeBuffer.x===r&&this._activeBuffer.y===i||this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(c,this._bufferService.rows-1),Math.min(s,this._bufferService.rows-1))}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,d=this._coreService.modes.insertMode,p=this._curAttrData,m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&m.getWidth(this._activeBuffer.x-1)===2&&m.setCellFromCodepoint(this._activeBuffer.x-1,0,1,p);let h=this._parser.precedingJoinState;for(let _=t;_<n;++_){if(r=e[_],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,h);i=g.UnicodeService.extractWidth(t);let n=g.UnicodeService.extractShouldJoin(t),v=n?g.UnicodeService.extractWidth(h):0;if(h=t,o&&this._onA11yChar.fire((0,l.stringFromCodePoint)(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-v>s){if(c){let e=m,t=this._activeBuffer.x-v;for(this._activeBuffer.x=v,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),v>0&&m instanceof u.BufferLine&&m.copyCellsFrom(e,t,0,v,!1);t<s;)e.setCellFromCodepoint(t++,0,1,p)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=m.getWidth(this._activeBuffer.x-1)?1:2;m.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-v;--e>=0;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}else if(d&&(m.insertCells(this._activeBuffer.x,i-v,this._activeBuffer.getNullCell(p)),m.getWidth(s-1)===2&&m.setCellFromCodepoint(s-1,f.NULL_CELL_CODE,f.NULL_CELL_WIDTH,p)),m.setCellFromCodepoint(this._activeBuffer.x++,r,i,p),i>0)for(;--i;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}this._parser.precedingJoinState=h,this._activeBuffer.x<s&&n-t>0&&m.getWidth(this._activeBuffer.x)===0&&!m.hasContent(this._activeBuffer.x)&&m.setCellFromCodepoint(this._activeBuffer.x,0,1,p),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final!==`t`||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,(e=>!S(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new v.DcsHandler(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new _.OscHandler(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),t!==2&&t!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){let n;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(u.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=g.UnicodeService.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(a.C0.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),this._charsetService.setgCharset(1,o.DEFAULT_CHARSET),this._charsetService.setgCharset(2,o.DEFAULT_CHARSET),this._charsetService.setgCharset(3,o.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(e,t){let n=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:i}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=e=>e?1:2,p=e.params[0];return m=p,h=t?p===2?4:p===4?f(o.modes.insertMode):p===12?3:p===20?f(d.convertEol):0:p===1?f(n.applicationCursorKeys):p===3?d.windowOptions.setWinLines?c===80?2:c===132?1:0:0:p===6?f(n.origin):p===7?f(n.wraparound):p===8?3:p===9?f(r===`X10`):p===12?f(d.cursorBlink):p===25?f(!o.isCursorHidden):p===45?f(n.reverseWraparound):p===66?f(n.applicationKeypad):p===67?4:p===1e3?f(r===`VT200`):p===1002?f(r===`DRAG`):p===1003?f(r===`ANY`):p===1004?f(n.sendFocus):p===1005?4:p===1006?f(i===`SGR`):p===1015?4:p===1016?f(i===`SGR_PIXELS`):p===1048?1:p===47||p===1047||p===1049?f(l===u):p===2004?f(n.bracketedPasteMode):0,o.triggerDataEvent(`${a.C0.ESC}[${t?``:`?`}${m};${h}$y`),!0;var m,h}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=m.AttributeData.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|255&n),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=u.DEFAULT_ATTR_DATA.fg,e.bg=u.DEFAULT_ATTR_DATA.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777224|n-90):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777224|n-100):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg):n===49?(r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg,r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${a.C0.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle=`block`;break;case 3:case 4:this._optionsService.options.cursorStyle=`underline`;break;case 5:case 6:this._optionsService.options.cursorStyle=`bar`}let n=t%2==1;return this._optionsService.options.cursorBlink=n,!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!S(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(C.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(C.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${a.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:t!==0&&t!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),t!==0&&t!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:t!==0&&t!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),t!==0&&t!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(D(n))if(r===`?`)t.push({type:0,index:n});else{let e=(0,y.parseColor)(r);e&&t.push({type:1,index:n,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.split(`;`);return!(t.length<2)&&(t[1]?this._createHyperlink(t[0],t[1]):!t[0]&&this._finishHyperlink())}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex((e=>e.startsWith(`id=`)));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=(0,y.parseColor)(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);D(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(b[e[0]],o.CHARSETS[e[1]]||o.DEFAULT_CHARSET),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new p.CellData;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=this._bufferService.buffer,r=this._optionsService.rawOptions;return(e=>(this._coreService.triggerDataEvent(`${a.C0.ESC}${e}${a.C0.ESC}\\`),!0))(e===`"q`?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}}t.InputHandler=T;let E=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(w=e,e=t,t=w),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function D(e){return 0<=e&&e<256}E=r([i(0,h.IBufferService)],E)},844:(e,t)=>{function n(e){for(let t of e)t.dispose();e.length=0}Object.defineProperty(t,`__esModule`,{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){let t=this._disposables.indexOf(e);t!==-1&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=n,t.getDisposeArrayDisposable=function(e){return{dispose:()=>n(e)}}},114:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.getSafariVersion=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.isNode=typeof process<`u`&&`title`in process;let n=t.isNode?`node`:navigator.userAgent,r=t.isNode?`node`:navigator.platform;t.isFirefox=n.includes(`Firefox`),t.isLegacyEdge=n.includes(`Edge`),t.isSafari=/^((?!chrome|android).)*safari/i.test(n),t.getSafariVersion=function(){if(!t.isSafari)return 0;let e=n.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])},t.isMac=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(r),t.isIpad=r===`iPad`,t.isIphone=r===`iPhone`,t.isWindows=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(r),t.isLinux=r.indexOf(`Linux`)>=0,t.isChromeOS=/\bCrOS\b/.test(n)},226:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;let r=n(114);class i{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=Date.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,Date.now()-t),n=Math.max(t,n),i=e.timeRemaining(),1.5*n>i)return r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),void this._start();r=i}this.clear()}}class a extends i{_requestCallback(e){return setTimeout((()=>e(this._createDeadline(16))))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=Date.now()+e;return{timeRemaining:()=>Math.max(0,t-Date.now())}}}t.PriorityTaskQueue=a,t.IdleTaskQueue=!r.isNode&&`requestIdleCallback`in window?class extends i{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:a,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}}},282:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.updateWindowsModeWrappedState=void 0;let r=n(643);t.updateWindowsModeWrappedState=function(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[r.CHAR_DATA_CODE_INDEX]!==r.NULL_CELL_CODE&&t[r.CHAR_DATA_CODE_INDEX]!==r.WHITESPACE_CELL_CODE)}},734:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class n{constructor(){this.fg=0,this.bg=0,this.extended=new r}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){let e=new n;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t.AttributeData=n;class r{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new r(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}t.ExtendedAttrs=r},92:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;let r=n(349),i=n(226),a=n(734),o=n(437),s=n(634),c=n(511),l=n(643),u=n(863),d=n(116);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o.DEFAULT_ATTR_DATA.clone(),this.savedCharset=d.DEFAULT_CHARSET,this.markers=[],this._nullCell=c.CellData.fromCharData([0,l.NULL_CELL_CHAR,l.NULL_CELL_WIDTH,l.NULL_CELL_CODE]),this._whitespaceCell=c.CellData.fromCharData([0,l.WHITESPACE_CELL_CHAR,l.WHITESPACE_CELL_WIDTH,l.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new i.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new a.ExtendedAttrs),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new a.ExtendedAttrs),this._whitespaceCell}getBlankLine(e,t){return new o.BufferLine(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let n=e+this._optionsService.rawOptions.scrollback;return n>t.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:n}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=o.DEFAULT_ATTR_DATA);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new o.BufferLine(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new o.BufferLine(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=(0,s.reflowLargerGetLinesToRemove)(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(o.DEFAULT_ATTR_DATA));if(n.length>0){let r=(0,s.reflowLargerCreateNewLayout)(this.lines,n);(0,s.reflowLargerApplyNewLayout)(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(o.DEFAULT_ATTR_DATA),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new o.BufferLine(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=[],i=0;for(let a=this.lines.length-1;a>=0;a--){let c=this.lines.get(a);if(!c||!c.isWrapped&&c.getTrimmedLength()<=e)continue;let l=[c];for(;c.isWrapped&&a>0;)c=this.lines.get(--a),l.unshift(c);let u=this.ybase+this.y;if(u>=a&&u<a+l.length)continue;let d=l[l.length-1].getTrimmedLength(),f=(0,s.reflowSmallerGetNewLineLengths)(l,this._cols,e),p=f.length-l.length,m=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+p):Math.max(0,this.lines.length-this.lines.maxLength+p),h=[];for(let e=0;e<p;e++){let e=this.getBlankLine(o.DEFAULT_ATTR_DATA,!0);h.push(e)}h.length>0&&(r.push({start:a+l.length+i,newLines:h}),i+=h.length),l.push(...h);let g=f.length-1,_=f[g];_===0&&(g--,_=f[g]);let v=l.length-p-1,y=d;for(;v>=0;){let e=Math.min(y,_);if(l[g]===void 0)break;if(l[g].copyCellsFrom(l[v],y-e,_-e,e,!0),_-=e,_===0&&(g--,_=f[g]),y-=e,y===0){v--;let e=Math.max(v,0);y=(0,s.getWrappedLineTrimmedLength)(l,e,this._cols)}}for(let t=0;t<l.length;t++)f[t]<e&&l[t].setCell(f[t],n);let b=p-m;for(;b-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+i)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+p,this.ybase+t-1)}if(r.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,a=n-1,o=0,s=r[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+i);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+i-1);l>=0;l--)if(s&&s.start>a+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:a+1,amount:s.newLines.length}),c+=s.newLines.length,s=r[++o]}else this.lines.set(l,t[a--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+i-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose(),this.markers.splice(e--,1);this._isClearing=!1}addMarker(e){let t=new u.Marker(e);return this.markers.push(t),t.register(this.lines.onTrim((e=>{t.line-=e,t.line<0&&t.dispose()}))),t.register(this.lines.onInsert((e=>{t.line>=e.index&&(t.line+=e.amount)}))),t.register(this.lines.onDelete((e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)}))),t.register(t.onDispose((()=>this._removeMarker(t)))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}}},437:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;let r=n(734),i=n(511),a=n(643),o=n(482);t.DEFAULT_ATTR_DATA=Object.freeze(new r.AttributeData);let s=0;class c{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);let r=t||i.CellData.fromCharData([0,a.NULL_CELL_CHAR,a.NULL_CELL_WIDTH,a.NULL_CELL_CODE]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[3*e+0],n=2097151&t;return[this._data[3*e+1],2097152&t?this._combined[e]:n?(0,o.stringFromCodePoint)(n):``,t>>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[3*e+1]=t[a.CHAR_DATA_ATTR_INDEX],t[a.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[a.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e+0]=t[a.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[a.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?(0,o.stringFromCodePoint)(2097151&t):``}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return s=3*e,t.content=this._data[s+0],t.fg=this._data[s+1],t.bg=this._data[s+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,n,r){268435456&r.bg&&(this._extendedAttrs[e]=r.extended),this._data[3*e+0]=t|n<<22,this._data[3*e+1]=r.fg,this._data[3*e+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[3*e+0];2097152&r?this._combined[e]+=(0,o.stringFromCodePoint)(t):2097151&r?(this._combined[e]=(0,o.stringFromCodePoint)(2097151&r)+(0,o.stringFromCodePoint)(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[3*e+0]=r}insertCells(e,t,n){if((e%=this.length)&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new i.CellData;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new i.CellData;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)!==0||this.hasContent(e)||this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let n=3*e;if(e>this.length){if(this._data.buffer.byteLength>=4*n)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,4*n*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){for(let t in this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={},e._combined)this._combined[t]=e._combined[t];for(let t in this._extendedAttrs={},e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let e=new c(0);for(let t in e._data=new Uint32Array(this._data),e.length=this.length,this._combined)e._combined[t]=this._combined[t];for(let t in this._extendedAttrs)e._extendedAttrs[t]=this._extendedAttrs[t];return e.isWrapped=this.isWrapped,e}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[3*t+0],n=2097151&e,s=2097152&e?this._combined[t]:n?(0,o.stringFromCodePoint)(n):a.WHITESPACE_CELL_CHAR;if(i+=s,r)for(let e=0;e<s.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}}t.BufferLine=c},634:(e,t)=>{function n(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}Object.defineProperty(t,`__esModule`,{value:!0}),t.getWrappedLineTrimmedLength=t.reflowSmallerGetNewLineLengths=t.reflowLargerApplyNewLayout=t.reflowLargerCreateNewLayout=t.reflowLargerGetLinesToRemove=void 0,t.reflowLargerGetLinesToRemove=function(e,t,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(i>=s&&i<c){s+=u.length-1;continue}let d=0,f=n(u,d,t),p=1,m=0;for(;p<u.length;){let e=n(u,p,t),i=e-m,o=r-f,s=Math.min(i,o);u[d].copyCellsFrom(u[p],m,f,s,!1),f+=s,f===r&&(d++,f=0),m+=s,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(r-1)===2&&(u[d].copyCellsFrom(u[d-1],r-1,f++,1,!1),u[d-1].setCell(r-1,a))}u[d].replaceCells(f,r,a);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o},t.reflowLargerCreateNewLayout=function(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}},t.reflowLargerApplyNewLayout=function(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length},t.reflowSmallerGetNewLineLengths=function(e,t,r){let i=[],a=e.map(((r,i)=>n(e,i,t))).reduce(((e,t)=>e+t)),o=0,s=0,c=0;for(;c<a;){if(a-c<r){i.push(a-c);break}o+=r;let l=n(e,s,t);o>l&&(o-=l,s++);let u=e[s].getWidth(o-1)===2;u&&o--;let d=u?r-1:r;i.push(d),c+=d}return i},t.getWrappedLineTrimmedLength=n},295:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferSet=void 0;let r=n(460),i=n(844),a=n(92);class o extends i.Disposable{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this.register(new r.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange(`scrollback`,(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,(()=>this.setupTabStops())))}reset(){this._normal=new a.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new a.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}}t.BufferSet=o},511:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CellData=void 0;let r=n(482),i=n(643),a=n(734);class o extends a.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new a.ExtendedAttrs,this.combinedData=``}static fromCharData(e){let t=new o;return t.setFromCharData(e),t}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,r.stringFromCodePoint)(2097151&this.content):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[i.CHAR_DATA_ATTR_INDEX],this.bg=0;let t=!1;if(e[i.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(e[i.CHAR_DATA_CHAR_INDEX].length===2){let n=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=r&&r<=57343?this.content=1024*(n-55296)+r-56320+65536|e[i.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[i.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[i.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[i.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=o},643:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=256|t.DEFAULT_COLOR<<9,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR=``,t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=` `,t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},863:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Marker=void 0;let r=n(460),i=n(844);class a{get id(){return this._id}constructor(e){this.line=e,this.isDisposed=!1,this._disposables=[],this._id=a._nextId++,this._onDispose=this.register(new r.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,i.disposeArray)(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}}t.Marker=a,a._nextId=1},116:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:``,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},t.CHARSETS.A={"#":`£`},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},t.CHARSETS.C=t.CHARSETS[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},t.CHARSETS.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},t.CHARSETS.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},t.CHARSETS.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},t.CHARSETS.E=t.CHARSETS[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},t.CHARSETS.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},t.CHARSETS.H=t.CHARSETS[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`}},584:(e,t)=>{var n,r,i;Object.defineProperty(t,`__esModule`,{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,function(e){e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
|
|
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(`
|
|
30
|
+
`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})}),Ye=a.__commonJS({"../../node_modules/debug/src/index.js":((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=Ge():t.exports=Je()})});let Xe={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Ze={get(e){return z.get(e,6),{signature:B.get(e,0),compressedSize:B.get(e,8),uncompressedSize:B.get(e,12)}},len:16},Qe={get(e){let t=z.get(e,6);return{signature:B.get(e,0),minVersion:z.get(e,4),dataDescriptor:!!(t&8),compressedMethod:z.get(e,8),compressedSize:B.get(e,18),uncompressedSize:B.get(e,22),filenameLength:z.get(e,26),extraFieldLength:z.get(e,28),filename:null}},len:30},$e={get(e){return{signature:B.get(e,0),nrOfThisDisk:z.get(e,4),nrOfThisDiskWithTheStart:z.get(e,6),nrOfEntriesOnThisDisk:z.get(e,8),nrOfEntriesOfSize:z.get(e,10),sizeOfCd:B.get(e,12),offsetOfStartOfCd:B.get(e,16),zipFileCommentLength:z.get(e,20)}},len:22},et={get(e){let t=z.get(e,8);return{signature:B.get(e,0),minVersion:z.get(e,6),dataDescriptor:!!(t&8),compressedMethod:z.get(e,10),compressedSize:B.get(e,20),uncompressedSize:B.get(e,24),filenameLength:z.get(e,28),extraFieldLength:z.get(e,30),fileCommentLength:z.get(e,32),relativeOffsetOfLocalHeader:B.get(e,42),filename:null}},len:46};var tt=a.__toESM(Ye(),1);function nt(e){let t=new Uint8Array(B.len);return B.put(t,0,e),t}let rt=(0,tt.default)(`tokenizer:inflate`),it=256*1024,at=nt(Xe.DataDescriptor),ot=nt(Xe.EndOfCentralDirectory);var st=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(it)}async isZip(){return await this.peekSignature()===Xe.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(B)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===ot[0]&&n[r+1]===ot[1]&&n[r+2]===ot[2]&&n[r+3]===ot[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){rt(`Cannot reading central-directory without random-read support`);return}rt(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){rt(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken($e,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(et);if(t.signature!==Xe.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new se(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),rt(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=it;rt(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===it;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=ct(this.syncBuffer.subarray(0,n),at);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}rt(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,lt(e),r.handler)}else r.handler?(rt(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(rt(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(rt(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(Ze)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Ze.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}inflate(e,t,n){if(e.compressedMethod===0)return n(t);rt(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let r=Ve(t);return n(r)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(B);if(e===Xe.LocalFileHeader){let e=await this.tokenizer.readToken(Qe);return e.filename=await this.tokenizer.readToken(new se(e.filenameLength,`utf-8`)),e}if(e===Xe.CentralFileHeader)return!1;throw e===3759263696?Error(`Encrypted ZIP`):Error(`Unexpected signature`)}};function ct(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function lt(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function ut(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function dt(e){return[...e].map(e=>e.charCodeAt(0))}function ft(e,t=0){let n=Number.parseInt(new se(6).get(e,148).replace(/\0.*$/,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}let pt={get:(e,t)=>e[t+3]&127|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},mt=4100;async function ht(e,t){return new vt(t).fromBuffer(e)}function gt(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function _t(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}var vt=class{constructor(e){this.detectConfident=async e=>{if(this.buffer=new Uint8Array(mt),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return{ext:`gz`,mime:`application/gzip`};if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await e.ignore(6);let t=await e.readToken(pt);return e.position+t>e.fileInfo.size?{ext:`mp3`,mime:`audio/mpeg`}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4])){let t;return await new st(e).unzip(e=>{switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return{async handler(e){let n=new TextDecoder(`utf-8`).decode(e).trim();t=gt(n)},stop:!0};case`[Content_Types].xml`:return{async handler(e){let n=new TextDecoder(`utf-8`).decode(e),r=n.indexOf(`.main+xml"`);if(r===-1){let e=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;n.includes(`ContentType="${e}"`)&&(t=gt(e))}else{n=n.slice(0,Math.max(0,r));let e=n.lastIndexOf(`"`),i=n.slice(Math.max(0,e+1));t=gt(i)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}}),t??{ext:`zip`,mime:`application/zip`}}if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),_t(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:_t(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:_t(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:_t(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:_t(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:_t(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/x-lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163])){async function t(){let t=await e.peekNumber(ne),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await e.readBuffer(i),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:ut(i),len:ut(a)}}async function r(t){for(;t>0;){let r=await n();if(r.id===17026)return(await e.readToken(new se(r.len))).replaceAll(/\00.*$/g,``);await e.ignore(r.len),--t}}let i=await n();switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:return}}if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(`{\\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190]))return{ext:`class`,mime:`application/java-vm`};if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/vnd.google.draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new se(4,`latin1`).get(this.buffer,2);if(e.match(`^d*`)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new se(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
|
|
31
|
+
`,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(ae),type:await e.readToken(new se(4,`latin1`))}}do{let n=await t();if(n.length<0)return;switch(n.type){case`IDAT`:return{ext:`png`,mime:`image/png`};case`acTL`:return{ext:`apng`,mime:`image/apng`};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:`png`,mime:`image/png`}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new se(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(oe))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),r=n.size-24;if(_t(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(r-=await e.readBuffer(t),_t(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(_t(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}await e.ignore(r)}return{ext:`asf`,mime:`application/vnd.ms-asf`}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new se(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x.ms.shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x.apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x.autodesk.fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&ft(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:`xml`,mime:`application/xml`}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:void 0;if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}},this.detectImprecise=async e=>{if(this.buffer=new Uint8Array(mt),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}},this.options={mpegOffsetTolerance:0,...e},this.detectors=[...e?.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let r=await n.detect(e);if(r)return r;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(j(t,this.tokenizerOptions))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){let t=await A(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=mt}=t,r,i,a=e.getReader({mode:`byob`});try{let{value:e,done:t}=await a.read(new Uint8Array(n));if(i=e,!t&&e)try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof b))throw e;r=void 0}i=e}finally{a.releaseLock()}let o=new TransformStream({async start(e){e.enqueue(i)},transform(e,t){t.enqueue(e)}}),s=e.pipeThrough(o);return s.fileType=r,s}check(e,t){return _t(this.buffer,e,t)}checkString(e,t){return this.check(dt(e),t)}async readTiffTag(e){let t=await this.tokenizer.readToken(e?re:z);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?re:z);for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t=(e?re:z).get(this.buffer,2),n=(e?ie:B).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(n>=8){let t=(e?re:z).get(this.buffer,8),n=(e?re:z).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:`tif`,mime:`image/tiff`}}if(t===43)return{ext:`tif`,mime:`image/tiff`}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}},yt=a.__commonJS({"../../node_modules/@xterm/addon-serialize/lib/addon-serialize.js":((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.SerializeAddon=r():n.SerializeAddon=r()})(e,(()=>(()=>{var e={930:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ColorContrastCache=void 0;let r=n(485);t.ColorContrastCache=class{constructor(){this._color=new r.TwoKeyMap,this._css=new r.TwoKeyMap}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}}},997:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.ThemeService=t.DEFAULT_ANSI_COLORS=void 0;let a=n(930),o=n(160),s=n(345),c=n(859),l=n(97),u=o.css.toColor(`#ffffff`),d=o.css.toColor(`#000000`),f=o.css.toColor(`#ffffff`),p=o.css.toColor(`#000000`),m={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117};t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{let e=[o.css.toColor(`#2e3436`),o.css.toColor(`#cc0000`),o.css.toColor(`#4e9a06`),o.css.toColor(`#c4a000`),o.css.toColor(`#3465a4`),o.css.toColor(`#75507b`),o.css.toColor(`#06989a`),o.css.toColor(`#d3d7cf`),o.css.toColor(`#555753`),o.css.toColor(`#ef2929`),o.css.toColor(`#8ae234`),o.css.toColor(`#fce94f`),o.css.toColor(`#729fcf`),o.css.toColor(`#ad7fa8`),o.css.toColor(`#34e2e2`),o.css.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:o.channels.toCss(r,i,a),rgba:o.channels.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+10*t;e.push({css:o.channels.toCss(n,n,n),rgba:o.channels.toRgba(n,n,n)})}return e})());let h=t.ThemeService=class extends c.Disposable{get colors(){return this._colors}constructor(e){super(),this._optionsService=e,this._contrastCache=new a.ColorContrastCache,this._halfContrastCache=new a.ColorContrastCache,this._onChangeColors=this.register(new s.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:u,background:d,cursor:f,cursorAccent:p,selectionForeground:void 0,selectionBackgroundTransparent:m,selectionBackgroundOpaque:o.color.blend(d,m),selectionInactiveBackgroundTransparent:m,selectionInactiveBackgroundOpaque:o.color.blend(d,m),ansi:t.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange(`theme`,(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(e={}){let n=this._colors;if(n.foreground=g(e.foreground,u),n.background=g(e.background,d),n.cursor=g(e.cursor,f),n.cursorAccent=g(e.cursorAccent,p),n.selectionBackgroundTransparent=g(e.selectionBackground,m),n.selectionBackgroundOpaque=o.color.blend(n.background,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundTransparent=g(e.selectionInactiveBackground,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundOpaque=o.color.blend(n.background,n.selectionInactiveBackgroundTransparent),n.selectionForeground=e.selectionForeground?g(e.selectionForeground,o.NULL_COLOR):void 0,n.selectionForeground===o.NULL_COLOR&&(n.selectionForeground=void 0),o.color.isOpaque(n.selectionBackgroundTransparent)&&(n.selectionBackgroundTransparent=o.color.opacity(n.selectionBackgroundTransparent,.3)),o.color.isOpaque(n.selectionInactiveBackgroundTransparent)&&(n.selectionInactiveBackgroundTransparent=o.color.opacity(n.selectionInactiveBackgroundTransparent,.3)),n.ansi=t.DEFAULT_ANSI_COLORS.slice(),n.ansi[0]=g(e.black,t.DEFAULT_ANSI_COLORS[0]),n.ansi[1]=g(e.red,t.DEFAULT_ANSI_COLORS[1]),n.ansi[2]=g(e.green,t.DEFAULT_ANSI_COLORS[2]),n.ansi[3]=g(e.yellow,t.DEFAULT_ANSI_COLORS[3]),n.ansi[4]=g(e.blue,t.DEFAULT_ANSI_COLORS[4]),n.ansi[5]=g(e.magenta,t.DEFAULT_ANSI_COLORS[5]),n.ansi[6]=g(e.cyan,t.DEFAULT_ANSI_COLORS[6]),n.ansi[7]=g(e.white,t.DEFAULT_ANSI_COLORS[7]),n.ansi[8]=g(e.brightBlack,t.DEFAULT_ANSI_COLORS[8]),n.ansi[9]=g(e.brightRed,t.DEFAULT_ANSI_COLORS[9]),n.ansi[10]=g(e.brightGreen,t.DEFAULT_ANSI_COLORS[10]),n.ansi[11]=g(e.brightYellow,t.DEFAULT_ANSI_COLORS[11]),n.ansi[12]=g(e.brightBlue,t.DEFAULT_ANSI_COLORS[12]),n.ansi[13]=g(e.brightMagenta,t.DEFAULT_ANSI_COLORS[13]),n.ansi[14]=g(e.brightCyan,t.DEFAULT_ANSI_COLORS[14]),n.ansi[15]=g(e.brightWhite,t.DEFAULT_ANSI_COLORS[15]),e.extendedAnsi){let r=Math.min(n.ansi.length-16,e.extendedAnsi.length);for(let i=0;i<r;i++)n.ansi[i+16]=g(e.extendedAnsi[i],t.DEFAULT_ANSI_COLORS[i+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e!==void 0)switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}else for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e]}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function g(e,t){if(e!==void 0)try{return o.css.toColor(e)}catch{}return t}t.ThemeService=h=r([i(0,l.IOptionsService)],h)},160:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.contrastRatio=t.toPaddedHex=t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0;let n=0,r=0,i=0,a=0;var o,s,c,l,u;function d(e){let t=e.toString(16);return t.length<2?`0`+t:t}function f(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}t.NULL_COLOR={css:`#00000000`,rgba:0},function(e){e.toCss=function(e,t,n,r){return r===void 0?`#${d(e)}${d(t)}${d(n)}`:`#${d(e)}${d(t)}${d(n)}${d(r)}`},e.toRgba=function(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0},e.toColor=function(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}}(o||(t.channels=o={})),function(e){function t(e,t){return a=Math.round(255*t),[n,r,i]=u.toChannels(e.rgba),{css:o.toCss(n,r,i,a),rgba:o.toRgba(n,r,i,a)}}e.blend=function(e,t){if(a=(255&t.rgba)/255,a===1)return{css:t.css,rgba:t.rgba};let s=t.rgba>>24&255,c=t.rgba>>16&255,l=t.rgba>>8&255,u=e.rgba>>24&255,d=e.rgba>>16&255,f=e.rgba>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),{css:o.toCss(n,r,i),rgba:o.toRgba(n,r,i)}},e.isOpaque=function(e){return(255&e.rgba)==255},e.ensureContrastRatio=function(e,t,n){let r=u.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return o.toColor(r>>24&255,r>>16&255,r>>8&255)},e.opaque=function(e){let t=(255|e.rgba)>>>0;return[n,r,i]=u.toChannels(t),{css:o.toCss(n,r,i),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,n){return a=255&e.rgba,t(e,a*n/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}}(s||(t.color=s={})),function(e){let t,s;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let n=e.getContext(`2d`,{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation=`copy`,s=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),o.toColor(n,r,i);case 5:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),a=parseInt(e.slice(4,5).repeat(2),16),o.toColor(n,r,i,a);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let c=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(c)return n=parseInt(c[1]),r=parseInt(c[2]),i=parseInt(c[3]),a=Math.round(255*(c[5]===void 0?1:parseFloat(c[5]))),o.toColor(n,r,i,a);if(!t||!s||(t.fillStyle=s,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[n,r,i,a]=t.getImageData(0,0,1,1).data,a!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:o.toRgba(n,r,i,a),css:e}}}(c||(t.css=c={})),function(e){function t(e,t,n){let r=e/255,i=t/255,a=n/255;return .2126*(r<=.03928?r/12.92:((r+.055)/1.055)**2.4)+.7152*(i<=.03928?i/12.92:((i+.055)/1.055)**2.4)+.0722*(a<=.03928?a/12.92:((a+.055)/1.055)**2.4)}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(l||(t.rgb=l={})),function(e){function t(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(.1*o)),s-=Math.max(0,Math.ceil(.1*s)),c-=Math.max(0,Math.ceil(.1*c)),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}function s(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil(.1*(255-o))),s=Math.min(255,s+Math.ceil(.1*(255-s))),c=Math.min(255,c+Math.ceil(.1*(255-c))),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.blend=function(e,t){if(a=(255&t)/255,a===1)return t;let s=t>>24&255,c=t>>16&255,l=t>>8&255,u=e>>24&255,d=e>>16&255,f=e>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),o.toRgba(n,r,i)},e.ensureContrastRatio=function(e,n,r){let i=l.relativeLuminance(e>>8),a=l.relativeLuminance(n>>8);if(f(i,a)<r){if(a<i){let a=t(e,n,r),o=f(i,l.relativeLuminance(a>>8));if(o<r){let t=s(e,n,r);return o>f(i,l.relativeLuminance(t>>8))?a:t}return a}let o=s(e,n,r),c=f(i,l.relativeLuminance(o>>8));if(c<r){let a=t(e,n,r);return c>f(i,l.relativeLuminance(a>>8))?o:a}return o}},e.reduceLuminance=t,e.increaseLuminance=s,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}}(u||(t.rgba=u={})),t.toPaddedHex=d,t.contrastRatio=f},345:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed){for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}}}),this._event}fire(e,t){let n=[];for(let e=0;e<this._listeners.length;e++)n.push(this._listeners[e]);for(let r=0;r<n.length;r++)n[r].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},859:(e,t)=>{function n(e){for(let t of e)t.dispose();e.length=0}Object.defineProperty(t,`__esModule`,{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){let t=this._disposables.indexOf(e);t!==-1&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=n,t.getDisposeArrayDisposable=function(e){return{dispose:()=>n(e)}}},485:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class n{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}}t.TwoKeyMap=n,t.FourKeyMap=class{constructor(){this._data=new n}set(e,t,r,i,a){this._data.get(e,t)||this._data.set(e,t,new n),this._data.get(e,t).set(r,i,a)}get(e,t,n,r){return this._data.get(e,t)?.get(n,r)}clear(){this._data.clear()}}},726:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;let n=`di$target`,r=`di$dependencies`;t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[r]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);let i=function(e,t,a){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);(function(e,t,i){t[n]===t?t[r].push({id:e,index:i}):(t[r]=[{id:e,index:i}],t[n]=t)})(i,e,a)};return i.toString=()=>e,t.serviceRegistry.set(e,i),i}},97:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;let r=n(726);var i;t.IBufferService=(0,r.createDecorator)(`BufferService`),t.ICoreMouseService=(0,r.createDecorator)(`CoreMouseService`),t.ICoreService=(0,r.createDecorator)(`CoreService`),t.ICharsetService=(0,r.createDecorator)(`CharsetService`),t.IInstantiationService=(0,r.createDecorator)(`InstantiationService`),function(e){e[e.TRACE=0]=`TRACE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARN=3]=`WARN`,e[e.ERROR=4]=`ERROR`,e[e.OFF=5]=`OFF`}(i||(t.LogLevelEnum=i={})),t.ILogService=(0,r.createDecorator)(`LogService`),t.IOptionsService=(0,r.createDecorator)(`OptionsService`),t.IOscLinkService=(0,r.createDecorator)(`OscLinkService`),t.IUnicodeService=(0,r.createDecorator)(`UnicodeService`),t.IDecorationService=(0,r.createDecorator)(`DecorationService`)}},t={};function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}var r={};return(()=>{var e=r;Object.defineProperty(e,`__esModule`,{value:!0}),e.HTMLSerializeHandler=e.SerializeAddon=void 0;let t=n(997);function i(e,t,n){return Math.max(t,Math.min(e,n))}class a{constructor(e){this._buffer=e}serialize(e,t){let n=this._buffer.getNullCell(),r=this._buffer.getNullCell(),i=n,a=e.start.y,o=e.end.y,s=e.start.x,c=e.end.x;this._beforeSerialize(o-a,a,o);for(let t=a;t<=o;t++){let a=this._buffer.getLine(t);if(a){let o=t===e.start.y?s:0,l=t===e.end.y?c:a.length;for(let e=o;e<l;e++){let o=a.getCell(e,i===n?r:n);o?(this._nextCell(o,i,t,e),i=o):console.warn(`Can't get cell at row=${t}, col=${e}`)}}this._rowEnd(t,t===o)}return this._afterSerialize(),this._serializeString(t)}_nextCell(e,t,n,r){}_rowEnd(e,t){}_beforeSerialize(e,t,n){}_afterSerialize(){}_serializeString(e){return``}}function o(e,t){return e.getFgColorMode()===t.getFgColorMode()&&e.getFgColor()===t.getFgColor()}function s(e,t){return e.getBgColorMode()===t.getBgColorMode()&&e.getBgColor()===t.getBgColor()}function c(e,t){return e.isInverse()===t.isInverse()&&e.isBold()===t.isBold()&&e.isUnderline()===t.isUnderline()&&e.isOverline()===t.isOverline()&&e.isBlink()===t.isBlink()&&e.isInvisible()===t.isInvisible()&&e.isItalic()===t.isItalic()&&e.isDim()===t.isDim()&&e.isStrikethrough()===t.isStrikethrough()}class l extends a{constructor(e,t){super(e),this._terminal=t,this._rowIndex=0,this._allRows=[],this._allRowSeparators=[],this._currentRow=``,this._nullCellCount=0,this._cursorStyle=this._buffer.getNullCell(),this._cursorStyleRow=0,this._cursorStyleCol=0,this._backgroundCell=this._buffer.getNullCell(),this._firstRow=0,this._lastCursorRow=0,this._lastCursorCol=0,this._lastContentCursorRow=0,this._lastContentCursorCol=0,this._thisRowLastChar=this._buffer.getNullCell(),this._thisRowLastSecondChar=this._buffer.getNullCell(),this._nextRowFirstChar=this._buffer.getNullCell()}_beforeSerialize(e,t,n){this._allRows=Array(e),this._lastContentCursorRow=t,this._lastCursorRow=t,this._firstRow=t}_rowEnd(e,t){this._nullCellCount>0&&!s(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`[${this._nullCellCount}X`);let n=``;if(!t){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let t=this._buffer.getLine(e),r=this._buffer.getLine(e+1);if(r.isWrapped){n=``;let i=t.getCell(t.length-1,this._thisRowLastChar),a=t.getCell(t.length-2,this._thisRowLastSecondChar),o=r.getCell(0,this._nextRowFirstChar),c=o.getWidth()>1,l=!1;(o.getChars()&&c?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&s(i,o)&&(l=!0),c&&(a.getChars()||a.getWidth()===0)&&s(i,o)&&s(a,o)&&(l=!0)),l||(n=`-`.repeat(this._nullCellCount+1),n+=`\x1B[1D\x1B[1X`,this._nullCellCount>0&&(n+=`\x1B[A`,n+=`[${t.length-this._nullCellCount}C`,n+=`[${this._nullCellCount}X`,n+=`[${t.length-this._nullCellCount}D`,n+=`\x1B[B`),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}else n=`\r
|
|
32
|
+
`,this._lastCursorRow=e+1,this._lastCursorCol=0}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=n,this._currentRow=``,this._nullCellCount=0}_diffStyle(e,t){let n=[],r=!o(e,t),i=!s(e,t),a=!c(e,t);if(r||i||a)if(e.isAttributeDefault())t.isAttributeDefault()||n.push(0);else{if(r){let t=e.getFgColor();e.isFgRGB()?n.push(38,2,t>>>16&255,t>>>8&255,255&t):e.isFgPalette()?t>=16?n.push(38,5,t):n.push(8&t?90+(7&t):30+(7&t)):n.push(39)}if(i){let t=e.getBgColor();e.isBgRGB()?n.push(48,2,t>>>16&255,t>>>8&255,255&t):e.isBgPalette()?t>=16?n.push(48,5,t):n.push(8&t?100+(7&t):40+(7&t)):n.push(49)}a&&(e.isInverse()!==t.isInverse()&&n.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&n.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&n.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&n.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&n.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&n.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&n.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&n.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&n.push(e.isStrikethrough()?9:29))}return n}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,this._cursorStyle);if(i?!s(this._cursorStyle,e):a.length>0){this._nullCellCount>0&&(s(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r,this._currentRow+=`[${a.join(`;`)}m`;let e=this._buffer.getLine(n);e!==void 0&&(e.getCell(r,this._cursorStyle),this._cursorStyleRow=n,this._cursorStyleCol=r)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(s(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let n=``;for(let e=0;e<t;e++)n+=this._allRows[e],e+1<t&&(n+=this._allRowSeparators[e]);if(!e){let e=this._buffer.baseY+this._buffer.cursorY,t=this._buffer.cursorX;(e!==this._lastCursorRow||t!==this._lastCursorCol)&&((r=e-this._lastCursorRow)>0?n+=`[${r}B`:r<0&&(n+=`[${-r}A`),(e=>{e>0?n+=`[${e}C`:e<0&&(n+=`[${-e}D`)})(t-this._lastCursorCol))}var r;let i=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(i,this._cursorStyle);return a.length>0&&(n+=`[${a.join(`;`)}m`),n}}e.SerializeAddon=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,n){let r=t.length,a=n===void 0?r:i(n+e.rows,0,r);return this._serializeBufferByRange(e,t,{start:r-a,end:r-1},!1)}_serializeBufferByRange(e,t,n,r){return new l(t,e).serialize({start:{x:0,y:typeof n.start==`number`?n.start:n.start.line},end:{x:e.cols,y:typeof n.end==`number`?n.end:n.end.line}},r)}_serializeBufferAsHTML(e,t){let n=e.buffer.active,r=new u(n,e,t);if(!t.onlySelection){let a=n.length,o=t.scrollback,s=o===void 0?a:i(o+e.rows,0,a);return r.serialize({start:{x:0,y:a-s},end:{x:e.cols,y:a-1}})}let a=this._terminal?.getSelectionPosition();return a===void 0?``:r.serialize({start:{x:a.start.x,y:a.start.y},end:{x:a.end.x,y:a.end.y}})}_serializeModes(e){let t=``,n=e.modes;if(n.applicationCursorKeysMode&&(t+=`\x1B[?1h`),n.applicationKeypadMode&&(t+=`\x1B[?66h`),n.bracketedPasteMode&&(t+=`\x1B[?2004h`),n.insertMode&&(t+=`\x1B[4h`),n.originMode&&(t+=`\x1B[?6h`),n.reverseWraparoundMode&&(t+=`\x1B[?45h`),n.sendFocusMode&&(t+=`\x1B[?1004h`),!1===n.wraparoundMode&&(t+=`\x1B[?7l`),n.mouseTrackingMode!==`none`)switch(n.mouseTrackingMode){case`x10`:t+=`\x1B[?9h`;break;case`vt200`:t+=`\x1B[?1000h`;break;case`drag`:t+=`\x1B[?1002h`;break;case`any`:t+=`\x1B[?1003h`}return t}serialize(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);let t=e?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e?.scrollback);return e?.excludeAltBuffer||this._terminal.buffer.active.type!==`alternate`||(t+=`[?1049h[H${this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0)}`),e?.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}};class u extends a{constructor(e,n,r){super(e),this._terminal=n,this._options=r,this._currentRow=``,this._htmlContent=``,n._core._themeService?this._ansiColors=n._core._themeService.colors.ansi:this._ansiColors=t.DEFAULT_ANSI_COLORS}_padStart(e,t,n){return t>>=0,n??=` `,e.length>t?e:((t-=e.length)>n.length&&(n+=n.repeat(t/n.length)),n.slice(0,t)+e)}_beforeSerialize(e,t,n){this._htmlContent+=`<html><body><!--StartFragment--><pre>`;let r=`#000000`,i=`#ffffff`;this._options.includeGlobalBackground&&(r=this._terminal.options.theme?.foreground??`#ffffff`,i=this._terminal.options.theme?.background??`#000000`);let a=[];a.push(`color: `+r+`;`),a.push(`background-color: `+i+`;`),a.push(`font-family: `+this._terminal.options.fontFamily+`;`),a.push(`font-size: `+this._terminal.options.fontSize+`px;`),this._htmlContent+=`<div style='`+a.join(` `)+`'>`}_afterSerialize(){this._htmlContent+=`</div>`,this._htmlContent+=`</pre><!--EndFragment--></body></html>`}_rowEnd(e,t){this._htmlContent+=`<div><span>`+this._currentRow+`</span></div>`,this._currentRow=``}_getHexColor(e,t){let n=t?e.getFgColor():e.getBgColor();return(t?e.isFgRGB():e.isBgRGB())?`#`+[n>>16&255,n>>8&255,255&n].map((e=>this._padStart(e.toString(16),2,`0`))).join(``):(t?e.isFgPalette():e.isBgPalette())?this._ansiColors[n].css:void 0}_diffStyle(e,t){let n=[],r=!o(e,t),i=!s(e,t),a=!c(e,t);if(r||i||a){let t=this._getHexColor(e,!0);t&&n.push(`color: `+t+`;`);let r=this._getHexColor(e,!1);return r&&n.push(`background-color: `+r+`;`),e.isInverse()&&n.push(`color: #000000; background-color: #BFBFBF;`),e.isBold()&&n.push(`font-weight: bold;`),e.isUnderline()&&e.isOverline()?n.push(`text-decoration: overline underline;`):e.isUnderline()?n.push(`text-decoration: underline;`):e.isOverline()&&n.push(`text-decoration: overline;`),e.isBlink()&&n.push(`text-decoration: blink;`),e.isInvisible()&&n.push(`visibility: hidden;`),e.isItalic()&&n.push(`font-style: italic;`),e.isDim()&&n.push(`opacity: 0.5;`),e.isStrikethrough()&&n.push(`text-decoration: line-through;`),n}}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,t);a&&(this._currentRow+=a.length===0?`</span><span>`:`</span><span style='`+a.join(` `)+`'>`),this._currentRow+=i?` `:e.getChars()}_serializeString(){return this._htmlContent}}e.HTMLSerializeHandler=u})(),r})()))})}),bt=a.__commonJS({"../../node_modules/@xterm/headless/lib-headless/xterm-headless.js":(e=>{(()=>{var t={349:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CircularList=void 0;let r=n(460),i=n(844);class a extends i.Disposable{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this.register(new r.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new r.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new r.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}}t.CircularList=a},439:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.clone=void 0,t.clone=function e(t,n=5){if(typeof t!=`object`)return t;let r=Array.isArray(t)?[]:{};for(let i in t)r[i]=n<=1?t[i]:t[i]&&e(t[i],n-1);return r}},969:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreTerminal=void 0;let r=n(844),i=n(585),a=n(348),o=n(866),s=n(744),c=n(302),l=n(83),u=n(460),d=n(753),f=n(480),p=n(994),m=n(282),h=n(435),g=n(981),_=n(660),v=!1;class y extends r.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new u.EventEmitter),this._onScroll.event((e=>{this._onScrollApi?.fire(e.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}constructor(e){super(),this._windowsWrappingHeuristics=this.register(new r.MutableDisposable),this._onBinary=this.register(new u.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new u.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new u.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new u.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new u.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new u.EventEmitter),this._instantiationService=new a.InstantiationService,this.optionsService=this.register(new c.OptionsService(e)),this._instantiationService.setService(i.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(s.BufferService)),this._instantiationService.setService(i.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(o.LogService)),this._instantiationService.setService(i.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(l.CoreService)),this._instantiationService.setService(i.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(d.CoreMouseService)),this._instantiationService.setService(i.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(f.UnicodeService)),this._instantiationService.setService(i.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(p.CharsetService),this._instantiationService.setService(i.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_.OscLinkService),this._instantiationService.setService(i.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new h.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,u.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,u.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,u.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,u.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new g.WriteBuffer(((e,t)=>this._inputHandler.parse(e,t)))),this.register((0,u.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=i.LogLevelEnum.WARN&&!v&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),v=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,s.MINIMUM_COLS),t=Math.max(t,s.MINIMUM_ROWS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t,n){this._bufferService.scrollLines(e,t,n)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(m.updateWindowsModeWrappedState.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},(()=>((0,m.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,r.toDisposable)((()=>{for(let t of e)t.dispose()}))}}}t.CoreTerminal=y},460:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed){for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}}}),this._event}fire(e,t){let n=[];for(let e=0;e<this._listeners.length;e++)n.push(this._listeners[e]);for(let r=0;r<n.length;r++)n[r].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},435:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0;let a=n(584),o=n(116),s=n(15),c=n(844),l=n(482),u=n(437),d=n(460),f=n(643),p=n(511),m=n(734),h=n(585),g=n(480),_=n(242),v=n(351),y=n(941),b={"(":0,")":1,"*":2,"+":3,"-":1,".":2},x=131072;function S(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var C;(function(e){e[e.GET_WIN_SIZE_PIXELS=0]=`GET_WIN_SIZE_PIXELS`,e[e.GET_CELL_SIZE_PIXELS=1]=`GET_CELL_SIZE_PIXELS`})(C||(t.WindowsOptionsReportType=C={}));let w=0;class T extends c.Disposable{getAttrData(){return this._curAttrData}constructor(e,t,n,r,i,c,f,m,h=new s.EscapeSequenceParser){for(let s in super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=c,this._coreMouseService=f,this._unicodeService=m,this._parser=h,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new l.StringToUtf32,this._utf8Decoder=new l.Utf8ToUtf32,this._workCell=new p.CellData,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new d.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new d.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new d.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new d.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new d.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new d.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new d.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new d.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new d.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new d.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new d.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new d.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new E(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._parser.setCsiHandlerFallback(((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})})),this._parser.setEscHandlerFallback((e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})})),this._parser.setExecuteHandlerFallback((e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})})),this._parser.setOscHandlerFallback(((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})})),this._parser.setDcsHandlerFallback(((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})})),this._parser.setPrintHandler(((e,t,n)=>this.print(e,t,n))),this._parser.registerCsiHandler({final:`@`},(e=>this.insertChars(e))),this._parser.registerCsiHandler({intermediates:` `,final:`@`},(e=>this.scrollLeft(e))),this._parser.registerCsiHandler({final:`A`},(e=>this.cursorUp(e))),this._parser.registerCsiHandler({intermediates:` `,final:`A`},(e=>this.scrollRight(e))),this._parser.registerCsiHandler({final:`B`},(e=>this.cursorDown(e))),this._parser.registerCsiHandler({final:`C`},(e=>this.cursorForward(e))),this._parser.registerCsiHandler({final:`D`},(e=>this.cursorBackward(e))),this._parser.registerCsiHandler({final:`E`},(e=>this.cursorNextLine(e))),this._parser.registerCsiHandler({final:`F`},(e=>this.cursorPrecedingLine(e))),this._parser.registerCsiHandler({final:`G`},(e=>this.cursorCharAbsolute(e))),this._parser.registerCsiHandler({final:`H`},(e=>this.cursorPosition(e))),this._parser.registerCsiHandler({final:`I`},(e=>this.cursorForwardTab(e))),this._parser.registerCsiHandler({final:`J`},(e=>this.eraseInDisplay(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`J`},(e=>this.eraseInDisplay(e,!0))),this._parser.registerCsiHandler({final:`K`},(e=>this.eraseInLine(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`K`},(e=>this.eraseInLine(e,!0))),this._parser.registerCsiHandler({final:`L`},(e=>this.insertLines(e))),this._parser.registerCsiHandler({final:`M`},(e=>this.deleteLines(e))),this._parser.registerCsiHandler({final:`P`},(e=>this.deleteChars(e))),this._parser.registerCsiHandler({final:`S`},(e=>this.scrollUp(e))),this._parser.registerCsiHandler({final:`T`},(e=>this.scrollDown(e))),this._parser.registerCsiHandler({final:`X`},(e=>this.eraseChars(e))),this._parser.registerCsiHandler({final:`Z`},(e=>this.cursorBackwardTab(e))),this._parser.registerCsiHandler({final:"`"},(e=>this.charPosAbsolute(e))),this._parser.registerCsiHandler({final:`a`},(e=>this.hPositionRelative(e))),this._parser.registerCsiHandler({final:`b`},(e=>this.repeatPrecedingCharacter(e))),this._parser.registerCsiHandler({final:`c`},(e=>this.sendDeviceAttributesPrimary(e))),this._parser.registerCsiHandler({prefix:`>`,final:`c`},(e=>this.sendDeviceAttributesSecondary(e))),this._parser.registerCsiHandler({final:`d`},(e=>this.linePosAbsolute(e))),this._parser.registerCsiHandler({final:`e`},(e=>this.vPositionRelative(e))),this._parser.registerCsiHandler({final:`f`},(e=>this.hVPosition(e))),this._parser.registerCsiHandler({final:`g`},(e=>this.tabClear(e))),this._parser.registerCsiHandler({final:`h`},(e=>this.setMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`h`},(e=>this.setModePrivate(e))),this._parser.registerCsiHandler({final:`l`},(e=>this.resetMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`l`},(e=>this.resetModePrivate(e))),this._parser.registerCsiHandler({final:`m`},(e=>this.charAttributes(e))),this._parser.registerCsiHandler({final:`n`},(e=>this.deviceStatus(e))),this._parser.registerCsiHandler({prefix:`?`,final:`n`},(e=>this.deviceStatusPrivate(e))),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},(e=>this.softReset(e))),this._parser.registerCsiHandler({intermediates:` `,final:`q`},(e=>this.setCursorStyle(e))),this._parser.registerCsiHandler({final:`r`},(e=>this.setScrollRegion(e))),this._parser.registerCsiHandler({final:`s`},(e=>this.saveCursor(e))),this._parser.registerCsiHandler({final:`t`},(e=>this.windowOptions(e))),this._parser.registerCsiHandler({final:`u`},(e=>this.restoreCursor(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},(e=>this.insertColumns(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},(e=>this.deleteColumns(e))),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},(e=>this.selectProtected(e))),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},(e=>this.requestMode(e,!0))),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},(e=>this.requestMode(e,!1))),this._parser.setExecuteHandler(a.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(a.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(a.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(a.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(a.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(a.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(a.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(a.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(a.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new _.OscHandler((e=>(this.setTitle(e),this.setIconName(e),!0)))),this._parser.registerOscHandler(1,new _.OscHandler((e=>this.setIconName(e)))),this._parser.registerOscHandler(2,new _.OscHandler((e=>this.setTitle(e)))),this._parser.registerOscHandler(4,new _.OscHandler((e=>this.setOrReportIndexedColor(e)))),this._parser.registerOscHandler(8,new _.OscHandler((e=>this.setHyperlink(e)))),this._parser.registerOscHandler(10,new _.OscHandler((e=>this.setOrReportFgColor(e)))),this._parser.registerOscHandler(11,new _.OscHandler((e=>this.setOrReportBgColor(e)))),this._parser.registerOscHandler(12,new _.OscHandler((e=>this.setOrReportCursorColor(e)))),this._parser.registerOscHandler(104,new _.OscHandler((e=>this.restoreIndexedColor(e)))),this._parser.registerOscHandler(110,new _.OscHandler((e=>this.restoreFgColor(e)))),this._parser.registerOscHandler(111,new _.OscHandler((e=>this.restoreBgColor(e)))),this._parser.registerOscHandler(112,new _.OscHandler((e=>this.restoreCursorColor(e)))),this._parser.registerEscHandler({final:`7`},(()=>this.saveCursor())),this._parser.registerEscHandler({final:`8`},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:`D`},(()=>this.index())),this._parser.registerEscHandler({final:`E`},(()=>this.nextLine())),this._parser.registerEscHandler({final:`H`},(()=>this.tabSet())),this._parser.registerEscHandler({final:`M`},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:`=`},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:`>`},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:`c`},(()=>this.fullReset())),this._parser.registerEscHandler({final:`n`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`o`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`|`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`}`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`~`},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:`%`,final:`@`},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:`%`,final:`G`},(()=>this.selectDefaultCharset())),o.CHARSETS)this._parser.registerEscHandler({intermediates:`(`,final:s},(()=>this.selectCharset(`(`+s))),this._parser.registerEscHandler({intermediates:`)`,final:s},(()=>this.selectCharset(`)`+s))),this._parser.registerEscHandler({intermediates:`*`,final:s},(()=>this.selectCharset(`*`+s))),this._parser.registerEscHandler({intermediates:`+`,final:s},(()=>this.selectCharset(`+`+s))),this._parser.registerEscHandler({intermediates:`-`,final:s},(()=>this.selectCharset(`-`+s))),this._parser.registerEscHandler({intermediates:`.`,final:s},(()=>this.selectCharset(`.`+s))),this._parser.registerEscHandler({intermediates:`/`,final:s},(()=>this.selectCharset(`/`+s)));this._parser.registerEscHandler({intermediates:`#`,final:`8`},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((e=>(this._logService.error(`Parsing error: `,e),e))),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new v.DcsHandler(((e,t)=>this.requestStatusString(e,t))))}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=h.LogLevelEnum.WARN&&Promise.race([e,new Promise(((e,t)=>setTimeout((()=>t(`#SLOW_TIMEOUT`)),5e3)))]).catch((e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than 5000 ms`)}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>x&&(a=this._parseStack.position+x)}if(this._logService.logLevel<=h.LogLevelEnum.DEBUG&&this._logService.debug(`parsing data`+(typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,(e=>String.fromCharCode(e))).join(``)}"`),typeof e==`string`?e.split(``).map((e=>e.charCodeAt(0))):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<x&&(this._parseBuffer=new Uint32Array(Math.min(e.length,x))),o||this._dirtyRowTracker.clearRange(),e.length>x)for(let t=a;t<e.length;t+=x){let a=t+x<e.length?t+x:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}this._activeBuffer.x===r&&this._activeBuffer.y===i||this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(c,this._bufferService.rows-1),Math.min(s,this._bufferService.rows-1))}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,d=this._coreService.modes.insertMode,p=this._curAttrData,m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&m.getWidth(this._activeBuffer.x-1)===2&&m.setCellFromCodepoint(this._activeBuffer.x-1,0,1,p);let h=this._parser.precedingJoinState;for(let _=t;_<n;++_){if(r=e[_],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,h);i=g.UnicodeService.extractWidth(t);let n=g.UnicodeService.extractShouldJoin(t),v=n?g.UnicodeService.extractWidth(h):0;if(h=t,o&&this._onA11yChar.fire((0,l.stringFromCodePoint)(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-v>s){if(c){let e=m,t=this._activeBuffer.x-v;for(this._activeBuffer.x=v,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),v>0&&m instanceof u.BufferLine&&m.copyCellsFrom(e,t,0,v,!1);t<s;)e.setCellFromCodepoint(t++,0,1,p)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=m.getWidth(this._activeBuffer.x-1)?1:2;m.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-v;--e>=0;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}else if(d&&(m.insertCells(this._activeBuffer.x,i-v,this._activeBuffer.getNullCell(p)),m.getWidth(s-1)===2&&m.setCellFromCodepoint(s-1,f.NULL_CELL_CODE,f.NULL_CELL_WIDTH,p)),m.setCellFromCodepoint(this._activeBuffer.x++,r,i,p),i>0)for(;--i;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}this._parser.precedingJoinState=h,this._activeBuffer.x<s&&n-t>0&&m.getWidth(this._activeBuffer.x)===0&&!m.hasContent(this._activeBuffer.x)&&m.setCellFromCodepoint(this._activeBuffer.x,0,1,p),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final!==`t`||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,(e=>!S(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new v.DcsHandler(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new _.OscHandler(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),t!==2&&t!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){let n;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(u.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=g.UnicodeService.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(a.C0.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),this._charsetService.setgCharset(1,o.DEFAULT_CHARSET),this._charsetService.setgCharset(2,o.DEFAULT_CHARSET),this._charsetService.setgCharset(3,o.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(e,t){let n=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:i}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=e=>e?1:2,p=e.params[0];return m=p,h=t?p===2?4:p===4?f(o.modes.insertMode):p===12?3:p===20?f(d.convertEol):0:p===1?f(n.applicationCursorKeys):p===3?d.windowOptions.setWinLines?c===80?2:c===132?1:0:0:p===6?f(n.origin):p===7?f(n.wraparound):p===8?3:p===9?f(r===`X10`):p===12?f(d.cursorBlink):p===25?f(!o.isCursorHidden):p===45?f(n.reverseWraparound):p===66?f(n.applicationKeypad):p===67?4:p===1e3?f(r===`VT200`):p===1002?f(r===`DRAG`):p===1003?f(r===`ANY`):p===1004?f(n.sendFocus):p===1005?4:p===1006?f(i===`SGR`):p===1015?4:p===1016?f(i===`SGR_PIXELS`):p===1048?1:p===47||p===1047||p===1049?f(l===u):p===2004?f(n.bracketedPasteMode):0,o.triggerDataEvent(`${a.C0.ESC}[${t?``:`?`}${m};${h}$y`),!0;var m,h}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=m.AttributeData.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|255&n),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=u.DEFAULT_ATTR_DATA.fg,e.bg=u.DEFAULT_ATTR_DATA.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777224|n-90):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777224|n-100):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg):n===49?(r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg,r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${a.C0.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle=`block`;break;case 3:case 4:this._optionsService.options.cursorStyle=`underline`;break;case 5:case 6:this._optionsService.options.cursorStyle=`bar`}let n=t%2==1;return this._optionsService.options.cursorBlink=n,!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!S(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(C.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(C.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${a.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:t!==0&&t!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),t!==0&&t!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:t!==0&&t!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),t!==0&&t!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(D(n))if(r===`?`)t.push({type:0,index:n});else{let e=(0,y.parseColor)(r);e&&t.push({type:1,index:n,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.split(`;`);return!(t.length<2)&&(t[1]?this._createHyperlink(t[0],t[1]):!t[0]&&this._finishHyperlink())}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex((e=>e.startsWith(`id=`)));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=(0,y.parseColor)(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);D(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(b[e[0]],o.CHARSETS[e[1]]||o.DEFAULT_CHARSET),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new p.CellData;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=this._bufferService.buffer,r=this._optionsService.rawOptions;return(e=>(this._coreService.triggerDataEvent(`${a.C0.ESC}${e}${a.C0.ESC}\\`),!0))(e===`"q`?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}}t.InputHandler=T;let E=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(w=e,e=t,t=w),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function D(e){return 0<=e&&e<256}E=r([i(0,h.IBufferService)],E)},844:(e,t)=>{function n(e){for(let t of e)t.dispose();e.length=0}Object.defineProperty(t,`__esModule`,{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){let t=this._disposables.indexOf(e);t!==-1&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=n,t.getDisposeArrayDisposable=function(e){return{dispose:()=>n(e)}}},114:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.getSafariVersion=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.isNode=typeof process<`u`&&`title`in process;let n=t.isNode?`node`:navigator.userAgent,r=t.isNode?`node`:navigator.platform;t.isFirefox=n.includes(`Firefox`),t.isLegacyEdge=n.includes(`Edge`),t.isSafari=/^((?!chrome|android).)*safari/i.test(n),t.getSafariVersion=function(){if(!t.isSafari)return 0;let e=n.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])},t.isMac=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(r),t.isIpad=r===`iPad`,t.isIphone=r===`iPhone`,t.isWindows=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(r),t.isLinux=r.indexOf(`Linux`)>=0,t.isChromeOS=/\bCrOS\b/.test(n)},226:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;let r=n(114);class i{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=Date.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,Date.now()-t),n=Math.max(t,n),i=e.timeRemaining(),1.5*n>i)return r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),void this._start();r=i}this.clear()}}class a extends i{_requestCallback(e){return setTimeout((()=>e(this._createDeadline(16))))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=Date.now()+e;return{timeRemaining:()=>Math.max(0,t-Date.now())}}}t.PriorityTaskQueue=a,t.IdleTaskQueue=!r.isNode&&`requestIdleCallback`in window?class extends i{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:a,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}}},282:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.updateWindowsModeWrappedState=void 0;let r=n(643);t.updateWindowsModeWrappedState=function(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[r.CHAR_DATA_CODE_INDEX]!==r.NULL_CELL_CODE&&t[r.CHAR_DATA_CODE_INDEX]!==r.WHITESPACE_CELL_CODE)}},734:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class n{constructor(){this.fg=0,this.bg=0,this.extended=new r}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){let e=new n;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t.AttributeData=n;class r{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new r(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}t.ExtendedAttrs=r},92:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;let r=n(349),i=n(226),a=n(734),o=n(437),s=n(634),c=n(511),l=n(643),u=n(863),d=n(116);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o.DEFAULT_ATTR_DATA.clone(),this.savedCharset=d.DEFAULT_CHARSET,this.markers=[],this._nullCell=c.CellData.fromCharData([0,l.NULL_CELL_CHAR,l.NULL_CELL_WIDTH,l.NULL_CELL_CODE]),this._whitespaceCell=c.CellData.fromCharData([0,l.WHITESPACE_CELL_CHAR,l.WHITESPACE_CELL_WIDTH,l.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new i.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new a.ExtendedAttrs),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new a.ExtendedAttrs),this._whitespaceCell}getBlankLine(e,t){return new o.BufferLine(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let n=e+this._optionsService.rawOptions.scrollback;return n>t.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:n}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=o.DEFAULT_ATTR_DATA);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new o.BufferLine(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new o.BufferLine(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=(0,s.reflowLargerGetLinesToRemove)(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(o.DEFAULT_ATTR_DATA));if(n.length>0){let r=(0,s.reflowLargerCreateNewLayout)(this.lines,n);(0,s.reflowLargerApplyNewLayout)(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(o.DEFAULT_ATTR_DATA),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new o.BufferLine(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=[],i=0;for(let a=this.lines.length-1;a>=0;a--){let c=this.lines.get(a);if(!c||!c.isWrapped&&c.getTrimmedLength()<=e)continue;let l=[c];for(;c.isWrapped&&a>0;)c=this.lines.get(--a),l.unshift(c);let u=this.ybase+this.y;if(u>=a&&u<a+l.length)continue;let d=l[l.length-1].getTrimmedLength(),f=(0,s.reflowSmallerGetNewLineLengths)(l,this._cols,e),p=f.length-l.length,m=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+p):Math.max(0,this.lines.length-this.lines.maxLength+p),h=[];for(let e=0;e<p;e++){let e=this.getBlankLine(o.DEFAULT_ATTR_DATA,!0);h.push(e)}h.length>0&&(r.push({start:a+l.length+i,newLines:h}),i+=h.length),l.push(...h);let g=f.length-1,_=f[g];_===0&&(g--,_=f[g]);let v=l.length-p-1,y=d;for(;v>=0;){let e=Math.min(y,_);if(l[g]===void 0)break;if(l[g].copyCellsFrom(l[v],y-e,_-e,e,!0),_-=e,_===0&&(g--,_=f[g]),y-=e,y===0){v--;let e=Math.max(v,0);y=(0,s.getWrappedLineTrimmedLength)(l,e,this._cols)}}for(let t=0;t<l.length;t++)f[t]<e&&l[t].setCell(f[t],n);let b=p-m;for(;b-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+i)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+p,this.ybase+t-1)}if(r.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,a=n-1,o=0,s=r[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+i);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+i-1);l>=0;l--)if(s&&s.start>a+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:a+1,amount:s.newLines.length}),c+=s.newLines.length,s=r[++o]}else this.lines.set(l,t[a--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+i-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose(),this.markers.splice(e--,1);this._isClearing=!1}addMarker(e){let t=new u.Marker(e);return this.markers.push(t),t.register(this.lines.onTrim((e=>{t.line-=e,t.line<0&&t.dispose()}))),t.register(this.lines.onInsert((e=>{t.line>=e.index&&(t.line+=e.amount)}))),t.register(this.lines.onDelete((e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)}))),t.register(t.onDispose((()=>this._removeMarker(t)))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}}},437:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;let r=n(734),i=n(511),a=n(643),o=n(482);t.DEFAULT_ATTR_DATA=Object.freeze(new r.AttributeData);let s=0;class c{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);let r=t||i.CellData.fromCharData([0,a.NULL_CELL_CHAR,a.NULL_CELL_WIDTH,a.NULL_CELL_CODE]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[3*e+0],n=2097151&t;return[this._data[3*e+1],2097152&t?this._combined[e]:n?(0,o.stringFromCodePoint)(n):``,t>>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[3*e+1]=t[a.CHAR_DATA_ATTR_INDEX],t[a.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[a.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e+0]=t[a.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[a.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?(0,o.stringFromCodePoint)(2097151&t):``}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return s=3*e,t.content=this._data[s+0],t.fg=this._data[s+1],t.bg=this._data[s+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,n,r){268435456&r.bg&&(this._extendedAttrs[e]=r.extended),this._data[3*e+0]=t|n<<22,this._data[3*e+1]=r.fg,this._data[3*e+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[3*e+0];2097152&r?this._combined[e]+=(0,o.stringFromCodePoint)(t):2097151&r?(this._combined[e]=(0,o.stringFromCodePoint)(2097151&r)+(0,o.stringFromCodePoint)(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[3*e+0]=r}insertCells(e,t,n){if((e%=this.length)&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new i.CellData;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new i.CellData;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)!==0||this.hasContent(e)||this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let n=3*e;if(e>this.length){if(this._data.buffer.byteLength>=4*n)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,4*n*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){for(let t in this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={},e._combined)this._combined[t]=e._combined[t];for(let t in this._extendedAttrs={},e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let e=new c(0);for(let t in e._data=new Uint32Array(this._data),e.length=this.length,this._combined)e._combined[t]=this._combined[t];for(let t in this._extendedAttrs)e._extendedAttrs[t]=this._extendedAttrs[t];return e.isWrapped=this.isWrapped,e}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[3*t+0],n=2097151&e,s=2097152&e?this._combined[t]:n?(0,o.stringFromCodePoint)(n):a.WHITESPACE_CELL_CHAR;if(i+=s,r)for(let e=0;e<s.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}}t.BufferLine=c},634:(e,t)=>{function n(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}Object.defineProperty(t,`__esModule`,{value:!0}),t.getWrappedLineTrimmedLength=t.reflowSmallerGetNewLineLengths=t.reflowLargerApplyNewLayout=t.reflowLargerCreateNewLayout=t.reflowLargerGetLinesToRemove=void 0,t.reflowLargerGetLinesToRemove=function(e,t,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(i>=s&&i<c){s+=u.length-1;continue}let d=0,f=n(u,d,t),p=1,m=0;for(;p<u.length;){let e=n(u,p,t),i=e-m,o=r-f,s=Math.min(i,o);u[d].copyCellsFrom(u[p],m,f,s,!1),f+=s,f===r&&(d++,f=0),m+=s,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(r-1)===2&&(u[d].copyCellsFrom(u[d-1],r-1,f++,1,!1),u[d-1].setCell(r-1,a))}u[d].replaceCells(f,r,a);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o},t.reflowLargerCreateNewLayout=function(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}},t.reflowLargerApplyNewLayout=function(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length},t.reflowSmallerGetNewLineLengths=function(e,t,r){let i=[],a=e.map(((r,i)=>n(e,i,t))).reduce(((e,t)=>e+t)),o=0,s=0,c=0;for(;c<a;){if(a-c<r){i.push(a-c);break}o+=r;let l=n(e,s,t);o>l&&(o-=l,s++);let u=e[s].getWidth(o-1)===2;u&&o--;let d=u?r-1:r;i.push(d),c+=d}return i},t.getWrappedLineTrimmedLength=n},295:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferSet=void 0;let r=n(460),i=n(844),a=n(92);class o extends i.Disposable{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this.register(new r.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange(`scrollback`,(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,(()=>this.setupTabStops())))}reset(){this._normal=new a.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new a.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}}t.BufferSet=o},511:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CellData=void 0;let r=n(482),i=n(643),a=n(734);class o extends a.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new a.ExtendedAttrs,this.combinedData=``}static fromCharData(e){let t=new o;return t.setFromCharData(e),t}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,r.stringFromCodePoint)(2097151&this.content):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[i.CHAR_DATA_ATTR_INDEX],this.bg=0;let t=!1;if(e[i.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(e[i.CHAR_DATA_CHAR_INDEX].length===2){let n=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=r&&r<=57343?this.content=1024*(n-55296)+r-56320+65536|e[i.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[i.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[i.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[i.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=o},643:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=256|t.DEFAULT_COLOR<<9,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR=``,t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=` `,t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},863:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Marker=void 0;let r=n(460),i=n(844);class a{get id(){return this._id}constructor(e){this.line=e,this.isDisposed=!1,this._disposables=[],this._id=a._nextId++,this._onDispose=this.register(new r.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,i.disposeArray)(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}}t.Marker=a,a._nextId=1},116:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:``,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},t.CHARSETS.A={"#":`£`},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},t.CHARSETS.C=t.CHARSETS[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},t.CHARSETS.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},t.CHARSETS.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},t.CHARSETS.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},t.CHARSETS.E=t.CHARSETS[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},t.CHARSETS.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},t.CHARSETS.H=t.CHARSETS[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`}},584:(e,t)=>{var n,r,i;Object.defineProperty(t,`__esModule`,{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,function(e){e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
|
|
33
33
|
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``}(n||(t.C0=n={})),function(e){e.PAD=``,e.HOP=``,e.BPH=``,e.NBH=``,e.IND=``,e.NEL=`
`,e.SSA=``,e.ESA=``,e.HTS=``,e.HTJ=``,e.VTS=``,e.PLD=``,e.PLU=``,e.RI=``,e.SS2=``,e.SS3=``,e.DCS=``,e.PU1=``,e.PU2=``,e.STS=``,e.CCH=``,e.MW=``,e.SPA=``,e.EPA=``,e.SOS=``,e.SGCI=``,e.SCI=``,e.CSI=``,e.ST=``,e.OSC=``,e.PM=``,e.APC=``}(r||(t.C1=r={})),function(e){e.ST=`${n.ESC}\\`}(i||(t.C1_ESCAPED=i={}))},482:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Utf8ToUtf32=t.StringToUtf32=t.utf32ToString=t.stringFromCodePoint=void 0,t.stringFromCodePoint=function(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)},t.utf32ToString=function(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r},t.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=1024*(this._interim-55296)+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=1024*(i-55296)+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},t.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r,i,a,o,s=0,c=0,l=0;if(this.interim[0]){let r=!1,i=this.interim[0];i&=(224&i)==192?31:(240&i)==224?15:7;let a,o=0;for(;(a=63&this.interim[++o])&&o<4;)i<<=6,i|=a;let c=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(a=e[l++],(192&a)!=128){l--,r=!0;break}this.interim[o++]=a,i<<=6,i|=63&a}r||(c===2?i<128?l--:t[s++]=i:c===3?i<2048||i>=55296&&i<=57343||i===65279||(t[s++]=i):i<65536||i>1114111||(t[s++]=i)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;!(!(d<u)||128&(r=e[d])||128&(i=e[d+1])||128&(a=e[d+2])||128&(o=e[d+3]));)t[s++]=r,t[s++]=i,t[s++]=a,t[s++]=o,d+=4;if(r=e[d++],r<128)t[s++]=r;else if((224&r)==192){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(c=(31&r)<<6|63&i,c<128){d--;continue}t[s++]=c}else if((240&r)==224){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,s;if(a=e[d++],(192&a)!=128){d--;continue}if(c=(15&r)<<12|(63&i)<<6|63&a,c<2048||c>=55296&&c<=57343||c===65279)continue;t[s++]=c}else if((248&r)==240){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,s;if(a=e[d++],(192&a)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,this.interim[2]=a,s;if(o=e[d++],(192&o)!=128){d--;continue}if(c=(7&r)<<18|(63&i)<<12|(63&a)<<6|63&o,c<65536||c>1114111)continue;t[s++]=c}}return s}}},225:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.UnicodeV6=void 0;let r=n(480),i=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],a=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],o;t.UnicodeV6=class{constructor(){if(this.version=`6`,!o){o=new Uint8Array(65536),o.fill(1),o[0]=0,o.fill(0,1,32),o.fill(0,127,160),o.fill(2,4352,4448),o[9001]=2,o[9002]=2,o.fill(2,11904,42192),o[12351]=1,o.fill(2,44032,55204),o.fill(2,63744,64256),o.fill(2,65040,65050),o.fill(2,65072,65136),o.fill(2,65280,65377),o.fill(2,65504,65511);for(let e=0;e<i.length;++e)o.fill(0,i[e][0],i[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?o[e]:function(e,t){let n,r=0,i=t.length-1;if(e<t[0][0]||e>t[i][1])return!1;for(;i>=r;)if(n=r+i>>1,e>t[n][1])r=n+1;else{if(!(e<t[n][0]))return!0;i=n-1}return!1}(e,a)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),i=n===0&&t!==0;if(i){let e=r.UnicodeService.extractWidth(t);e===0?i=!1:e>n&&(n=e)}return r.UnicodeService.createPropertyValue(0,n,i)}}},981:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.WriteBuffer=void 0;let r=n(460),i=n(844);class a extends i.Disposable{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new r.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t)return void(this._syncCalls=0);if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let n;for(this._isSyncWriting=!0;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>5e7)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch((e=>(queueMicrotask((()=>{throw e})),Promise.resolve(!1)))).then(e=>Date.now()-n>=12?setTimeout((()=>this._innerWrite(0,e))):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,Date.now()-n>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}t.WriteBuffer=a},941:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.toRgbString=t.parseColor=void 0;let n=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,r=/^[\da-f]+$/;function i(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}t.parseColor=function(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=n.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),r.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}},t.toRgbString=function(e,t=16){let[n,r,a]=e;return`rgb:${i(n,t)}/${i(r,t)}/${i(a,t)}`}},770:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.PAYLOAD_LIMIT=void 0,t.PAYLOAD_LIMIT=1e7},351:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DcsHandler=t.DcsParser=void 0;let r=n(482),i=n(742),a=n(770),o=[];t.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=o,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=o}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=o,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||o,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t);else this._handlerFb(this._ident,`HOOK`,t)}put(e,t,n){if(this._active.length)for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n);else this._handlerFb(this._ident,`PUT`,(0,r.utf32ToString)(e,t,n))}unhook(e,t=!0){if(this._active.length){let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===n){for(;r>=0&&(n=this._active[r].unhook(e),!0!==n);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}else this._handlerFb(this._ident,`UNHOOK`,e);this._active=o,this._ident=0}};let s=new i.Params;s.addParam(0),t.DcsHandler=class{constructor(e){this._handler=e,this._data=``,this._params=s,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():s,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=(0,r.utf32ToString)(e,t,n),this._data.length>a.PAYLOAD_LIMIT&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then((e=>(this._params=s,this._data=``,this._hitLimit=!1,e)));return this._params=s,this._data=``,this._hitLimit=!1,t}}},15:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.EscapeSequenceParser=t.VT500_TRANSITION_TABLE=t.TransitionTable=void 0;let r=n(844),i=n(742),a=n(242),o=n(351);class s{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}}t.TransitionTable=s,t.VT500_TRANSITION_TABLE=function(){let e=new s(4095),t=Array.apply(null,Array(256)).map(((e,t)=>t)),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(160,0,2,0),e.add(160,8,5,8),e.add(160,6,0,6),e.add(160,11,0,11),e.add(160,13,13,13),e}();class c extends r.Disposable{constructor(e=t.VT500_TRANSITION_TABLE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new i.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,r.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new a.OscParser),this._dcsParser=this.register(new o.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},(()=>!0))}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r,i=0,a=0,o=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,a=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===n&&a>-1){for(;a>=0&&(r=t[a](this._params),!0!==r);a--)if(r instanceof Promise)return this._parseStack.handlerPos=a,r}this._parseStack.handlers=[];break;case 4:if(!1===n&&a>-1){for(;a>=0&&(r=t[a](),!0!==r);a--)if(r instanceof Promise)return this._parseStack.handlerPos=a,r}this._parseStack.handlers=[];break;case 6:if(i=e[this._parseStack.chunkPos],r=this._dcsParser.unhook(i!==24&&i!==26,n),r)return r;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(i=e[this._parseStack.chunkPos],r=this._oscParser.end(i!==24&&i!==26,n),r)return r;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let n=o;n<t;++n){switch(i=e[n],a=this._transitions.table[this.currentState<<8|(i<160?i:160)],a>>4){case 2:for(let r=n+1;;++r){if(r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}if(++r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}if(++r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}if(++r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}}break;case 3:this._executeHandlers[i]?this._executeHandlers[i]():this._executeHandlerFb(i),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:i,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let o=this._csiHandlers[this._collect<<8|i],s=o?o.length-1:-1;for(;s>=0&&(r=o[s](this._params),!0!==r);s--)if(r instanceof Promise)return this._preserveStack(3,o,s,a,n),r;s<0&&this._csiHandlerFb(this._collect<<8|i,this._params),this.precedingJoinState=0;break;case 8:do switch(i){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(i-48)}while(++n<t&&(i=e[n])>47&&i<60);n--;break;case 9:this._collect<<=8,this._collect|=i;break;case 10:let c=this._escHandlers[this._collect<<8|i],l=c?c.length-1:-1;for(;l>=0&&(r=c[l](),!0!==r);l--)if(r instanceof Promise)return this._preserveStack(4,c,l,a,n),r;l<0&&this._escHandlerFb(this._collect<<8|i),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|i,this._params);break;case 13:for(let r=n+1;;++r)if(r>=t||(i=e[r])===24||i===26||i===27||i>127&&i<160){this._dcsParser.put(e,n,r),n=r-1;break}break;case 14:if(r=this._dcsParser.unhook(i!==24&&i!==26),r)return this._preserveStack(6,[],0,a,n),r;i===27&&(a|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let r=n+1;;r++)if(r>=t||(i=e[r])<32||i>127&&i<160){this._oscParser.put(e,n,r),n=r-1;break}break;case 6:if(r=this._oscParser.end(i!==24&&i!==26),r)return this._preserveStack(5,[],0,a,n),r;i===27&&(a|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&a}}}t.EscapeSequenceParser=c},242:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.OscHandler=t.OscParser=void 0;let r=n(770),i=n(482),a=[];t.OscParser=class{constructor(){this._state=0,this._active=a,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=a}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=a,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||a,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,`START`)}_put(e,t,n){if(this._active.length)for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n);else this._handlerFb(this._id,`PUT`,(0,i.utf32ToString)(e,t,n))}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===n){for(;r>=0&&(n=this._active[r].end(e),!0!==n);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}else this._handlerFb(this._id,`END`,e);this._active=a,this._id=-1,this._state=0}}},t.OscHandler=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=(0,i.utf32ToString)(e,t,n),this._data.length>r.PAYLOAD_LIMIT&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then((e=>(this._data=``,this._hitLimit=!1,e)));return this._data=``,this._hitLimit=!1,t}}},742:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Params=void 0;let n=2147483647;class r{static fromArray(e){let t=new r;if(!e.length)return t;for(let n=Array.isArray(e[0])?1:0;n<e.length;++n){let r=e[n];if(Array.isArray(r))for(let e=0;e<r.length;++e)t.addSubParam(r[e]);else t.addParam(r)}return t}constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>256)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let e=new r(this.maxLength,this.maxSubParamsLength);return e.params.set(this.params),e.length=this.length,e._subParams.set(this._subParams),e._subParamsLength=this._subParamsLength,e._subParamsIdx.set(this._subParamsIdx),e._rejectDigits=this._rejectDigits,e._rejectSubDigits=this._rejectSubDigits,e._digitIsSub=this._digitIsSub,e}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=255&this._subParamsIdx[t];r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>n?n:e}}addSubParam(e){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>n?n:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=255&this._subParamsIdx[e];return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=255&this._subParamsIdx[t];r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let r=this._digitIsSub?this._subParams:this.params,i=r[t-1];r[t-1]=~i?Math.min(10*i+e,n):e}}t.Params=r},741:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.AddonManager=void 0,t.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}}},771:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferApiView=void 0;let r=n(785),i=n(511);t.BufferApiView=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new r.BufferLineApiView(t)}getNullCell(){return new i.CellData}}},785:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferLineApiView=void 0;let r=n(511);t.BufferLineApiView=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new r.CellData)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}}},285:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferNamespaceApi=void 0;let r=n(771),i=n(460),a=n(844);class o extends a.Disposable{constructor(e){super(),this._core=e,this._onBufferChange=this.register(new i.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new r.BufferApiView(this._core.buffers.normal,`normal`),this._alternate=new r.BufferApiView(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}t.BufferNamespaceApi=o},975:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ParserApi=void 0,t.ParserApi=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,(e=>t(e.toArray())))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,((e,n)=>t(e,n.toArray())))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}}},90:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.UnicodeApi=void 0,t.UnicodeApi=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}}},744:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferService=t.MINIMUM_ROWS=t.MINIMUM_COLS=void 0;let a=n(460),o=n(844),s=n(295),c=n(585);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;let l=t.BufferService=class extends o.Disposable{get buffer(){return this.buffers.active}constructor(e){super(),this.isUserScrolling=!1,this._onResize=this.register(new a.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new a.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,t.MINIMUM_COLS),this.rows=Math.max(e.rawOptions.rows||0,t.MINIMUM_ROWS),this.buffers=this.register(new s.BufferSet(e,this))}resize(e,t){this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r=this._cachedBlankLine;r&&r.length===this.cols&&r.getFg(0)===e.fg&&r.getBg(0)===e.bg||(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t,n){let r=this.buffer;if(e<0){if(r.ydisp===0)return;this.isUserScrolling=!0}else e+r.ydisp>=r.ybase&&(this.isUserScrolling=!1);let i=r.ydisp;r.ydisp=Math.max(Math.min(r.ydisp+e,r.ybase),0),i!==r.ydisp&&(t||this._onScroll.fire(r.ydisp))}};t.BufferService=l=r([i(0,c.IOptionsService)],l)},994:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CharsetService=void 0,t.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}}},753:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreMouseService=void 0;let a=n(585),o=n(460),s=n(844),c={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button!==4&&e.action===1&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function l(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=3&e.button,4&e.button&&(n|=64),8&e.button&&(n|=128),e.action===32?n|=32:e.action!==0||t||(n|=3)),n}let u=String.fromCharCode,d={DEFAULT:e=>{let t=[l(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`[M${u(t[0])}${u(t[1])}${u(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`[<${l(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`[<${l(e,!0)};${e.x};${e.y}${t}`}},f=t.CoreMouseService=class extends s.Disposable{constructor(e,t){super(),this._bufferService=e,this._coreService=t,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._onProtocolChange=this.register(new o.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(c))this.addProtocol(e,c[e]);for(let e of Object.keys(d))this.addEncoding(e,d[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};t.CoreMouseService=f=r([i(0,a.IBufferService),i(1,a.ICoreService)],f)},83:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreService=void 0;let a=n(439),o=n(460),s=n(844),c=n(585),l=Object.freeze({insertMode:!1}),u=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0}),d=t.CoreService=class extends s.Disposable{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new o.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new o.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new o.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new o.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,a.clone)(l),this.decPrivateModes=(0,a.clone)(u)}reset(){this.modes=(0,a.clone)(l),this.decPrivateModes=(0,a.clone)(u)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`,(()=>e.split(``).map((e=>e.charCodeAt(0))))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`,(()=>e.split(``).map((e=>e.charCodeAt(0))))),this._onBinary.fire(e))}};t.CoreService=d=r([i(0,c.IBufferService),i(1,c.ILogService),i(2,c.IOptionsService)],d)},348:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.InstantiationService=t.ServiceCollection=void 0;let r=n(585),i=n(343);class a{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}}t.ServiceCollection=a,t.InstantiationService=class{constructor(){this._services=new a,this._services.set(r.IInstantiationService,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=(0,i.getServiceDependencies)(e).sort(((e,t)=>e.index-t.index)),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id}.`);r.push(n)}let a=n.length>0?n[0].index:t.length;if(t.length!==a)throw Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}}},866:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.traceCall=t.setTraceLogger=t.LogService=void 0;let a=n(844),o=n(585),s={trace:o.LogLevelEnum.TRACE,debug:o.LogLevelEnum.DEBUG,info:o.LogLevelEnum.INFO,warn:o.LogLevelEnum.WARN,error:o.LogLevelEnum.ERROR,off:o.LogLevelEnum.OFF},c,l=t.LogService=class extends a.Disposable{get logLevel(){return this._logLevel}constructor(e){super(),this._optionsService=e,this._logLevel=o.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange(`logLevel`,(()=>this._updateLogLevel()))),c=this}_updateLogLevel(){this._logLevel=s[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:`xterm.js: `)+t,...n)}trace(e,...t){this._logLevel<=o.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=o.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=o.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=o.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=o.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};t.LogService=l=r([i(0,o.IOptionsService)],l),t.setTraceLogger=function(e){c=e},t.traceCall=function(e,t,n){if(typeof n.value!=`function`)throw Error(`not supported`);let r=n.value;n.value=function(...e){if(c.logLevel!==o.LogLevelEnum.TRACE)return r.apply(this,e);c.trace(`GlyphRenderer#${r.name}(${e.map((e=>JSON.stringify(e))).join(`, `)})`);let t=r.apply(this,e);return c.trace(`GlyphRenderer#${r.name} return`,t),t}}},302:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.OptionsService=t.DEFAULT_OPTIONS=void 0;let r=n(460),i=n(844);t.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`courier-new, courier, monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:n(114).isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRulerWidth:0};let a=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`];class o extends i.Disposable{constructor(e){super(),this._onOptionChange=this.register(new r.EventEmitter),this.onOptionChange=this._onOptionChange.event;let n={...t.DEFAULT_OPTIONS};for(let t in e)if(t in n)try{let r=e[t];n[t]=this._sanitizeAndValidateOption(t,r)}catch(e){console.error(e)}this.rawOptions=n,this.options={...n},this._setupOptions(),this.register((0,i.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(e,t){return this.onOptionChange((n=>{n===e&&t(this.rawOptions[e])}))}onMultipleOptionChange(e,t){return this.onOptionChange((n=>{e.indexOf(n)!==-1&&t()}))}_setupOptions(){let e=e=>{if(!(e in t.DEFAULT_OPTIONS))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},n=(e,n)=>{if(!(e in t.DEFAULT_OPTIONS))throw Error(`No option with key "${e}"`);n=this._sanitizeAndValidateOption(e,n),this.rawOptions[e]!==n&&(this.rawOptions[e]=n,this._onOptionChange.fire(e))};for(let t in this.rawOptions){let r={get:e.bind(this,t),set:n.bind(this,t)};Object.defineProperty(this.options,t,r)}}_sanitizeAndValidateOption(e,n){switch(e){case`cursorStyle`:if(n||=t.DEFAULT_OPTIONS[e],!function(e){return e===`block`||e===`underline`||e===`bar`}(n))throw Error(`"${n}" is not a valid value for ${e}`);break;case`wordSeparator`:n||=t.DEFAULT_OPTIONS[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof n==`number`&&1<=n&&n<=1e3)break;n=a.includes(n)?n:t.DEFAULT_OPTIONS[e];break;case`cursorWidth`:n=Math.floor(n);case`lineHeight`:case`tabStopWidth`:if(n<1)throw Error(`${e} cannot be less than 1, value: ${n}`);break;case`minimumContrastRatio`:n=Math.max(1,Math.min(21,Math.round(10*n)/10));break;case`scrollback`:if((n=Math.min(n,4294967295))<0)throw Error(`${e} cannot be less than 0, value: ${n}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(n<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${n}`);break;case`rows`:case`cols`:if(!n&&n!==0)throw Error(`${e} must be numeric, value: ${n}`);break;case`windowsPty`:n??={}}return n}}t.OptionsService=o},660:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.OscLinkService=void 0;let a=n(585),o=t.OscLinkService=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose((()=>this._removeMarkerFromLink(r,n))),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose((()=>this._removeMarkerFromLink(o,a))),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every((e=>e.line!==t))){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose((()=>this._removeMarkerFromLink(n,e)))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};t.OscLinkService=o=r([i(0,a.IBufferService)],o)},343:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;let n=`di$target`,r=`di$dependencies`;t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[r]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);let i=function(e,t,a){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);(function(e,t,i){t[n]===t?t[r].push({id:e,index:i}):(t[r]=[{id:e,index:i}],t[n]=t)})(i,e,a)};return i.toString=()=>e,t.serviceRegistry.set(e,i),i}},585:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;let r=n(343);var i;t.IBufferService=(0,r.createDecorator)(`BufferService`),t.ICoreMouseService=(0,r.createDecorator)(`CoreMouseService`),t.ICoreService=(0,r.createDecorator)(`CoreService`),t.ICharsetService=(0,r.createDecorator)(`CharsetService`),t.IInstantiationService=(0,r.createDecorator)(`InstantiationService`),function(e){e[e.TRACE=0]=`TRACE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARN=3]=`WARN`,e[e.ERROR=4]=`ERROR`,e[e.OFF=5]=`OFF`}(i||(t.LogLevelEnum=i={})),t.ILogService=(0,r.createDecorator)(`LogService`),t.IOptionsService=(0,r.createDecorator)(`OptionsService`),t.IOscLinkService=(0,r.createDecorator)(`OscLinkService`),t.IUnicodeService=(0,r.createDecorator)(`UnicodeService`),t.IDecorationService=(0,r.createDecorator)(`DecorationService`)},480:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.UnicodeService=void 0;let r=n(460),i=n(225);class a{static extractShouldJoin(e){return(1&e)!=0}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(16777215&e)<<3|(3&t)<<1|(n?1:0)}constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new r.EventEmitter,this.onChange=this._onChange.event;let e=new i.UnicodeV6;this.register(e),this._active=e.version,this._activeProvider=e}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(e){let t=0,n=0,r=e.length;for(let i=0;i<r;++i){let o=e.charCodeAt(i);if(55296<=o&&o<=56319){if(++i>=r)return t+this.wcwidth(o);let n=e.charCodeAt(i);56320<=n&&n<=57343?o=1024*(o-55296)+n-56320+65536:t+=this.wcwidth(n)}let s=this.charProperties(o,n),c=a.extractWidth(s);a.extractShouldJoin(s)&&(c-=a.extractWidth(n)),t+=c,n=s}return t}charProperties(e,t){return this._activeProvider.charProperties(e,t)}}t.UnicodeService=a},781:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Terminal=void 0;let r=n(437),i=n(969),a=n(460);class o extends i.CoreTerminal{constructor(e={}){super(e),this._onBell=this.register(new a.EventEmitter),this.onBell=this._onBell.event,this._onCursorMove=this.register(new a.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onTitleChange=this.register(new a.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onA11yCharEmitter=this.register(new a.EventEmitter),this.onA11yChar=this._onA11yCharEmitter.event,this._onA11yTabEmitter=this.register(new a.EventEmitter),this.onA11yTab=this._onA11yTabEmitter.event,this._setup(),this.register(this._inputHandler.onRequestBell((()=>this.bell()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register((0,a.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,a.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,a.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,a.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter))}get buffer(){return this.buffers.active}get markers(){return this.buffer.markers}addMarker(e){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}bell(){this._onBell.fire()}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){e===this.cols&&t===this.rows||super.resize(e,t)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(r.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0})}}reset(){this.options.rows=this.rows,this.options.cols=this.cols,this._setup(),super.reset()}}t.Terminal=o}},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e].call(a.exports,a,a.exports,r),a.exports}var i={};(()=>{var e=i;Object.defineProperty(e,`__esModule`,{value:!0}),e.Terminal=void 0;let t=r(285),n=r(975),a=r(90),o=r(781),s=r(741),c=r(844),l=[`cols`,`rows`];class u extends c.Disposable{constructor(e){super(),this._core=this.register(new o.Terminal(e)),this._addonManager=this.register(new s.AddonManager),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){Object.defineProperty(this._publicOptions,e,{get:()=>this._core.options[e],set:t=>{this._checkReadonlyOptions(e),this._core.options[e]=t}});let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(l.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.options.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onLineFeed(){return this._core.onLineFeed}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onTitleChange(){return this._core.onTitleChange}get parser(){return this._checkProposedApi(),this._parser||=new n.ParserApi(this._core),this._parser}get unicode(){return this._checkProposedApi(),new a.UnicodeApi(this._core)}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._checkProposedApi(),this._buffer||=this.register(new t.BufferNamespaceApi(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}registerMarker(e=0){return this._checkProposedApi(),this._verifyIntegers(e),this._core.addMarker(e)}addMarker(e){return this.registerMarker(e)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
34
|
-
`,t)}reset(){this._core.reset()}loadAddon(e){this._addonManager.loadAddon(this,e)}_verifyIntegers(...e){for(let t of e)if(t===1/0||isNaN(t)||t%1!=0)throw Error(`This API only accepts integers`)}}e.Terminal=u})();var a=e;for(var o in i)a[o]=i[o];i.__esModule&&Object.defineProperty(a,`__esModule`,{value:!0})})()})}),yt=a.__toESM(_t(),1),bt=a.__toESM(vt(),1),xt=(i=class e{constructor(e){this.processes=new Map,this.spawnListeners=[],this.globalEnv=e?.env??{},this.nodePty=e?.nodePty}onSpawn(e){return this.spawnListeners.push(e),{dispose:()=>{this.spawnListeners=this.spawnListeners.filter(t=>t!==e)}}}setEnv(e){this.globalEnv={...this.globalEnv,...e},Object.keys(e).forEach(t=>{e[t]===``&&delete this.globalEnv[t]})}execute(t,n,r){let i=St(t,n,{name:`xterm-256color`,cols:e.COLUMNS,rows:e.ROWS,cwd:r?.cwd,env:{...globalThis.process.env,...this.globalEnv,...r?.env}},this.nodePty),a=new bt.default.Terminal({allowProposedApi:!0,convertEol:!0,scrollback:e.SCROLLBACK,cols:e.COLUMNS,rows:e.ROWS}),o=new yt.SerializeAddon;a.loadAddon(o);let s;i.onData(e=>{s=new Promise(t=>{a.write(e,t)})}),a.onData(e=>{i.write(e)});let c={command:t,args:n,cwd:r?.cwd??``,env:{...r?.env},startTimeMS:Date.now(),exitCode:void 0,exitSignal:void 0,pid:i.pid,pty:i,terminal:a,serializer:o,kill:e=>{i.kill(e)},onExit:e=>i.onExit(({exitCode:t,signal:n})=>{s?s.then(()=>{e(t,n)}):e(t,n)}),onOutput:e=>i.onData(t=>{e(t)}),sendInput:e=>{a.input(e)}};this.processes.set(i.pid,c),i.onExit(({exitCode:e,signal:t})=>{c.exitCode=e,c.exitSignal=t});for(let e of this.spawnListeners)e(c);return c}status(e){let t=this.processes.get(e);if(!t)throw Error(`Process with PID ${e} not found`);let n=this.readPlainOutput(e);return{pid:t.pid,command:t.command,title:t.pty.process,args:t.args,cwd:t.cwd,env:t.env,exit_code:t.exitCode,exit_signal:t.exitSignal,duration_ms:Date.now()-t.startTimeMS,output_total_lines:n.totalLines}}list(e){return Array.from(this.processes.values()).filter(t=>e||t.exitCode===void 0).map(e=>this.status(e.pid))}getProcess(e){return this.processes.get(e)}readANSIOutput(e,t){let n=this.processes.get(e);if(!n)throw Error(`Process with PID ${e} not found`);return n.serializer.serialize({scrollback:t})}readPlainOutput(t,n,r){let i=n?Math.max(0,n-1):0,a=r?Math.max(0,r-1):e.SCROLLBACK+e.ROWS-1,o=this.processes.get(t);if(!o)throw Error(`Process with PID ${t} not found`);let s=[];for(let t=0;t<e.SCROLLBACK+e.ROWS;t++){let e=o.terminal.buffer.normal.getLine(t);e&&s.push(e.translateToString(!0)??``)}for(;s.length>0&&s[s.length-1].trim()===``;)s.pop();return{lines:s.slice(i,a+1),totalLines:s.length}}close(){this.processes.forEach(e=>{e.pty.kill()})}},i.COLUMNS=80,i.ROWS=24,i.SCROLLBACK=128e3,i);let St=(e,t,n,r)=>{if(!r||globalThis.Bun!==void 0){let r=new f,i=new f,a=(0,l.spawn)(e,t,{env:n.env,cwd:n.cwd,stdio:`pipe`});return a.stdout.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.stderr.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.on(`exit`,(e,t)=>{let n=e??-1,i=t?n:void 0;r.emit({exitCode:n,signal:i})}),a.on(`error`,e=>{throw e}),{pid:a.pid??-1,process:``,onExit:e=>r.event(e),kill(e){a.kill(e)},onData:e=>i.event(e),write(e){a.stdin?.write(e)}}}return r.spawn(e,t,n)};var Ct=a.__commonJS({"../../node_modules/fast-fifo/fixed-size.js":((e,t)=>{t.exports=class{constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return this.buffer[this.top]===void 0?(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0):!1}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}})}),wt=a.__commonJS({"../../node_modules/fast-fifo/index.js":((e,t)=>{let n=Ct();t.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){let t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){this.length!==0&&this.length--;let e=this.tail.shift();if(e===void 0&&this.tail.next){let e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){let e=this.tail.peek();return e===void 0&&this.tail.next?this.tail.next.peek():e}isEmpty(){return this.length===0}}})}),Tt=a.__commonJS({"../../node_modules/b4a/index.js":((e,t)=>{function n(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function r(e){return Buffer.isEncoding(e)}function i(e,t,n){return Buffer.alloc(e,t,n)}function a(e){return Buffer.allocUnsafe(e)}function o(e){return Buffer.allocUnsafeSlow(e)}function s(e,t){return Buffer.byteLength(e,t)}function c(e,t){return Buffer.compare(e,t)}function l(e,t){return Buffer.concat(e,t)}function u(e,t,n,r,i){return b(e).copy(t,n,r,i)}function d(e,t){return b(e).equals(t)}function f(e,t,n,r,i){return b(e).fill(t,n,r,i)}function p(e,t,n){return Buffer.from(e,t,n)}function m(e,t,n,r){return b(e).includes(t,n,r)}function h(e,t,n,r){return b(e).indexOf(t,n,r)}function g(e,t,n,r){return b(e).lastIndexOf(t,n,r)}function _(e){return b(e).swap16()}function v(e){return b(e).swap32()}function y(e){return b(e).swap64()}function b(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function x(e,t,n,r){return b(e).toString(t,n,r)}function S(e,t,n,r,i){return b(e).write(t,n,r,i)}function C(e,t,n){return b(e).writeDoubleLE(t,n)}function w(e,t,n){return b(e).writeFloatLE(t,n)}function T(e,t,n){return b(e).writeUInt32LE(t,n)}function E(e,t,n){return b(e).writeInt32LE(t,n)}function D(e,t){return b(e).readDoubleLE(t)}function O(e,t){return b(e).readFloatLE(t)}function k(e,t){return b(e).readUInt32LE(t)}function A(e,t){return b(e).readInt32LE(t)}function j(e,t,n){return b(e).writeDoubleBE(t,n)}function M(e,t,n){return b(e).writeFloatBE(t,n)}function N(e,t,n){return b(e).writeUInt32BE(t,n)}function ee(e,t,n){return b(e).writeInt32BE(t,n)}function P(e,t){return b(e).readDoubleBE(t)}function F(e,t){return b(e).readFloatBE(t)}function te(e,t){return b(e).readUInt32BE(t)}function I(e,t){return b(e).readInt32BE(t)}t.exports={isBuffer:n,isEncoding:r,alloc:i,allocUnsafe:a,allocUnsafeSlow:o,byteLength:s,compare:c,concat:l,copy:u,equals:d,fill:f,from:p,includes:m,indexOf:h,lastIndexOf:g,swap16:_,swap32:v,swap64:y,toBuffer:b,toString:x,write:S,writeDoubleLE:C,writeFloatLE:w,writeUInt32LE:T,writeInt32LE:E,readDoubleLE:D,readFloatLE:O,readUInt32LE:k,readInt32LE:A,writeDoubleBE:j,writeFloatBE:M,writeUInt32BE:N,writeInt32BE:ee,readDoubleBE:P,readFloatBE:F,readUInt32BE:te,readInt32BE:I}})}),Et=a.__commonJS({"../../node_modules/text-decoder/lib/pass-through-decoder.js":((e,t)=>{let n=Tt();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})}),Dt=a.__commonJS({"../../node_modules/text-decoder/lib/utf8-decoder.js":((e,t)=>{let n=Tt();t.exports=class{constructor(){this.codePoint=0,this.bytesSeen=0,this.bytesNeeded=0,this.lowerBoundary=128,this.upperBoundary=191}get remaining(){return this.bytesSeen}decode(e){if(this.bytesNeeded===0){let t=!0;for(let n=Math.max(0,e.byteLength-4),r=e.byteLength;n<r&&t;n++)t=e[n]<=127;if(t)return n.toString(e,`utf8`)}let t=``;for(let n=0,r=e.byteLength;n<r;n++){let r=e[n];if(this.bytesNeeded===0){r<=127?t+=String.fromCharCode(r):(this.bytesSeen=1,r>=194&&r<=223?(this.bytesNeeded=2,this.codePoint=r&31):r>=224&&r<=239?(r===224?this.lowerBoundary=160:r===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.codePoint=r&15):r>=240&&r<=244?(r===240&&(this.lowerBoundary=144),r===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.codePoint=r&7):t+=`�`);continue}if(r<this.lowerBoundary||r>this.upperBoundary){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,t+=`�`;continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|r&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0)}return t}flush(){let e=this.bytesNeeded>0?`�`:``;return this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,e}}})}),Ot=a.__commonJS({"../../node_modules/text-decoder/index.js":((e,t)=>{let n=Et(),r=Dt();t.exports=class{constructor(e=`utf8`){switch(this.encoding=i(e),this.encoding){case`utf8`:this.decoder=new r;break;case`utf16le`:case`base64`:throw Error(`Unsupported encoding: `+this.encoding);default:this.decoder=new n(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return typeof e==`string`?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t=``;return e&&(t=this.push(e)),t+=this.decoder.flush(),t}};function i(e){switch(e=e.toLowerCase(),e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:throw Error(`Unknown encoding: `+e)}}})}),kt=a.__commonJS({"../../node_modules/streamx/index.js":((e,t)=>{let{EventEmitter:n}=q(`events`),r=Error(`Stream was destroyed`),i=Error(`Premature close`),a=wt(),o=Ot(),s=typeof queueMicrotask>`u`?e=>global.process.nextTick(e):queueMicrotask,c=(1<<29)-1,l=c^1;c^2;let u=1024,d=2048,f=4096,p=8192,m=16384,h=32768,g=65536,_=131072;16|g,f|128;let v=256|_;c^16,c^64,c^(64|g);let y=c^g;c^256,c^(128|p),c^u;let b=c^768,x=c^h;c^32;let S=c^_;c^v;let C=1<<18,w=2<<18,T=4<<18,E=8<<18,D=16<<18,O=32<<18,k=64<<18,A=128<<18,j=256<<18,M=512<<18,N=1024<<18;c^(C|j);let ee=c^T;c^(C|M),c^D,c^E;let P=c^A;c^w;let F=c^N,te=16|C,I=c^te,L=m|O,R=14|L;ee&536870847;let ne=A|h;ne&I;let z=33587215;u|16399;let re=m|143;u|143,u|16398,h|1,M|8388623,E|D,E|C;let B=270794767;T|C,C|j,O|134217742;let ie=Symbol.asyncIterator||Symbol(`asyncIterator`);var ae=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:r,byteLength:i,byteLengthWritable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||i||Ne,this.map=r||n,this.afterWrite=ue.bind(this),this.afterUpdateNextTick=pe.bind(this)}get ended(){return(this.stream._duplexState&O)!==0}push(e){return this.stream._duplexState&142606350?!1:(this.map!==null&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=E,!0):(this.stream._duplexState|=6291456,!1))}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=534773759),e}end(e){typeof e==`function`?this.stream.once(`finish`,e):e!=null&&this.push(e),this.stream._duplexState=(this.stream._duplexState|M)&ee}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&B)===2359296;)n.push(r._writableState.shift());if(r._duplexState&15)return t(null);r._writev(n,t)}update(){let e=this.stream;e._duplexState|=w;do{for(;(e._duplexState&B)===E;){let t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}e._duplexState&1310720||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536346623}updateNonPrimary(){let e=this.stream;if((e._duplexState&144965647)===M){e._duplexState|=C,e._final(H.bind(this));return}if((e._duplexState&14)==4){(e._duplexState&ne)===0&&(e._duplexState|=te,e._destroy(le.bind(this)));return}(e._duplexState&z)===1&&(e._duplexState=(e._duplexState|te)&l,e._open(he.bind(this)))}continueUpdate(){return(this.stream._duplexState&A)===0?!1:(this.stream._duplexState&=P,!0)}updateCallback(){(this.stream._duplexState&35127311)===T?this.update():this.updateNextTick()}updateNextTick(){(this.stream._duplexState&A)===0&&(this.stream._duplexState|=A,(this.stream._duplexState&w)===0&&s(this.afterUpdateNextTick))}},oe=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:r,byteLength:i,byteLengthReadable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||i||Ne,this.map=r||n,this.pipeTo=null,this.afterRead=de.bind(this),this.afterUpdateNextTick=fe.bind(this)}get ended(){return(this.stream._duplexState&m)!==0}pipe(e,t){if(this.pipeTo!==null)throw Error(`Can only pipe to one destination`);if(typeof t!=`function`&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new ce(this.stream,e,t),t&&this.stream.on(`error`,Pe),De(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,Pe),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,V.bind(this)),this.stream.emit(`piping`,e),e.emit(`pipe`,this.stream)}push(e){let t=this.stream;return e===null?(this.highWaterMark=0,t._duplexState=(t._duplexState|u)&536805311,!1):this.map!==null&&(e=this.map(e),e===null)?(t._duplexState&=y,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|128)&y,this.buffered<this.highWaterMark)}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=536862591),e}unshift(e){let t=[this.map===null?e:this.map(e)];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){let n=t[e];this.buffered+=this.byteLength(n),this.queue.push(n)}this.push(t[t.length-1])}read(){let e=this.stream;if((e._duplexState&re)===128){let t=this.shift();return this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t),t}return this.readAhead===!1&&(e._duplexState|=_,this.updateNextTick()),null}drain(){let e=this.stream;for(;(e._duplexState&re)===128&&e._duplexState&768;){let t=this.shift();this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t)}}update(){let e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(e._duplexState&214047)===_;)e._duplexState|=65552,e._read(this.afterRead),this.drain();(e._duplexState&12431)==4224&&(e._duplexState|=p,e.emit(`readable`)),e._duplexState&80||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536870879}updateNonPrimary(){let e=this.stream;if((e._duplexState&1167)===u&&(e._duplexState=(e._duplexState|m)&536869887,e.emit(`end`),(e._duplexState&R)===L&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){(e._duplexState&ne)===0&&(e._duplexState|=te,e._destroy(le.bind(this)));return}(e._duplexState&z)===1&&(e._duplexState=(e._duplexState|te)&l,e._open(he.bind(this)))}continueUpdate(){return(this.stream._duplexState&h)===0?!1:(this.stream._duplexState&=x,!0)}updateCallback(){(this.stream._duplexState&32879)==64?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&32769||(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}updateNextTick(){(this.stream._duplexState&h)===0&&(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}},se=class{constructor(e){this.data=null,this.afterTransform=ge.bind(e),this.afterFinal=null}},ce=class{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){if(t&&(this.error=t),e===this.to&&(this.to=null,this.from!==null)){((this.from._duplexState&m)===0||!this.pipeToFinished)&&this.from.destroy(this.error||Error(`Writable stream closed prematurely`));return}if(e===this.from&&(this.from=null,this.to!==null)){(e._duplexState&m)===0&&this.to.destroy(this.error||Error(`Readable stream closed before ending`));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function V(){this.stream._duplexState|=512,this.updateCallback()}function H(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=O,t.emit(`finish`)),(t._duplexState&R)===L&&(t._duplexState|=4),t._duplexState&=402391039,(t._duplexState&w)===0?this.update():this.updateNextTick()}function le(e){let t=this.stream;!e&&this.error!==r&&(e=this.error),e&&t.emit(`error`,e),t._duplexState|=8,t.emit(`close`);let n=t._readableState,i=t._writableState;if(n!==null&&n.pipeline!==null&&n.pipeline.done(t,e),i!==null){for(;i.drains!==null&&i.drains.length>0;)i.drains.shift().resolve(!1);i.pipeline!==null&&i.pipeline.done(t,e)}}function ue(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&me(this.drains),(t._duplexState&6553615)===D&&(t._duplexState&=532676607,(t._duplexState&k)===k&&t.emit(`drain`)),this.updateCallback()}function de(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=S),this.updateCallback()}function fe(){this.stream._duplexState&32||(this.stream._duplexState&=x,this.update())}function pe(){(this.stream._duplexState&w)===0&&(this.stream._duplexState&=P,this.update())}function me(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function he(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=T),t.emit(`open`)),t._duplexState&=I,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function ge(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function _e(e){this._readableState!==null&&(e===`data`&&(this._duplexState|=d|v,this._readableState.updateNextTick()),e===`readable`&&(this._duplexState|=f,this._readableState.updateNextTick())),this._writableState!==null&&e===`drain`&&(this._duplexState|=k,this._writableState.updateNextTick())}var ve=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,Fe.bind(this))),this.on(`newListener`,_e)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return this._readableState===null?void 0:!0}get writable(){return this._writableState===null?void 0:!0}get destroyed(){return(this._duplexState&8)!=0}get destroying(){return(this._duplexState&14)!=0}destroy(e){this._duplexState&14||(e||=r,this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=e),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},ye=class e extends ve{constructor(e){super(e),this._duplexState|=O|131073,this._readableState=new oe(this,e),e&&(this._readableState.readAhead===!1&&(this._duplexState&=S),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}setEncoding(e){let t=new o(e),n=this._readableState.map||Ee;return this._readableState.map=r,this;function r(e){let r=t.push(e);return r===``&&(e.byteLength!==0||t.remaining>0)?null:n(r)}}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=v,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator(t,n){let r,i=new e({...n,read(e){t.next().then(a).then(e.bind(null,null)).catch(e)},predestroy(){r=t.return()},destroy(e){if(!r)return e(null);r.then(e.bind(null,null)).catch(e)}});return i;function a(e){e.done?i.push(null):i.push(e.value)}}static from(t,n){if(G(t))return t;if(t[ie])return this._fromAsyncIterator(t[ie](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(e){this.push(r===t.length?null:t[r++]),e(null)}})}static isBackpressured(e){return(e._duplexState&17422)!=0||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return(e._duplexState&256)==0}[ie](){let e=this,t=null,n=null,i=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,a),this.on(`close`,o),{[ie](){return this},next(){return new Promise(function(t,r){n=t,i=r;let a=e.read();a===null?e._duplexState&8&&s(null):s(a)})},return(){return c(null)},throw(e){return c(e)}};function a(){n!==null&&s(e.read())}function o(){n!==null&&s(null)}function s(a){i!==null&&(t?i(t):a===null&&(e._duplexState&m)===0?i(r):n({value:a,done:a===null}),i=n=null)}function c(t){return e.destroy(t),new Promise((n,r)=>{if(e._duplexState&8)return n({value:void 0,done:!0});e.once(`close`,function(){t?r(t):n({value:void 0,done:!0})})})}}},U=class extends ve{constructor(e){super(e),this._duplexState|=1|m,this._writableState=new ae(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=N}uncork(){this._duplexState&=F,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return(e._duplexState&146800654)!=0}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(Ie(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&j?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},be=class extends ye{constructor(e){super(e),this._duplexState=1|this._duplexState&_,this._writableState=new ae(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=N}uncork(){this._duplexState&=F,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},xe=class extends be{constructor(e){super(e),this._transformState=new se(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(this._transformState.data!==null){let t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(Ce.bind(this))}},Se=class extends xe{};function Ce(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function we(...e){return new Promise((t,n)=>Te(...e,e=>{if(e)return n(e);t()}))}function Te(e,...t){let n=Array.isArray(e)?[...e,...t]:[e,...t],r=n.length&&typeof n[n.length-1]==`function`?n.pop():null;if(n.length<2)throw Error(`Pipeline requires at least 2 streams`);let a=n[0],o=null,s=null;for(let e=1;e<n.length;e++)o=n[e],De(a)?a.pipe(o,l):(c(a,!0,e>1,l),a.pipe(o)),a=o;if(r){let e=!1,t=De(o)||!!(o._writableState&&o._writableState.autoDestroy);o.on(`error`,e=>{s===null&&(s=e)}),o.on(`finish`,()=>{e=!0,t||r(s)}),t&&o.on(`close`,()=>r(s||(e?null:i)))}return o;function c(e,t,n,r){e.on(`error`,r),e.on(`close`,a);function a(){if(t&&e._readableState&&!e._readableState.ended||n&&e._writableState&&!e._writableState.ended)return r(i)}}function l(e){if(!(!e||s)){s=e;for(let t of n)t.destroy(e)}}}function Ee(e){return e}function W(e){return!!e._readableState||!!e._writableState}function De(e){return typeof e._duplexState==`number`&&W(e)}function Oe(e){return!!e._readableState&&e._readableState.ended}function ke(e){return!!e._writableState&&e._writableState.ended}function Ae(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===r?null:n}function G(e){return De(e)&&e.readable}function je(e){return(e._duplexState&1)!=1||(e._duplexState&ne)!==0}function Me(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Ne(e){return Me(e)?e.byteLength:1024}function Pe(){}function Fe(){this.destroy(Error(`Stream aborted.`))}function Ie(e){return e._writev!==U.prototype._writev&&e._writev!==be.prototype._writev}t.exports={pipeline:Te,pipelinePromise:we,isStream:W,isStreamx:De,isEnded:Oe,isFinished:ke,isDisturbed:je,getStreamError:Ae,Stream:ve,Writable:U,Readable:ye,Duplex:be,Transform:xe,PassThrough:Se}})}),At=a.__commonJS({"../../node_modules/tar-stream/headers.js":(e=>{let t=Tt(),n=t.from([117,115,116,97,114,0]),r=t.from([48,48]),i=t.from([117,115,116,97,114,32]),a=t.from([32,0]);e.decodeLongPath=function(e,t){return v(e,0,e.length,t)},e.encodePax=function(e){let n=``;e.name&&(n+=y(` path=`+e.name+`
|
|
34
|
+
`,t)}reset(){this._core.reset()}loadAddon(e){this._addonManager.loadAddon(this,e)}_verifyIntegers(...e){for(let t of e)if(t===1/0||isNaN(t)||t%1!=0)throw Error(`This API only accepts integers`)}}e.Terminal=u})();var a=e;for(var o in i)a[o]=i[o];i.__esModule&&Object.defineProperty(a,`__esModule`,{value:!0})})()})}),xt=a.__toESM(yt(),1),St=a.__toESM(bt(),1),Ct=(i=class e{constructor(e){this.processes=new Map,this.spawnListeners=[],this.globalEnv=e?.env??{},this.nodePty=e?.nodePty}onSpawn(e){return this.spawnListeners.push(e),{dispose:()=>{this.spawnListeners=this.spawnListeners.filter(t=>t!==e)}}}setEnv(e){this.globalEnv={...this.globalEnv,...e},Object.keys(e).forEach(t=>{e[t]===``&&delete this.globalEnv[t]})}execute(t,n,r){let i=wt(t,n,{name:`xterm-256color`,cols:e.COLUMNS,rows:e.ROWS,cwd:r?.cwd,env:{...globalThis.process.env,...this.globalEnv,...r?.env}},this.nodePty),a=new St.default.Terminal({allowProposedApi:!0,convertEol:!0,scrollback:e.SCROLLBACK,cols:e.COLUMNS,rows:e.ROWS}),o=new xt.SerializeAddon;a.loadAddon(o);let s;i.onData(e=>{s=new Promise(t=>{a.write(e,t)})}),a.onData(e=>{i.write(e)});let c={command:t,args:n,cwd:r?.cwd??``,env:{...r?.env},startTimeMS:Date.now(),exitCode:void 0,exitSignal:void 0,pid:i.pid,pty:i,terminal:a,serializer:o,kill:e=>{i.kill(e)},onExit:e=>i.onExit(({exitCode:t,signal:n})=>{s?s.then(()=>{e(t,n)}):e(t,n)}),onOutput:e=>i.onData(t=>{e(t)}),sendInput:e=>{a.input(e)}};this.processes.set(i.pid,c),i.onExit(({exitCode:e,signal:t})=>{c.exitCode=e,c.exitSignal=t});for(let e of this.spawnListeners)e(c);return c}status(e){let t=this.processes.get(e);if(!t)throw Error(`Process with PID ${e} not found`);let n=this.readPlainOutput(e);return{pid:t.pid,command:t.command,title:t.pty.process,args:t.args,cwd:t.cwd,env:t.env,exit_code:t.exitCode,exit_signal:t.exitSignal,duration_ms:Date.now()-t.startTimeMS,output_total_lines:n.totalLines}}list(e){return Array.from(this.processes.values()).filter(t=>e||t.exitCode===void 0).map(e=>this.status(e.pid))}getProcess(e){return this.processes.get(e)}readANSIOutput(e,t){let n=this.processes.get(e);if(!n)throw Error(`Process with PID ${e} not found`);return n.serializer.serialize({scrollback:t})}readPlainOutput(t,n,r){let i=n?Math.max(0,n-1):0,a=r?Math.max(0,r-1):e.SCROLLBACK+e.ROWS-1,o=this.processes.get(t);if(!o)throw Error(`Process with PID ${t} not found`);let s=[];for(let t=0;t<e.SCROLLBACK+e.ROWS;t++){let e=o.terminal.buffer.normal.getLine(t);e&&s.push(e.translateToString(!0)??``)}for(;s.length>0&&s[s.length-1].trim()===``;)s.pop();return{lines:s.slice(i,a+1),totalLines:s.length}}close(){this.processes.forEach(e=>{e.pty.kill()})}},i.COLUMNS=80,i.ROWS=24,i.SCROLLBACK=128e3,i);let wt=(e,t,n,r)=>{if(!r||globalThis.Bun!==void 0){let r=new f,i=new f,a=(0,l.spawn)(e,t,{env:n.env,cwd:n.cwd,stdio:`pipe`});return a.stdout.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.stderr.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.on(`exit`,(e,t)=>{let n=e??-1,i=t?n:void 0;r.emit({exitCode:n,signal:i})}),a.on(`error`,e=>{throw e}),{pid:a.pid??-1,process:``,onExit:e=>r.event(e),kill(e){a.kill(e)},onData:e=>i.event(e),write(e){a.stdin?.write(e)}}}return r.spawn(e,t,n)};var Tt=a.__commonJS({"../../node_modules/fast-fifo/fixed-size.js":((e,t)=>{t.exports=class{constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return this.buffer[this.top]===void 0?(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0):!1}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}})}),Et=a.__commonJS({"../../node_modules/fast-fifo/index.js":((e,t)=>{let n=Tt();t.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){let t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){this.length!==0&&this.length--;let e=this.tail.shift();if(e===void 0&&this.tail.next){let e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){let e=this.tail.peek();return e===void 0&&this.tail.next?this.tail.next.peek():e}isEmpty(){return this.length===0}}})}),Dt=a.__commonJS({"../../node_modules/b4a/index.js":((e,t)=>{function n(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function r(e){return Buffer.isEncoding(e)}function i(e,t,n){return Buffer.alloc(e,t,n)}function a(e){return Buffer.allocUnsafe(e)}function o(e){return Buffer.allocUnsafeSlow(e)}function s(e,t){return Buffer.byteLength(e,t)}function c(e,t){return Buffer.compare(e,t)}function l(e,t){return Buffer.concat(e,t)}function u(e,t,n,r,i){return b(e).copy(t,n,r,i)}function d(e,t){return b(e).equals(t)}function f(e,t,n,r,i){return b(e).fill(t,n,r,i)}function p(e,t,n){return Buffer.from(e,t,n)}function m(e,t,n,r){return b(e).includes(t,n,r)}function h(e,t,n,r){return b(e).indexOf(t,n,r)}function g(e,t,n,r){return b(e).lastIndexOf(t,n,r)}function _(e){return b(e).swap16()}function v(e){return b(e).swap32()}function y(e){return b(e).swap64()}function b(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function x(e,t,n,r){return b(e).toString(t,n,r)}function S(e,t,n,r,i){return b(e).write(t,n,r,i)}function C(e,t,n){return b(e).writeDoubleLE(t,n)}function w(e,t,n){return b(e).writeFloatLE(t,n)}function T(e,t,n){return b(e).writeUInt32LE(t,n)}function E(e,t,n){return b(e).writeInt32LE(t,n)}function D(e,t){return b(e).readDoubleLE(t)}function O(e,t){return b(e).readFloatLE(t)}function k(e,t){return b(e).readUInt32LE(t)}function A(e,t){return b(e).readInt32LE(t)}function j(e,t,n){return b(e).writeDoubleBE(t,n)}function M(e,t,n){return b(e).writeFloatBE(t,n)}function N(e,t,n){return b(e).writeUInt32BE(t,n)}function ee(e,t,n){return b(e).writeInt32BE(t,n)}function P(e,t){return b(e).readDoubleBE(t)}function F(e,t){return b(e).readFloatBE(t)}function te(e,t){return b(e).readUInt32BE(t)}function I(e,t){return b(e).readInt32BE(t)}t.exports={isBuffer:n,isEncoding:r,alloc:i,allocUnsafe:a,allocUnsafeSlow:o,byteLength:s,compare:c,concat:l,copy:u,equals:d,fill:f,from:p,includes:m,indexOf:h,lastIndexOf:g,swap16:_,swap32:v,swap64:y,toBuffer:b,toString:x,write:S,writeDoubleLE:C,writeFloatLE:w,writeUInt32LE:T,writeInt32LE:E,readDoubleLE:D,readFloatLE:O,readUInt32LE:k,readInt32LE:A,writeDoubleBE:j,writeFloatBE:M,writeUInt32BE:N,writeInt32BE:ee,readDoubleBE:P,readFloatBE:F,readUInt32BE:te,readInt32BE:I}})}),Ot=a.__commonJS({"../../node_modules/text-decoder/lib/pass-through-decoder.js":((e,t)=>{let n=Dt();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})}),kt=a.__commonJS({"../../node_modules/text-decoder/lib/utf8-decoder.js":((e,t)=>{let n=Dt();t.exports=class{constructor(){this.codePoint=0,this.bytesSeen=0,this.bytesNeeded=0,this.lowerBoundary=128,this.upperBoundary=191}get remaining(){return this.bytesSeen}decode(e){if(this.bytesNeeded===0){let t=!0;for(let n=Math.max(0,e.byteLength-4),r=e.byteLength;n<r&&t;n++)t=e[n]<=127;if(t)return n.toString(e,`utf8`)}let t=``;for(let n=0,r=e.byteLength;n<r;n++){let r=e[n];if(this.bytesNeeded===0){r<=127?t+=String.fromCharCode(r):(this.bytesSeen=1,r>=194&&r<=223?(this.bytesNeeded=2,this.codePoint=r&31):r>=224&&r<=239?(r===224?this.lowerBoundary=160:r===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.codePoint=r&15):r>=240&&r<=244?(r===240&&(this.lowerBoundary=144),r===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.codePoint=r&7):t+=`�`);continue}if(r<this.lowerBoundary||r>this.upperBoundary){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,t+=`�`;continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|r&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0)}return t}flush(){let e=this.bytesNeeded>0?`�`:``;return this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,e}}})}),At=a.__commonJS({"../../node_modules/text-decoder/index.js":((e,t)=>{let n=Ot(),r=kt();t.exports=class{constructor(e=`utf8`){switch(this.encoding=i(e),this.encoding){case`utf8`:this.decoder=new r;break;case`utf16le`:case`base64`:throw Error(`Unsupported encoding: `+this.encoding);default:this.decoder=new n(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return typeof e==`string`?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t=``;return e&&(t=this.push(e)),t+=this.decoder.flush(),t}};function i(e){switch(e=e.toLowerCase(),e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:throw Error(`Unknown encoding: `+e)}}})}),jt=a.__commonJS({"../../node_modules/streamx/index.js":((e,t)=>{let{EventEmitter:n}=G(`events`),r=Error(`Stream was destroyed`),i=Error(`Premature close`),a=Et(),o=At(),s=typeof queueMicrotask>`u`?e=>global.process.nextTick(e):queueMicrotask,c=(1<<29)-1,l=c^1;c^2;let u=1024,d=2048,f=4096,p=8192,m=16384,h=32768,g=65536,_=131072;16|g,f|128;let v=256|_;c^16,c^64,c^(64|g);let y=c^g;c^256,c^(128|p),c^u;let b=c^768,x=c^h;c^32;let S=c^_;c^v;let C=1<<18,w=2<<18,T=4<<18,E=8<<18,D=16<<18,O=32<<18,k=64<<18,A=128<<18,j=256<<18,M=512<<18,N=1024<<18;c^(C|j);let ee=c^T;c^(C|M),c^D,c^E;let P=c^A;c^w;let F=c^N,te=16|C,I=c^te,L=m|O,R=14|L;ee&536870847;let ne=A|h;ne&I;let z=33587215;u|16399;let re=m|143;u|143,u|16398,h|1,M|8388623,E|D,E|C;let B=270794767;T|C,C|j,O|134217742;let ie=Symbol.asyncIterator||Symbol(`asyncIterator`);var ae=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:r,byteLength:i,byteLengthWritable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||i||Fe,this.map=r||n,this.afterWrite=de.bind(this),this.afterUpdateNextTick=me.bind(this)}get ended(){return(this.stream._duplexState&O)!==0}push(e){return this.stream._duplexState&142606350?!1:(this.map!==null&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=E,!0):(this.stream._duplexState|=6291456,!1))}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=534773759),e}end(e){typeof e==`function`?this.stream.once(`finish`,e):e!=null&&this.push(e),this.stream._duplexState=(this.stream._duplexState|M)&ee}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&B)===2359296;)n.push(r._writableState.shift());if(r._duplexState&15)return t(null);r._writev(n,t)}update(){let e=this.stream;e._duplexState|=w;do{for(;(e._duplexState&B)===E;){let t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}e._duplexState&1310720||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536346623}updateNonPrimary(){let e=this.stream;if((e._duplexState&144965647)===M){e._duplexState|=C,e._final(le.bind(this));return}if((e._duplexState&14)==4){(e._duplexState&ne)===0&&(e._duplexState|=te,e._destroy(ue.bind(this)));return}(e._duplexState&z)===1&&(e._duplexState=(e._duplexState|te)&l,e._open(ge.bind(this)))}continueUpdate(){return(this.stream._duplexState&A)===0?!1:(this.stream._duplexState&=P,!0)}updateCallback(){(this.stream._duplexState&35127311)===T?this.update():this.updateNextTick()}updateNextTick(){(this.stream._duplexState&A)===0&&(this.stream._duplexState|=A,(this.stream._duplexState&w)===0&&s(this.afterUpdateNextTick))}},oe=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:r,byteLength:i,byteLengthReadable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||i||Fe,this.map=r||n,this.pipeTo=null,this.afterRead=fe.bind(this),this.afterUpdateNextTick=pe.bind(this)}get ended(){return(this.stream._duplexState&m)!==0}pipe(e,t){if(this.pipeTo!==null)throw Error(`Can only pipe to one destination`);if(typeof t!=`function`&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new ce(this.stream,e,t),t&&this.stream.on(`error`,Ie),ke(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,Ie),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,V.bind(this)),this.stream.emit(`piping`,e),e.emit(`pipe`,this.stream)}push(e){let t=this.stream;return e===null?(this.highWaterMark=0,t._duplexState=(t._duplexState|u)&536805311,!1):this.map!==null&&(e=this.map(e),e===null)?(t._duplexState&=y,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|128)&y,this.buffered<this.highWaterMark)}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=536862591),e}unshift(e){let t=[this.map===null?e:this.map(e)];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){let n=t[e];this.buffered+=this.byteLength(n),this.queue.push(n)}this.push(t[t.length-1])}read(){let e=this.stream;if((e._duplexState&re)===128){let t=this.shift();return this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t),t}return this.readAhead===!1&&(e._duplexState|=_,this.updateNextTick()),null}drain(){let e=this.stream;for(;(e._duplexState&re)===128&&e._duplexState&768;){let t=this.shift();this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t)}}update(){let e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(e._duplexState&214047)===_;)e._duplexState|=65552,e._read(this.afterRead),this.drain();(e._duplexState&12431)==4224&&(e._duplexState|=p,e.emit(`readable`)),e._duplexState&80||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536870879}updateNonPrimary(){let e=this.stream;if((e._duplexState&1167)===u&&(e._duplexState=(e._duplexState|m)&536869887,e.emit(`end`),(e._duplexState&R)===L&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){(e._duplexState&ne)===0&&(e._duplexState|=te,e._destroy(ue.bind(this)));return}(e._duplexState&z)===1&&(e._duplexState=(e._duplexState|te)&l,e._open(ge.bind(this)))}continueUpdate(){return(this.stream._duplexState&h)===0?!1:(this.stream._duplexState&=x,!0)}updateCallback(){(this.stream._duplexState&32879)==64?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&32769||(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}updateNextTick(){(this.stream._duplexState&h)===0&&(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}},se=class{constructor(e){this.data=null,this.afterTransform=_e.bind(e),this.afterFinal=null}},ce=class{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){if(t&&(this.error=t),e===this.to&&(this.to=null,this.from!==null)){((this.from._duplexState&m)===0||!this.pipeToFinished)&&this.from.destroy(this.error||Error(`Writable stream closed prematurely`));return}if(e===this.from&&(this.from=null,this.to!==null)){(e._duplexState&m)===0&&this.to.destroy(this.error||Error(`Readable stream closed before ending`));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function V(){this.stream._duplexState|=512,this.updateCallback()}function le(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=O,t.emit(`finish`)),(t._duplexState&R)===L&&(t._duplexState|=4),t._duplexState&=402391039,(t._duplexState&w)===0?this.update():this.updateNextTick()}function ue(e){let t=this.stream;!e&&this.error!==r&&(e=this.error),e&&t.emit(`error`,e),t._duplexState|=8,t.emit(`close`);let n=t._readableState,i=t._writableState;if(n!==null&&n.pipeline!==null&&n.pipeline.done(t,e),i!==null){for(;i.drains!==null&&i.drains.length>0;)i.drains.shift().resolve(!1);i.pipeline!==null&&i.pipeline.done(t,e)}}function de(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&he(this.drains),(t._duplexState&6553615)===D&&(t._duplexState&=532676607,(t._duplexState&k)===k&&t.emit(`drain`)),this.updateCallback()}function fe(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=S),this.updateCallback()}function pe(){this.stream._duplexState&32||(this.stream._duplexState&=x,this.update())}function me(){(this.stream._duplexState&w)===0&&(this.stream._duplexState&=P,this.update())}function he(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function ge(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=T),t.emit(`open`)),t._duplexState&=I,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function _e(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function ve(e){this._readableState!==null&&(e===`data`&&(this._duplexState|=d|v,this._readableState.updateNextTick()),e===`readable`&&(this._duplexState|=f,this._readableState.updateNextTick())),this._writableState!==null&&e===`drain`&&(this._duplexState|=k,this._writableState.updateNextTick())}var ye=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,Le.bind(this))),this.on(`newListener`,ve)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return this._readableState===null?void 0:!0}get writable(){return this._writableState===null?void 0:!0}get destroyed(){return(this._duplexState&8)!=0}get destroying(){return(this._duplexState&14)!=0}destroy(e){this._duplexState&14||(e||=r,this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=e),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},be=class e extends ye{constructor(e){super(e),this._duplexState|=O|131073,this._readableState=new oe(this,e),e&&(this._readableState.readAhead===!1&&(this._duplexState&=S),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}setEncoding(e){let t=new o(e),n=this._readableState.map||De;return this._readableState.map=r,this;function r(e){let r=t.push(e);return r===``&&(e.byteLength!==0||t.remaining>0)?null:n(r)}}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=v,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator(t,n){let r,i=new e({...n,read(e){t.next().then(a).then(e.bind(null,null)).catch(e)},predestroy(){r=t.return()},destroy(e){if(!r)return e(null);r.then(e.bind(null,null)).catch(e)}});return i;function a(e){e.done?i.push(null):i.push(e.value)}}static from(t,n){if(U(t))return t;if(t[ie])return this._fromAsyncIterator(t[ie](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(e){this.push(r===t.length?null:t[r++]),e(null)}})}static isBackpressured(e){return(e._duplexState&17422)!=0||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return(e._duplexState&256)==0}[ie](){let e=this,t=null,n=null,i=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,a),this.on(`close`,o),{[ie](){return this},next(){return new Promise(function(t,r){n=t,i=r;let a=e.read();a===null?e._duplexState&8&&s(null):s(a)})},return(){return c(null)},throw(e){return c(e)}};function a(){n!==null&&s(e.read())}function o(){n!==null&&s(null)}function s(a){i!==null&&(t?i(t):a===null&&(e._duplexState&m)===0?i(r):n({value:a,done:a===null}),i=n=null)}function c(t){return e.destroy(t),new Promise((n,r)=>{if(e._duplexState&8)return n({value:void 0,done:!0});e.once(`close`,function(){t?r(t):n({value:void 0,done:!0})})})}}},H=class extends ye{constructor(e){super(e),this._duplexState|=1|m,this._writableState=new ae(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=N}uncork(){this._duplexState&=F,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return(e._duplexState&146800654)!=0}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(Re(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&j?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},xe=class extends be{constructor(e){super(e),this._duplexState=1|this._duplexState&_,this._writableState=new ae(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=N}uncork(){this._duplexState&=F,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},Se=class extends xe{constructor(e){super(e),this._transformState=new se(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(this._transformState.data!==null){let t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(we.bind(this))}},Ce=class extends Se{};function we(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function Te(...e){return new Promise((t,n)=>Ee(...e,e=>{if(e)return n(e);t()}))}function Ee(e,...t){let n=Array.isArray(e)?[...e,...t]:[e,...t],r=n.length&&typeof n[n.length-1]==`function`?n.pop():null;if(n.length<2)throw Error(`Pipeline requires at least 2 streams`);let a=n[0],o=null,s=null;for(let e=1;e<n.length;e++)o=n[e],ke(a)?a.pipe(o,l):(c(a,!0,e>1,l),a.pipe(o)),a=o;if(r){let e=!1,t=ke(o)||!!(o._writableState&&o._writableState.autoDestroy);o.on(`error`,e=>{s===null&&(s=e)}),o.on(`finish`,()=>{e=!0,t||r(s)}),t&&o.on(`close`,()=>r(s||(e?null:i)))}return o;function c(e,t,n,r){e.on(`error`,r),e.on(`close`,a);function a(){if(t&&e._readableState&&!e._readableState.ended||n&&e._writableState&&!e._writableState.ended)return r(i)}}function l(e){if(!(!e||s)){s=e;for(let t of n)t.destroy(e)}}}function De(e){return e}function Oe(e){return!!e._readableState||!!e._writableState}function ke(e){return typeof e._duplexState==`number`&&Oe(e)}function Ae(e){return!!e._readableState&&e._readableState.ended}function je(e){return!!e._writableState&&e._writableState.ended}function Me(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===r?null:n}function U(e){return ke(e)&&e.readable}function Ne(e){return(e._duplexState&1)!=1||(e._duplexState&ne)!==0}function Pe(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Fe(e){return Pe(e)?e.byteLength:1024}function Ie(){}function Le(){this.destroy(Error(`Stream aborted.`))}function Re(e){return e._writev!==H.prototype._writev&&e._writev!==xe.prototype._writev}t.exports={pipeline:Ee,pipelinePromise:Te,isStream:Oe,isStreamx:ke,isEnded:Ae,isFinished:je,isDisturbed:Ne,getStreamError:Me,Stream:ye,Writable:H,Readable:be,Duplex:xe,Transform:Se,PassThrough:Ce}})}),Mt=a.__commonJS({"../../node_modules/tar-stream/headers.js":(e=>{let t=Dt(),n=t.from([117,115,116,97,114,0]),r=t.from([48,48]),i=t.from([117,115,116,97,114,32]),a=t.from([32,0]);e.decodeLongPath=function(e,t){return v(e,0,e.length,t)},e.encodePax=function(e){let n=``;e.name&&(n+=y(` path=`+e.name+`
|
|
35
35
|
`)),e.linkname&&(n+=y(` linkpath=`+e.linkname+`
|
|
36
36
|
`));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
|
|
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}})}),jt=a.__commonJS({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=kt(),a=wt(),o=Tt(),s=At(),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}})}),Mt=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=q(`fs`).constants||n}catch{t.exports=n}})}),Nt=a.__commonJS({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=kt(),a=Tt(),o=Mt(),s=At(),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)}})}),Pt=a.__commonJS({"../../node_modules/tar-stream/index.js":(e=>{e.extract=jt(),e.pack=Nt()})}),Ft=a.__toESM(Pt(),1);let It=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=Ft.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{}}})},Lt=(e,t)=>e.length<=t?e:e.slice(e.length-t),Rt=(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 zt=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 xt({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=Rt(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 It(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 pt(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(`
|
|
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=Lt(this.processManager.readANSIOutput(i.pid),64e3),f=Rt(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 zt}})})}),Vo=K({"../../node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{To(),e.Server=Bo().Server})}),Ho=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}=Vo(),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 Uo=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}({}),Wo=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}({});Uo.REQUEST,v.z.string(),Uo.PROXY_INIT,v.z.object({method:v.z.string(),headers:v.z.record(v.z.string(),v.z.string()),url:v.z.string()}),Uo.PROXY_BODY,v.z.instanceof(Uint8Array),Uo.PROXY_WEBSOCKET_MESSAGE,v.z.object({type:v.z.enum([`text`,`binary`]),data:v.z.instanceof(Uint8Array)}),Uo.PROXY_WEBSOCKET_CLOSE,v.z.object({code:v.z.number().optional(),reason:v.z.string().optional()}),Wo.RESPONSE,v.z.string(),Wo.NOTIFICATION,v.z.string(),Wo.PROXY_INIT,v.z.object({status_code:v.z.number(),status_message:v.z.string(),headers:v.z.record(v.z.string(),v.z.string())}),Wo.PROXY_DATA,v.z.instanceof(Uint8Array),Wo.PROXY_WEBSOCKET_MESSAGE,v.z.instanceof(Uint8Array),Wo.PROXY_WEBSOCKET_CLOSE,v.z.object({code:v.z.number(),reason:v.z.string()}),Uo.PROXY_INIT,v.z.string(),v.z.record(v.z.string(),v.z.string()),v.z.string(),v.z.object({command:v.z.string(),args:v.z.array(v.z.string()),env:v.z.record(v.z.string(),v.z.string()).optional(),cwd:v.z.string().optional()}),v.z.object({pid:v.z.number(),data:v.z.string()}),v.z.object({pid:v.z.number(),output_idle_timeout_ms:v.z.number().optional(),timeout_ms:v.z.number().optional()}),v.z.object({include_dead:v.z.boolean().optional()}),v.z.object({pid:v.z.number(),start_line:v.z.number().optional(),end_line:v.z.number().optional()}),v.z.object({pid:v.z.number(),signal:v.z.string().optional()}),v.z.object({env:v.z.record(v.z.string(),v.z.string())}),v.z.object({path:v.z.string(),line_start:v.z.number().optional(),line_end:v.z.number().optional()}),v.z.object({path:v.z.string(),content:v.z.string(),base64:v.z.boolean().optional(),mode:v.z.number().optional()}),v.z.object({path:v.z.string()}),v.z.object({path:v.z.string()}),v.z.object({path:v.z.string()});const Go=v.z.object({pid:v.z.number(),command:v.z.string(),args:v.z.array(v.z.string()),title:v.z.string().optional(),cwd:v.z.string(),env:v.z.record(v.z.string(),v.z.string()),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional(),duration_ms:v.z.number().optional(),output_total_lines:v.z.number()});Go.extend({ansi_output:v.z.string(),plain_output:v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number()})}),v.z.object({pid:v.z.number()}),v.z.object({}),v.z.object({processes:v.z.array(Go)}),v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number(),duration_ms:v.z.number(),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional()}),v.z.object({}),v.z.object({}),v.z.object({total_lines:v.z.number(),lines_read:v.z.number(),start_line:v.z.number(),content:v.z.string(),mime_type:v.z.string()}),v.z.object({}),v.z.object({entries:v.z.array(v.z.object({name:v.z.string(),type:v.z.enum([`file`,`directory`,`symlink`])}))}),v.z.object({}),v.z.object({deployment_id:v.z.string()});const Ko=v.z.object({type:v.z.enum([`create`,`update`,`delete`]),path:v.z.string()}),qo=v.z.object({type:v.z.enum([`context`,`added`,`deleted`]),content:v.z.string(),oldLineNumber:v.z.number().optional(),newLineNumber:v.z.number().optional()}),Jo=v.z.object({oldStart:v.z.number(),oldLines:v.z.number(),newStart:v.z.number(),newLines:v.z.number(),lines:v.z.array(qo)}),Yo=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:v.z.string().optional(),insertions:v.z.number(),deletions:v.z.number(),chunks:v.z.array(Jo)}),Xo=v.z.object({totalFiles:v.z.number(),totalInsertions:v.z.number(),totalDeletions:v.z.number(),netChange:v.z.number(),startHash:v.z.string().optional(),currentHash:v.z.string().optional(),timespan:v.z.number(),files:v.z.array(Yo)}),Zo=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:v.z.boolean()}),Qo=v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),email:v.z.string(),date:v.z.date(),timestamp:v.z.date(),filesChanged:v.z.number(),insertions:v.z.number(),deletions:v.z.number(),commitDiff:v.z.array(Yo).optional()});v.z.object({files:v.z.array(Zo),branch:v.z.string(),ahead:v.z.number(),behind:v.z.number(),timestamp:v.z.date(),sessionDiff:Xo.optional(),workingDirectoryDiff:Xo.optional(),newCommits:v.z.array(Qo),currentCommit:v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),date:v.z.date()}).optional(),diffSkipped:v.z.boolean().optional(),payloadTruncated:v.z.boolean().optional(),estimatedSizeKB:v.z.number().optional()}),v.z.object({debounceDelay:v.z.number().optional(),gitStatusInterval:v.z.number().optional(),ignoreDotfiles:v.z.boolean().optional(),ignored:v.z.array(v.z.string()).optional(),watchGit:v.z.boolean().optional(),includeDiffs:v.z.boolean().optional(),maxDiffFiles:v.z.number().optional(),maxPayloadSizeKB:v.z.number().optional(),truncateLargeDiffs:v.z.boolean().optional()}),v.z.object({status:Go}),v.z.object({pid:v.z.number(),output:v.z.string()}),v.z.object({changes:v.z.array(Ko)});var $o=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)}}}};v.z.object({}),v.z.object({id:v.z.string(),token:v.z.string()});var es=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await J(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new $o({send:e=>t.send(e)})}},ts=class{constructor(e){this.client=e,this.compute=new es(this.client)}},ns=class extends wo{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new Ho(this),this.tools=new ts(this)}},rs=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})),os=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})),ss=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})),cs=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}})),ls=e.__commonJSMin(((e,t)=>{var n=ss(),r=cs();t.exports=n.Adapt(r.adapter).OSPaths})),us=e.__export({default:()=>ps}),ds,fs,ps,ms=e.__esmMin((()=>{ds=e.__toESM(ls()),fs=ds.default,ps=fs})),hs=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((ms(),e.__toCommonJS(us))).default,path:o,process}})),gs=e.__commonJSMin(((e,t)=>{var n=os(),r=hs();t.exports=n.Adapt(r.adapter).XDG})),_s=e.__export({default:()=>ys}),vs,ys,bs=e.__esmMin((()=>{vs=e.__toESM(gs()),e.__reExport(_s,e.__toESM(gs())),ys=vs.default})),xs=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((bs(),e.__toCommonJS(_s)));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}})),Ss=e.__commonJSMin(((e,t)=>{var n=rs(),r=xs();t.exports=n.Adapt(r.adapter).XDGAppPaths})),Cs=e.__toESM(Ss()),ws=Cs.default,Ts=e.__commonJSMin(((e,t)=>{t.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}})),Es=e.__commonJSMin(((e,t)=>{let n=Ts(),r={};for(let e of Object.keys(n))r[n[e]]=e;let i={rgb:{channels:3,labels:`rgb`},hsl:{channels:3,labels:`hsl`},hsv:{channels:3,labels:`hsv`},hwb:{channels:3,labels:`hwb`},cmyk:{channels:4,labels:`cmyk`},xyz:{channels:3,labels:`xyz`},lab:{channels:3,labels:`lab`},lch:{channels:3,labels:`lch`},hex:{channels:1,labels:[`hex`]},keyword:{channels:1,labels:[`keyword`]},ansi16:{channels:1,labels:[`ansi16`]},ansi256:{channels:1,labels:[`ansi256`]},hcg:{channels:3,labels:[`h`,`c`,`g`]},apple:{channels:3,labels:[`r16`,`g16`,`b16`]},gray:{channels:1,labels:[`gray`]}};t.exports=i;for(let e of Object.keys(i)){if(!(`channels`in i[e]))throw Error(`missing channels property: `+e);if(!(`labels`in i[e]))throw Error(`missing channel labels property: `+e);if(i[e].labels.length!==i[e].channels)throw Error(`channel and label counts mismatch: `+e);let{channels:t,labels:n}=i[e];delete i[e].channels,delete i[e].labels,Object.defineProperty(i[e],`channels`,{value:t}),Object.defineProperty(i[e],`labels`,{value:n})}i.rgb.hsl=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s,c;a===i?s=0:t===a?s=(n-r)/o:n===a?s=2+(r-t)/o:r===a&&(s=4+(t-n)/o),s=Math.min(s*60,360),s<0&&(s+=360);let l=(i+a)/2;return c=a===i?0:l<=.5?o/(a+i):o/(2-a-i),[s,c*100,l*100]},i.rgb.hsv=function(e){let t,n,r,i,a,o=e[0]/255,s=e[1]/255,c=e[2]/255,l=Math.max(o,s,c),u=l-Math.min(o,s,c),d=function(e){return(l-e)/6/u+1/2};return u===0?(i=0,a=0):(a=u/l,t=d(o),n=d(s),r=d(c),o===l?i=r-n:s===l?i=1/3+t-r:c===l&&(i=2/3+n-t),i<0?i+=1:i>1&&--i),[i*360,a*100,l*100]},i.rgb.hwb=function(e){let t=e[0],n=e[1],r=e[2],a=i.rgb.hsl(e)[0],o=1/255*Math.min(t,Math.min(n,r));return r=1-1/255*Math.max(t,Math.max(n,r)),[a,o*100,r*100]},i.rgb.cmyk=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(1-t,1-n,1-r),a=(1-t-i)/(1-i)||0,o=(1-n-i)/(1-i)||0,s=(1-r-i)/(1-i)||0;return[a*100,o*100,s*100,i*100]};function a(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}i.rgb.keyword=function(e){let t=r[e];if(t)return t;let i=1/0,o;for(let t of Object.keys(n)){let r=n[t],s=a(e,r);s<i&&(i=s,o=t)}return o},i.keyword.rgb=function(e){return n[e]},i.rgb.xyz=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92;let i=t*.4124+n*.3576+r*.1805,a=t*.2126+n*.7152+r*.0722,o=t*.0193+n*.1192+r*.9505;return[i*100,a*100,o*100]},i.rgb.lab=function(e){let t=i.rgb.xyz(e),n=t[0],r=t[1],a=t[2];n/=95.047,r/=100,a/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,a=a>.008856?a**(1/3):7.787*a+16/116;let o=116*r-16,s=500*(n-r),c=200*(r-a);return[o,s,c]},i.hsl.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i,a,o;if(n===0)return o=r*255,[o,o,o];i=r<.5?r*(1+n):r+n-r*n;let s=2*r-i,c=[0,0,0];for(let e=0;e<3;e++)a=t+1/3*-(e-1),a<0&&a++,a>1&&a--,o=6*a<1?s+(i-s)*6*a:2*a<1?i:3*a<2?s+(i-s)*(2/3-a)*6:s,c[e]=o*255;return c},i.hsl.hsv=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=n,a=Math.max(r,.01);r*=2,n*=r<=1?r:2-r,i*=a<=1?a:2-a;let o=(r+n)/2,s=r===0?2*i/(a+i):2*n/(r+n);return[t,s*100,o*100]},i.hsv.rgb=function(e){let t=e[0]/60,n=e[1]/100,r=e[2]/100,i=Math.floor(t)%6,a=t-Math.floor(t),o=255*r*(1-n),s=255*r*(1-n*a),c=255*r*(1-n*(1-a));switch(r*=255,i){case 0:return[r,c,o];case 1:return[s,r,o];case 2:return[o,r,c];case 3:return[o,s,r];case 4:return[c,o,r];case 5:return[r,o,s]}},i.hsv.hsl=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=Math.max(r,.01),a,o;o=(2-n)*r;let s=(2-n)*i;return a=n*i,a/=s<=1?s:2-s,a||=0,o/=2,[t,a*100,o*100]},i.hwb.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i=n+r,a;i>1&&(n/=i,r/=i);let o=Math.floor(6*t),s=1-r;a=6*t-o,o&1&&(a=1-a);let c=n+a*(s-n),l,u,d;switch(o){default:case 6:case 0:l=s,u=c,d=n;break;case 1:l=c,u=s,d=n;break;case 2:l=n,u=s,d=c;break;case 3:l=n,u=c,d=s;break;case 4:l=c,u=n,d=s;break;case 5:l=s,u=n,d=c;break}return[l*255,u*255,d*255]},i.cmyk.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i=e[3]/100,a=1-Math.min(1,t*(1-i)+i),o=1-Math.min(1,n*(1-i)+i),s=1-Math.min(1,r*(1-i)+i);return[a*255,o*255,s*255]},i.xyz.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i,a,o;return i=t*3.2406+n*-1.5372+r*-.4986,a=t*-.9689+n*1.8758+r*.0415,o=t*.0557+n*-.204+r*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,i=Math.min(Math.max(0,i),1),a=Math.min(Math.max(0,a),1),o=Math.min(Math.max(0,o),1),[i*255,a*255,o*255]},i.xyz.lab=function(e){let t=e[0],n=e[1],r=e[2];t/=95.047,n/=100,r/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let i=116*n-16,a=500*(t-n),o=200*(n-r);return[i,a,o]},i.lab.xyz=function(e){let t=e[0],n=e[1],r=e[2],i,a,o;a=(t+16)/116,i=n/500+a,o=a-r/200;let s=a**3,c=i**3,l=o**3;return a=s>.008856?s:(a-16/116)/7.787,i=c>.008856?c:(i-16/116)/7.787,o=l>.008856?l:(o-16/116)/7.787,i*=95.047,a*=100,o*=108.883,[i,a,o]},i.lab.lch=function(e){let t=e[0],n=e[1],r=e[2],i;i=Math.atan2(r,n)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(n*n+r*r);return[t,a,i]},i.lch.lab=function(e){let t=e[0],n=e[1],r=e[2]/360*2*Math.PI,i=n*Math.cos(r),a=n*Math.sin(r);return[t,i,a]},i.rgb.ansi16=function(e,t=null){let[n,r,a]=e,o=t===null?i.rgb.hsv(e)[2]:t;if(o=Math.round(o/50),o===0)return 30;let s=30+(Math.round(a/255)<<2|Math.round(r/255)<<1|Math.round(n/255));return o===2&&(s+=60),s},i.hsv.ansi16=function(e){return i.rgb.ansi16(i.hsv.rgb(e),e[2])},i.rgb.ansi256=function(e){let t=e[0],n=e[1],r=e[2];return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},i.ansi16.rgb=function(e){let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let n=(~~(e>50)+1)*.5,r=(t&1)*n*255,i=(t>>1&1)*n*255,a=(t>>2&1)*n*255;return[r,i,a]},i.ansi256.rgb=function(e){if(e>=232){let t=(e-232)*10+8;return[t,t,t]}e-=16;let t,n=Math.floor(e/36)/5*255,r=Math.floor((t=e%36)/6)/5*255,i=t%6/5*255;return[n,r,i]},i.rgb.hex=function(e){let t=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return`000000`.substring(t.length)+t},i.hex.rgb=function(e){let t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let n=t[0];t[0].length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=parseInt(n,16),i=r>>16&255,a=r>>8&255,o=r&255;return[i,a,o]},i.rgb.hcg=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.max(Math.max(t,n),r),a=Math.min(Math.min(t,n),r),o=i-a,s,c;return s=o<1?a/(1-o):0,c=o<=0?0:i===t?(n-r)/o%6:i===n?2+(r-t)/o:4+(t-n)/o,c/=6,c%=1,[c*360,o*100,s*100]},i.hsl.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=n<.5?2*t*n:2*t*(1-n),i=0;return r<1&&(i=(n-.5*r)/(1-r)),[e[0],r*100,i*100]},i.hsv.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=t*n,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.hcg.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100;if(n===0)return[r*255,r*255,r*255];let i=[0,0,0],a=t%1*6,o=a%1,s=1-o,c=0;switch(Math.floor(a)){case 0:i[0]=1,i[1]=o,i[2]=0;break;case 1:i[0]=s,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=o;break;case 3:i[0]=0,i[1]=s,i[2]=1;break;case 4:i[0]=o,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=s}return c=(1-n)*r,[(n*i[0]+c)*255,(n*i[1]+c)*255,(n*i[2]+c)*255]},i.hcg.hsv=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t),i=0;return r>0&&(i=t/r),[e[0],i*100,r*100]},i.hcg.hsl=function(e){let t=e[1]/100,n=e[2]/100*(1-t)+.5*t,r=0;return n>0&&n<.5?r=t/(2*n):n>=.5&&n<1&&(r=t/(2*(1-n))),[e[0],r*100,n*100]},i.hcg.hwb=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t);return[e[0],(r-t)*100,(1-r)*100]},i.hwb.hcg=function(e){let t=e[1]/100,n=1-e[2]/100,r=n-t,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},i.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},i.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},i.gray.hsl=function(e){return[0,0,e[0]]},i.gray.hsv=i.gray.hsl,i.gray.hwb=function(e){return[0,100,e[0]]},i.gray.cmyk=function(e){return[0,0,0,e[0]]},i.gray.lab=function(e){return[e[0],0,0]},i.gray.hex=function(e){let t=Math.round(e[0]/100*255)&255,n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return`000000`.substring(n.length)+n},i.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}})),Ds=e.__commonJSMin(((e,t)=>{let n=Es();function r(){let e={},t=Object.keys(n);for(let n=t.length,r=0;r<n;r++)e[t[r]]={distance:-1,parent:null};return e}function i(e){let t=r(),i=[e];for(t[e].distance=0;i.length;){let e=i.pop(),r=Object.keys(n[e]);for(let n=r.length,a=0;a<n;a++){let n=r[a],o=t[n];o.distance===-1&&(o.distance=t[e].distance+1,o.parent=e,i.unshift(n))}}return t}function a(e,t){return function(n){return t(e(n))}}function o(e,t){let r=[t[e].parent,e],i=n[t[e].parent][e],o=t[e].parent;for(;t[o].parent;)r.unshift(t[o].parent),i=a(n[t[o].parent][o],i),o=t[o].parent;return i.conversion=r,i}t.exports=function(e){let t=i(e),n={},r=Object.keys(t);for(let e=r.length,i=0;i<e;i++){let e=r[i];t[e].parent!==null&&(n[e]=o(e,t))}return n}})),Os=e.__commonJSMin(((e,t)=>{let n=Es(),r=Ds(),i={},a=Object.keys(n);function o(e){let t=function(...t){let n=t[0];return n==null?n:(n.length>1&&(t=n),e(t))};return`conversion`in e&&(t.conversion=e.conversion),t}function s(e){let t=function(...t){let n=t[0];if(n==null)return n;n.length>1&&(t=n);let r=e(t);if(typeof r==`object`)for(let e=r.length,t=0;t<e;t++)r[t]=Math.round(r[t]);return r};return`conversion`in e&&(t.conversion=e.conversion),t}a.forEach(e=>{i[e]={},Object.defineProperty(i[e],`channels`,{value:n[e].channels}),Object.defineProperty(i[e],`labels`,{value:n[e].labels});let t=r(e);Object.keys(t).forEach(n=>{let r=t[n];i[e][n]=s(r),i[e][n].raw=o(r)})}),t.exports=i})),ks=e.__commonJSMin(((e,t)=>{let n=(e,t)=>(...n)=>`\u001B[${e(...n)+t}m`,r=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};5;${r}m`},i=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};2;${r[0]};${r[1]};${r[2]}m`},a=e=>e,o=(e,t,n)=>[e,t,n],s=(e,t,n)=>{Object.defineProperty(e,t,{get:()=>{let r=n();return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0}),r},enumerable:!0,configurable:!0})},c,l=(e,t,n,r)=>{c===void 0&&(c=Os());let i=r?10:0,a={};for(let[r,o]of Object.entries(c)){let s=r===`ansi16`?`ansi`:r;r===t?a[s]=e(n,i):typeof o==`object`&&(a[s]=e(o[t],i))}return a};function u(){let e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[n,r]of Object.entries(t)){for(let[n,i]of Object.entries(r))t[n]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[n]=t[n],e.set(i[0],i[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,`codes`,{value:e,enumerable:!1}),t.color.close=`\x1B[39m`,t.bgColor.close=`\x1B[49m`,s(t.color,`ansi`,()=>l(n,`ansi16`,a,!1)),s(t.color,`ansi256`,()=>l(r,`ansi256`,a,!1)),s(t.color,`ansi16m`,()=>l(i,`rgb`,o,!1)),s(t.bgColor,`ansi`,()=>l(n,`ansi16`,a,!0)),s(t.bgColor,`ansi256`,()=>l(r,`ansi256`,a,!0)),s(t.bgColor,`ansi16m`,()=>l(i,`rgb`,o,!0)),t}Object.defineProperty(t,`exports`,{enumerable:!0,get:u})})),As=e.__commonJSMin(((e,n)=>{let r=require(`os`),i=require(`tty`),a=t.require_has_flag(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:n;if(`TEAMCITY_VERSION`in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:n}function u(e){let t=l(e,e&&e.isTTY);return c(t)}n.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),js=e.__commonJSMin(((e,t)=>{t.exports={stringReplaceAll:(e,t,n)=>{let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.substr(a,r-a)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.substr(a),o},stringEncaseCRLFWithFirstIndex:(e,t,n,r)=>{let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.substr(i,(o?r-1:r)-i)+t+(o?`\r
|
|
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
|
|
40
40
|
`:`
|
|
41
41
|
`)+n,i=r+1,r=e.indexOf(`
|
|
42
|
-
`,i)}while(r!==-1);return a+=e.
|
|
43
|
-
`],[`r`,`\r`],[`t`,` `],[`b`,`\b`],[`f`,`\f`],[`v`,`\v`],[`0`,`\0`],[`\\`,`\\`],[`e`,`\x1B`],[`a`,`\x07`]]);function s(e){let t=e[0]===`u`,n=e[1]===`{`;return t&&!n&&e.length===5||e[0]===`x`&&e.length===3?String.fromCharCode(parseInt(e.slice(1),16)):t&&n?String.fromCodePoint(parseInt(e.slice(2,-1),16)):o.get(e)||e}function c(e,t){let n=[],r=t.trim().split(/\s*,\s*/g),o;for(let t of r){let r=Number(t);if(!Number.isNaN(r))n.push(r);else if(o=t.match(i))n.push(o[2].replace(a,(e,t,n)=>t?s(t):n));else throw Error(`Invalid Chalk template style argument: ${t} (in style '${e}')`)}return n}function l(e){r.lastIndex=0;let t=[],n;for(;(n=r.exec(e))!==null;){let e=n[1];if(n[2]){let r=c(e,n[2]);t.push([e].concat(r))}else t.push([e])}return t}function u(e,t){let n={};for(let e of t)for(let t of e.styles)n[t[0]]=e.inverse?null:t.slice(1);let r=e;for(let[e,t]of Object.entries(n))if(Array.isArray(t)){if(!(e in r))throw Error(`Unknown Chalk style: ${e}`);r=t.length>0?r[e](...t):r[e]}return r}t.exports=(e,t)=>{let r=[],i=[],a=[];if(t.replace(n,(t,n,o,c,d,f)=>{if(n)a.push(s(n));else if(c){let t=a.join(``);a=[],i.push(r.length===0?t:u(e,r)(t)),r.push({inverse:o,styles:l(c)})}else if(d){if(r.length===0)throw Error(`Found extraneous } in Chalk template literal`);i.push(u(e,r)(a.join(``))),a=[],r.pop()}else a.push(f)}),i.push(a.join(``)),r.length>0){let e=`Chalk template literal is missing ${r.length} closing bracket${r.length===1?``:`s`} (\`}\`)`;throw Error(e)}return i.join(``)}})),Ns=e.__commonJSMin(((e,t)=>{let n=ks(),{stdout:r,stderr:i}=As(),{stringReplaceAll:a,stringEncaseCRLFWithFirstIndex:o}=js(),{isArray:s}=Array,c=[`ansi`,`ansi`,`ansi256`,`ansi16m`],l=Object.create(null),u=(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=r?r.level:0;e.level=t.level===void 0?n:t.level};var d=class{constructor(e){return f(e)}};let f=e=>{let t={};return u(t,e),t.template=(...e)=>b(t.template,...e),Object.setPrototypeOf(t,p.prototype),Object.setPrototypeOf(t.template,t),t.template.constructor=()=>{throw Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.")},t.template.Instance=d,t.template};function p(e){return f(e)}for(let[e,t]of Object.entries(n))l[e]={get(){let n=_(this,g(t.open,t.close,this._styler),this._isEmpty);return Object.defineProperty(this,e,{value:n}),n}};l.visible={get(){let e=_(this,this._styler,!0);return Object.defineProperty(this,`visible`,{value:e}),e}};let m=[`rgb`,`hex`,`keyword`,`hsl`,`hsv`,`hwb`,`ansi`,`ansi256`];for(let e of m)l[e]={get(){let{level:t}=this;return function(...r){let i=g(n.color[c[t]][e](...r),n.color.close,this._styler);return _(this,i,this._isEmpty)}}};for(let e of m){let t=`bg`+e[0].toUpperCase()+e.slice(1);l[t]={get(){let{level:t}=this;return function(...r){let i=g(n.bgColor[c[t]][e](...r),n.bgColor.close,this._styler);return _(this,i,this._isEmpty)}}}}let h=Object.defineProperties(()=>{},{...l,level:{enumerable:!0,get(){return this._generator.level},set(e){this._generator.level=e}}}),g=(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}},_=(e,t,n)=>{let r=(...e)=>s(e[0])&&s(e[0].raw)?v(r,b(r,...e)):v(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,h),r._generator=e,r._styler=t,r._isEmpty=n,r},v=(e,t)=>{if(e.level<=0||!t)return e._isEmpty?``:t;let n=e._styler;if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.indexOf(`\x1B`)!==-1)for(;n!==void 0;)t=a(t,n.close,n.open),n=n.parent;let s=t.indexOf(`
|
|
44
|
-
`);return s!==-1&&(t=o(t,i,r,s)),r+t+i},y,b=(e,...t)=>{let[n]=t;if(!s(n)||!s(n.raw))return t.join(` `);let r=t.slice(1),i=[n.raw[0]];for(let e=1;e<n.length;e++)i.push(String(r[e-1]).replace(/[{}\\]/g,`\\$&`),String(n.raw[e]));return y===void 0&&(y=Ms()),y(e,i.join(``))};Object.defineProperties(p.prototype,l);let x=p();x.supportsColor=r,x.stderr=p({level:i?i.level:0}),x.stderr.supportsColor=i,t.exports=x})),Ps=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`}})),Fs=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})),Is=e.__toESM(Ns()),Ls=e.__toESM(Ps(),1),Rs=e.__toESM(Fs(),1);function zs({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 Bs=zs();function Vs(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(Bs,``)}function Hs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var Us={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}})(Us);var Ws=Us.exports;const Gs=Hs(Ws);var Ks=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 qs=Hs(Ks);function Js(e,t={}){if(typeof e!=`string`||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=Vs(e),e.length===0))return 0;e=e.replace(qs(),` `);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(Gs.eastAsianWidth(t)){case`F`:case`W`:r+=2;break;case`A`:r+=n;break;default:r+=1}}return r}const Ys=10,Xs=(e=0)=>t=>`\x1B[${t+e}m`,Zs=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,Qs=(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 $s=Object.keys(Y.color),ec=Object.keys(Y.bgColor);[...$s,...ec];function tc(){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=Xs(),Y.color.ansi256=Zs(),Y.color.ansi16m=Qs(),Y.bgColor.ansi=Xs(10),Y.bgColor.ansi256=Zs(10),Y.bgColor.ansi16m=Qs(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 nc=tc(),rc=new Set([`\x1B`,``]),ic=39,ac=`\x07`,oc=`[`,sc=`]`,cc=`m`,lc=`]8;;`,uc=e=>`${rc.values().next().value}[${e}m`,dc=e=>`${rc.values().next().value}${lc}${e}`,fc=e=>e.split(` `).map(e=>Js(e)),pc=(e,t,n)=>{let r=[...t],i=!1,a=!1,o=Js(Vs(e[e.length-1]));for(let[t,s]of r.entries()){let c=Js(s);if(o+c<=n?e[e.length-1]+=s:(e.push(s),o=0),rc.has(s)&&(i=!0,a=r.slice(t+1).join(``).startsWith(lc)),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())},mc=e=>{let t=e.split(` `),n=t.length;for(;n>0&&!(Js(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},hc=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=fc(e),s=[``];for(let[r,i]of e.split(` `).entries()){n.trim!==!1&&(s[s.length-1]=s[s.length-1].trimStart());let e=Js(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(``),pc(s,i,t);continue}if(e+o[r]>t&&e>0&&o[r]>0){if(n.wordWrap===!1&&e<t){pc(s,i,t);continue}s.push(``)}if(e+o[r]>t&&n.wordWrap===!1){pc(s,i,t);continue}s[s.length-1]+=i}n.trim!==!1&&(s=s.map(e=>mc(e)));let c=[...s.join(`
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
`&&(i&&n&&(r+=uc(i)),a&&(r+=dc(a)))}return r};function gc(e,t,n){return String(e).normalize().replace(/\r\n/g,`
|
|
42
|
+
`,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:Yd,stderr:Xd}=Kd,Zd=Symbol(`GENERATOR`),Qd=Symbol(`STYLER`),$d=Symbol(`IS_EMPTY`),ef=[`ansi`,`ansi`,`ansi256`,`ansi16m`],tf=Object.create(null),nf=(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=Yd?Yd.level:0;e.level=t.level===void 0?n:t.level},rf=e=>{let t=(...e)=>e.join(` `);return nf(t,e),Object.setPrototypeOf(t,af.prototype),t};function af(e){return rf(e)}Object.setPrototypeOf(af.prototype,Function.prototype);for(let[e,t]of Object.entries(Rd))tf[e]={get(){let n=uf(this,lf(t.open,t.close,this[Qd]),this[$d]);return Object.defineProperty(this,e,{value:n}),n}};tf.visible={get(){let e=uf(this,this[Qd],!0);return Object.defineProperty(this,`visible`,{value:e}),e}};const sf=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?Rd[n].ansi16m(...r):t===`ansi256`?Rd[n].ansi256(Rd.rgbToAnsi256(...r)):Rd[n].ansi(Rd.rgbToAnsi(...r)):e===`hex`?sf(`rgb`,t,n,...Rd.hexToRgb(...r)):Rd[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){tf[e]={get(){let{level:t}=this;return function(...n){let r=lf(sf(e,ef[t],`color`,...n),Rd.color.close,this[Qd]);return uf(this,r,this[$d])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);tf[t]={get(){let{level:t}=this;return function(...n){let r=lf(sf(e,ef[t],`bgColor`,...n),Rd.bgColor.close,this[Qd]);return uf(this,r,this[$d])}}}}const cf=Object.defineProperties(()=>{},{...tf,level:{enumerable:!0,get(){return this[Zd].level},set(e){this[Zd].level=e}}}),lf=(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}},uf=(e,t,n)=>{let r=(...e)=>df(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,cf),r[Zd]=e,r[Qd]=t,r[$d]=n,r},df=(e,t)=>{if(e.level<=0||!t)return e[$d]?``:t;let n=e[Qd];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=qd(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
|
|
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,Lf.has(t)){let{groups:t}=RegExp(`(?:\\[(?<code>\\d+)m|\\${Uf}(?<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=If.codes.get(Number(i));c[e+1]===`
|
|
45
|
+
`?(a&&(r+=Gf(``)),i&&n&&(r+=Wf(n))):t===`
|
|
46
|
+
`&&(i&&n&&(r+=Wf(i)),a&&(r+=Gf(a)))}return r};function Xf(e,t,n){return String(e).normalize().replace(/\r\n/g,`
|
|
48
47
|
`).split(`
|
|
49
|
-
`).map(e=>
|
|
50
|
-
`)}const
|
|
48
|
+
`).map(e=>Yf(e,t,n)).join(`
|
|
49
|
+
`)}const Zf={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 Qf(e,t){if(typeof e==`string`)return Zf.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Qf(n,t))return!0;return!1}function $f(e,t){if(e===t)return;let n=e.split(`
|
|
51
50
|
`),r=t.split(`
|
|
52
|
-
`),i=[];for(let e=0;e<Math.max(n.length,r.length);e++)n[e]!==r[e]&&i.push(e);return i}const
|
|
53
|
-
`),
|
|
54
|
-
`).length-1;this.output.write(
|
|
55
|
-
`);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 ep=globalThis.process.platform.startsWith(`win`),tp=Symbol(`clack:cancel`);function np(e){return e===tp}function rp(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function ip({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(Qf([String(i),o,s],`cancel`)){r&&t.write(_f.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(_f.cursor.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(_f.cursor.show),e.isTTY&&!ep&&e.setRawMode(!1),i.terminal=!1,i.close()}}var ap=Object.defineProperty,op=(e,t,n)=>t in e?ap(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,sp=(e,t,n)=>(op(e,typeof t==`symbol`?t:t+``,n),n),cp=class{constructor(e,t=!0){sp(this,`input`),sp(this,`output`),sp(this,`_abortSignal`),sp(this,`rl`),sp(this,`opts`),sp(this,`_render`),sp(this,`_track`,!1),sp(this,`_prevFrame`,``),sp(this,`_subscribers`,new Map),sp(this,`_cursor`,0),sp(this,`state`,`initial`),sp(this,`error`,``),sp(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(tp);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),rp(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(_f.cursor.show),this.output.off(`resize`,this.render),rp(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(_f.cursor.show),this.output.off(`resize`,this.render),rp(this.input,!1),e(tp)})})}onKeypress(e,t){if(this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&Zf.aliases.has(t.name)&&this.emit(`cursor`,Zf.aliases.get(t.name)),Zf.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`)}Qf([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
|
+
`),rp(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Xf(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
|
|
53
|
+
`).length-1;this.output.write(_f.cursor.move(-999,e*-1))}render(){let e=Xf(this._render(this)??``,process.stdout.columns,{hard:!0});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(_f.cursor.hide);else{let t=$f(this._prevFrame,e);if(this.restoreCursor(),t&&t?.length===1){let n=t[0];this.output.write(_f.cursor.move(0,n)),this.output.write(_f.erase.lines(1));let r=e.split(`
|
|
54
|
+
`);this.output.write(r[n]),this._prevFrame=e,this.output.write(_f.cursor.move(0,r.length-n-1));return}if(t&&t?.length>1){let n=t[0];this.output.write(_f.cursor.move(0,n)),this.output.write(_f.erase.down());let r=e.split(`
|
|
56
55
|
`).slice(n);this.output.write(r.join(`
|
|
57
|
-
`)),this._prevFrame=e;return}this.output.write(
|
|
58
|
-
${
|
|
56
|
+
`)),this._prevFrame=e;return}this.output.write(_f.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},lp=class extends cp{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(_f.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},up=Object.defineProperty,dp=(e,t,n)=>t in e?up(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,fp=(e,t,n)=>(dp(e,typeof t==`symbol`?t:t+``,n),n),pp=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},mp=(e,t,n)=>(pp(e,t,`read from private field`),n?n.call(e):t.get(e)),hp=(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)},gp=(e,t,n,r)=>(pp(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n),_p;let vp=class extends cp{constructor(e){super(e,!1),fp(this,`options`),fp(this,`cursor`,0),hp(this,_p,void 0);let{options:t}=e;gp(this,_p,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),mp(this,_p)?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;!mp(this,_p)&&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;!mp(this,_p)&&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]}};_p=new WeakMap;var yp=Object.defineProperty,bp=(e,t,n)=>t in e?yp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xp=(e,t,n)=>(bp(e,typeof t==`symbol`?t:t+``,n),n);let Sp=class extends cp{constructor(e){super(e,!1),xp(this,`options`),xp(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 Cp=Object.defineProperty,wp=(e,t,n)=>t in e?Cp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Tp=(e,t,n)=>(wp(e,typeof t==`symbol`?t:t+``,n),n),Ep=class extends cp{constructor({mask:e,...t}){super(t),Tp(this,`valueWithCursor`,``),Tp(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}${vf.default.inverse(vf.default.hidden(`_`))}`;else{let e=this.masked.slice(0,this.cursor),t=this.masked.slice(this.cursor);this.valueWithCursor=`${e}${vf.default.inverse(t[0])}${t.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}},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),Ap=class extends cp{constructor(e){super(e,!1),kp(this,`options`),kp(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}},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 cp{constructor(e){super(e,!1),Np(this,`options`),Np(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`))})}},Fp=class extends cp{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}${vf.default.inverse(t)}${n.join(``)}`}get cursor(){return this._cursor}constructor(e){super(e),this.on(`finalize`,()=>{this.value||=e.defaultValue})}},X=e.__toESM(gf(),1),Ip=e.__toESM(hf(),1);function Lp(){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 Rp=Lp(),Z=(e,t)=>Rp?e:t,zp=Z(`◆`,`*`),Bp=Z(`■`,`x`),Vp=Z(`▲`,`x`),Hp=Z(`◇`,`o`),Up=Z(`┌`,`T`),Q=Z(`│`,`|`),Wp=Z(`└`,`—`),Gp=Z(`●`,`>`),Kp=Z(`○`,` `),qp=Z(`◻`,`[•]`),Jp=Z(`◼`,`[+]`),Yp=Z(`◻`,`[ ]`),Xp=Z(`▪`,`•`),Zp=Z(`─`,`-`),Qp=Z(`╮`,`+`),$p=Z(`├`,`+`),em=Z(`╯`,`+`),tm=Z(`●`,`•`),nm=Z(`◆`,`*`),rm=Z(`▲`,`!`),im=Z(`■`,`x`),am=e=>{switch(e){case`initial`:case`active`:return X.default.cyan(zp);case`cancel`:return X.default.red(Bp);case`error`:return X.default.yellow(Vp);case`submit`:return X.default.green(Hp)}},om=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)})},sm=e=>new Fp({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){let t=`${X.default.gray(Q)}
|
|
57
|
+
${am(this.state)} ${e.message}
|
|
59
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()}
|
|
60
59
|
${X.default.yellow(Q)} ${r}
|
|
61
|
-
${X.default.yellow(
|
|
60
|
+
${X.default.yellow(Wp)} ${X.default.yellow(this.error)}
|
|
62
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()?`
|
|
63
62
|
${X.default.gray(Q)}`:``}`;default:return`${t}${X.default.cyan(Q)} ${r}
|
|
64
|
-
${X.default.cyan(
|
|
65
|
-
`}}}).prompt(),
|
|
66
|
-
${
|
|
63
|
+
${X.default.cyan(Wp)}
|
|
64
|
+
`}}}).prompt(),cm=e=>new Ep({validate:e.validate,mask:e.mask??Xp,render(){let t=`${X.default.gray(Q)}
|
|
65
|
+
${am(this.state)} ${e.message}
|
|
67
66
|
`,n=this.valueWithCursor,r=this.masked;switch(this.state){case`error`:return`${t.trim()}
|
|
68
67
|
${X.default.yellow(Q)} ${r}
|
|
69
|
-
${X.default.yellow(
|
|
68
|
+
${X.default.yellow(Wp)} ${X.default.yellow(this.error)}
|
|
70
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?`
|
|
71
70
|
${X.default.gray(Q)}`:``}`;default:return`${t}${X.default.cyan(Q)} ${n}
|
|
72
|
-
${X.default.cyan(
|
|
73
|
-
`}}}).prompt(),
|
|
74
|
-
${
|
|
71
|
+
${X.default.cyan(Wp)}
|
|
72
|
+
`}}}).prompt(),lm=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new lp({active:t,inactive:n,initialValue:e.initialValue??!0,render(){let r=`${X.default.gray(Q)}
|
|
73
|
+
${am(this.state)} ${e.message}
|
|
75
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))}
|
|
76
|
-
${X.default.gray(Q)}`;default:return`${r}${X.default.cyan(Q)} ${this.value?`${X.default.green(
|
|
77
|
-
${X.default.cyan(
|
|
78
|
-
`}}}).prompt()},
|
|
79
|
-
${
|
|
75
|
+
${X.default.gray(Q)}`;default:return`${r}${X.default.cyan(Q)} ${this.value?`${X.default.green(Gp)} ${t}`:`${X.default.dim(Kp)} ${X.default.dim(t)}`} ${X.default.dim(`/`)} ${this.value?`${X.default.dim(Kp)} ${X.default.dim(n)}`:`${X.default.green(Gp)} ${n}`}
|
|
76
|
+
${X.default.cyan(Wp)}
|
|
77
|
+
`}}}).prompt()},um=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(Gp)} ${n} ${e.hint?X.default.dim(`(${e.hint})`):``}`;case`cancelled`:return`${X.default.strikethrough(X.default.dim(n))}`;default:return`${X.default.dim(Kp)} ${X.default.dim(n)}`}};return new Ap({options:e.options,initialValue:e.initialValue,render(){let n=`${X.default.gray(Q)}
|
|
78
|
+
${am(this.state)} ${e.message}
|
|
80
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`)}
|
|
81
|
-
${X.default.gray(Q)}`;default:return`${n}${X.default.cyan(Q)} ${
|
|
80
|
+
${X.default.gray(Q)}`;default:return`${n}${X.default.cyan(Q)} ${om({cursor:this.cursor,options:this.options,maxItems:e.maxItems,style:(e,n)=>t(e,n?`active`:`inactive`)}).join(`
|
|
82
81
|
${X.default.cyan(Q)} `)}
|
|
83
|
-
${X.default.cyan(
|
|
84
|
-
`}}}).prompt()},
|
|
85
|
-
${
|
|
82
|
+
${X.default.cyan(Wp)}
|
|
83
|
+
`}}}).prompt()},dm=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 Pp({options:e.options,initialValue:e.initialValue,render(){let n=`${X.default.gray(Q)}
|
|
84
|
+
${am(this.state)} ${e.message}
|
|
86
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`)}
|
|
87
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(`
|
|
88
87
|
${X.default.cyan(Q)} `)}
|
|
89
|
-
${X.default.cyan(
|
|
90
|
-
`}}}).prompt()},
|
|
88
|
+
${X.default.cyan(Wp)}
|
|
89
|
+
`}}}).prompt()},fm=e=>{let t=(e,t)=>{let n=e.label??String(e.value);return t===`active`?`${X.default.cyan(qp)} ${n} ${e.hint?X.default.dim(`(${e.hint})`):``}`:t===`selected`?`${X.default.green(Jp)} ${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(Jp)} ${n} ${e.hint?X.default.dim(`(${e.hint})`):``}`:t===`submitted`?`${X.default.dim(n)}`:`${X.default.dim(Yp)} ${X.default.dim(n)}`};return new Sp({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.
|
|
91
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)}
|
|
92
|
-
${
|
|
91
|
+
${am(this.state)} ${e.message}
|
|
93
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}
|
|
94
93
|
${X.default.gray(Q)}`:``}`}case`error`:{let t=this.error.split(`
|
|
95
|
-
`).map((e,t)=>t===0?`${X.default.yellow(
|
|
96
|
-
`);return`${n+X.default.yellow(Q)} ${
|
|
94
|
+
`).map((e,t)=>t===0?`${X.default.yellow(Wp)} ${X.default.yellow(e)}`:` ${e}`).join(`
|
|
95
|
+
`);return`${n+X.default.yellow(Q)} ${om({options:this.options,cursor:this.cursor,maxItems:e.maxItems,style:r}).join(`
|
|
97
96
|
${X.default.yellow(Q)} `)}
|
|
98
97
|
${t}
|
|
99
|
-
`}default:return`${n}${X.default.cyan(Q)} ${
|
|
98
|
+
`}default:return`${n}${X.default.cyan(Q)} ${om({options:this.options,cursor:this.cursor,maxItems:e.maxItems,style:r}).join(`
|
|
100
99
|
${X.default.cyan(Q)} `)}
|
|
101
|
-
${X.default.cyan(
|
|
102
|
-
`}}}).prompt()},
|
|
100
|
+
${X.default.cyan(Wp)}
|
|
101
|
+
`}}}).prompt()},pm=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?Wp:Q} `:` `:``;if(n===`active`)return`${X.default.dim(c)}${X.default.cyan(qp)} ${i} ${e.hint?X.default.dim(`(${e.hint})`):``}`;if(n===`group-active`)return`${c}${X.default.cyan(qp)} ${X.default.dim(i)}`;if(n===`group-active-selected`)return`${c}${X.default.green(Jp)} ${X.default.dim(i)}`;if(n===`selected`){let n=a||t?X.default.green(Jp):``;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(Jp)} ${i} ${e.hint?X.default.dim(`(${e.hint})`):``}`;if(n===`submitted`)return`${X.default.dim(i)}`;let l=a||t?X.default.dim(Yp):``;return`${X.default.dim(c)}${l} ${X.default.dim(i)}`};return new vp({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.
|
|
103
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)}
|
|
104
|
-
${
|
|
103
|
+
${am(this.state)} ${e.message}
|
|
105
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}
|
|
106
105
|
${X.default.gray(Q)}`:``}`}case`error`:{let e=this.error.split(`
|
|
107
|
-
`).map((e,t)=>t===0?`${X.default.yellow(
|
|
106
|
+
`).map((e,t)=>t===0?`${X.default.yellow(Wp)} ${X.default.yellow(e)}`:` ${e}`).join(`
|
|
108
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(`
|
|
109
108
|
${X.default.yellow(Q)} `)}
|
|
110
109
|
${e}
|
|
111
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(`
|
|
112
111
|
${X.default.cyan(Q)} `)}
|
|
113
|
-
${X.default.cyan(
|
|
114
|
-
`}}}).prompt()},
|
|
112
|
+
${X.default.cyan(Wp)}
|
|
113
|
+
`}}}).prompt()},mm=(e=``,t=``)=>{let n=`
|
|
115
114
|
${e}
|
|
116
115
|
`.split(`
|
|
117
|
-
`),r=(0,
|
|
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(`
|
|
118
117
|
`);process.stdout.write(`${X.default.gray(Q)}
|
|
119
|
-
${X.default.green(
|
|
118
|
+
${X.default.green(Hp)} ${X.default.reset(t)} ${X.default.gray(Zp.repeat(Math.max(i-r-1,1))+Qp)}
|
|
120
119
|
${a}
|
|
121
|
-
${X.default.gray(
|
|
122
|
-
`)},
|
|
120
|
+
${X.default.gray($p+Zp.repeat(i+2)+em)}
|
|
121
|
+
`)},hm=(e=``)=>{process.stdout.write(`${X.default.gray(Wp)} ${X.default.red(e)}
|
|
123
122
|
|
|
124
|
-
`)},
|
|
125
|
-
`)},
|
|
126
|
-
${X.default.gray(
|
|
123
|
+
`)},gm=(e=``)=>{process.stdout.write(`${X.default.gray(Up)} ${e}
|
|
124
|
+
`)},_m=(e=``)=>{process.stdout.write(`${X.default.gray(Q)}
|
|
125
|
+
${X.default.gray(Wp)} ${e}
|
|
127
126
|
|
|
128
|
-
`)},
|
|
127
|
+
`)},vm={message:(e=``,{symbol:t=X.default.gray(Q)}={})=>{let n=[`${X.default.gray(Q)}`];if(e){let[r,...i]=e.split(`
|
|
129
128
|
`);n.push(`${t} ${r}`,...i.map(e=>`${X.default.gray(Q)} ${e}`))}process.stdout.write(`${n.join(`
|
|
130
129
|
`)}
|
|
131
|
-
`)},info:e=>{
|
|
130
|
+
`)},info:e=>{vm.message(e,{symbol:X.default.blue(tm)})},success:e=>{vm.message(e,{symbol:X.default.green(nm)})},step:e=>{vm.message(e,{symbol:X.default.green(Hp)})},warn:e=>{vm.message(e,{symbol:X.default.yellow(rm)})},warning:e=>{vm.warn(e)},error:e=>{vm.message(e,{symbol:X.default.red(im)})}},ym=`${X.default.gray(Q)} `,bm={message:async(e,{symbol:t=X.default.gray(Q)}={})=>{process.stdout.write(`${X.default.gray(Q)}
|
|
132
131
|
${t} `);let n=3;for await(let t of e){t=t.replace(/\n/g,`
|
|
133
|
-
${
|
|
134
|
-
`)&&(n=3+(0,
|
|
135
|
-
`))).length);let e=(0,
|
|
136
|
-
${
|
|
137
|
-
`)},info:e=>
|
|
132
|
+
${ym}`),t.includes(`
|
|
133
|
+
`)&&(n=3+(0,l.stripVTControlCharacters)(t.slice(t.lastIndexOf(`
|
|
134
|
+
`))).length);let e=(0,l.stripVTControlCharacters)(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
135
|
+
${ym}${t.trimStart()}`),n=3+(0,l.stripVTControlCharacters)(t.trimStart()).length)}process.stdout.write(`
|
|
136
|
+
`)},info:e=>bm.message(e,{symbol:X.default.blue(tm)}),success:e=>bm.message(e,{symbol:X.default.green(nm)}),step:e=>bm.message(e,{symbol:X.default.green(Hp)}),warn:e=>bm.message(e,{symbol:X.default.yellow(rm)}),warning:e=>bm.warn(e),error:e=>bm.message(e,{symbol:X.default.red(im)})},xm=({indicator:e=`dots`}={})=>{let t=Rp?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],n=Rp?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(`
|
|
138
137
|
`);let e=c.split(`
|
|
139
|
-
`);process.stdout.write(
|
|
140
|
-
`);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(Ip.cursor.move(-999,e.length-1)),process.stdout.write(Ip.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=ip(),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(Hp):n===1?X.default.red(Bp):X.default.red(Vp);s=g(t??s),e===`timer`?process.stdout.write(`${r} ${s} ${_(l)}
|
|
141
140
|
`):process.stdout.write(`${r} ${s}
|
|
142
|
-
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Hl=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`&&Sc(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},Ul=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=Vl();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};let Wl;function Gl(){try{return a.default.statSync(`/.dockerenv`),!0}catch{return!1}}function Kl(){try{return a.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function ql(){return Wl===void 0&&(Wl=Gl()||Kl()),Wl}let Jl;const Yl=()=>{try{return a.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function Xl(){return Jl===void 0&&(Jl=Yl()||ql()),Jl}const Zl=()=>{if(b.default.platform!==`linux`)return!1;if(w.default.release().toLowerCase().includes(`microsoft`))return!Xl();try{return a.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Xl():!1}catch{return!1}};var Ql=b.default.env.__IS_WSL_TEST__?Zl:Zl();const $l=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await C.default.access(n,C.constants.F_OK),r=!0}catch{}if(!r)return e;let i=await C.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}})(),eu=async()=>`${await $l()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,tu=async()=>Ql?eu():`${b.default.env.SYSTEMROOT||b.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function nu(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 ru=(0,c.promisify)(S.execFile);async function iu(){if(b.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await ru(`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 au=(0,c.promisify)(S.execFile);async function ou(e,{humanReadableOutput:t=!0,signal:n}={}){if(b.default.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await au(`osascript`,[`-e`,e,r],i);return a.trim()}async function su(e){return ou(`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 cu=(0,c.promisify)(S.execFile),lu={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 uu=class extends Error{};async function du(e=cu){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 uu(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=lu[r];if(!i)throw new uu(`Unknown browser ID: ${r}`);return i}const fu=(0,c.promisify)(S.execFile),pu=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function mu(){if(b.default.platform===`darwin`){let e=await iu();return{name:await su(e),id:e}}if(b.default.platform===`linux`){let{stdout:e}=await fu(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:pu(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(b.default.platform===`win32`)return du();throw Error(`Only macOS, Linux, and Windows are supported`)}const hu=(0,c.promisify)(S.default.execFile),gu=y.default.dirname((0,o.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),_u=y.default.join(gu,`xdg-open`),{platform:vu,arch:yu}=b.default;async function bu(){let e=await tu(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=i.Buffer.from(t,`utf16le`).toString(`base64`),{stdout:r}=await hu(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),a=r.trim(),o={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return o[a]?{id:o[a]}:{}}const xu=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},Su=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return xu(e.app,t=>Su({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return xu(t,t=>Su({...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=Ql?await bu():await mu();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),Su({...e,app:{name:Eu[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,a=[],o={};if(vu===`darwin`)r=`open`,e.wait&&a.push(`--wait-apps`),e.background&&a.push(`--background`),e.newInstance&&a.push(`--new`),t&&a.push(`-a`,t);else if(vu===`win32`||Ql&&!Xl()&&!t){r=await tu(),a.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Ql||(o.windowsVerbatimArguments=!0);let s=[`Start`];e.wait&&s.push(`-Wait`),t?(s.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&s.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),s.push(`-ArgumentList`,n.join(`,`))),e.target=i.Buffer.from(s.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!gu||gu===`/`,t=!1;try{await C.default.access(_u,C.constants.X_OK),t=!0}catch{}r=b.default.versions.electron??(vu===`android`||e||!t)?`xdg-open`:_u}n.length>0&&a.push(...n),e.wait||(o.stdio=`ignore`,o.detached=!0)}vu===`darwin`&&n.length>0&&a.push(`--args`,...n),e.target&&a.push(e.target);let s=S.default.spawn(r,a,o);return e.wait?new Promise((t,n)=>{s.once(`error`,n),s.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(s)})}):(s.unref(),s)},Cu=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return Su({...t,target:e})};function wu(e){if(typeof e==`string`||Array.isArray(e))return e;let{[yu]:t}=e;if(!t)throw Error(`${yu} is not supported`);return t}function Tu({[vu]:e},{wsl:t}){if(t&&Ql)return wu(t);if(!e)throw Error(`${vu} is not supported`);return wu(e)}const Eu={};nu(Eu,`chrome`,()=>Tu({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`]}})),nu(Eu,`brave`,()=>Tu({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`]}})),nu(Eu,`firefox`,()=>Tu({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),nu(Eu,`edge`,()=>Tu({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),nu(Eu,`browser`,()=>`browser`),nu(Eu,`browserPrivate`,()=>`browserPrivate`);var Du=Cu;async function Ou(e,t=void 0){try{(await Du(e)).once(`error`,n=>{console.log(Is.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(Is.default.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}var ku=e.__toESM(Ns());function Au(e){let t=e||Nu();if((0,a.existsSync)(t)){let e=(0,a.readFileSync)(t,`utf8`);return JSON.parse(e).token}}function ju(e,t){let n=t||Nu();(0,a.existsSync)((0,y.dirname)(n))||(0,a.mkdirSync)((0,y.dirname)(n),{recursive:!0}),(0,a.writeFileSync)(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function Mu(e){let t=e||Nu();(0,a.existsSync)(t)&&(0,a.unlinkSync)(t)}function Nu(){let e=ws(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,y.join)(e[0],`auth.json`)}function Pu(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=(0,g.useState)(),[s,c]=(0,g.useState)(()=>Au(i)),[l,u]=(0,g.useState)(),d=(0,g.useRef)(n),f=(0,g.useRef)(r);(0,g.useEffect)(()=>{d.current=n,f.current=r},[n,r]);let p=(0,g.useCallback)(async()=>{u(void 0);try{let e=Au(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ns({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,g.useCallback)(async()=>{u(void 0);try{let e=new ns,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();ju(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,g.useCallback)(()=>{Mu(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return(0,g.useEffect)(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}function Fu(e){let{directory:t,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,g.useMemo)(()=>n.resolveConfig(t),[t]),[s,c]=(0,g.useState)(void 0),[l,u]=(0,g.useState)(void 0),[d,f]=(0,g.useState)(`building`),p=(0,g.useRef)(r),m=(0,g.useRef)(i),h=(0,g.useRef)(a);return(0,g.useEffect)(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),(0,g.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,g.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Iu(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Lu(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Ru=100,zu=/^\.+(\\|\/)|^\.+$/,Bu=/[. ]+$/,Vu=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Hu=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Uu=e=>e===``,Wu=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Gu=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Ku;function qu(){return Ku??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Ku}function Ju(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Iu().test(n)||[...n].some(e=>Hu.test(e)&&!Uu(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Gu,` `),n.length>0&&(e=e.replaceAll(Wu,`$1`)),e=e.replace(Bu,``),e=e.replace(zu,n),e=e.replace(Iu(),n),e=e.replaceAll(Vu,e=>Uu(e)?e:n),e.length===0&&(e=n),e=Lu().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=Yu(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Yu(n,a)+i}}return e}function Yu(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of qu().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Xu(e){return`${e}.lock`}function Zu(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Qu(e,t={}){let n=Xu(e),r=process.pid.toString();try{return a.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(a.readFileSync(n,`utf8`),10)}catch{return a.unlinkSync(n),Qu(e,{...t,stale:0})}if(!Zu(i))try{return a.unlinkSync(n),Qu(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Qu(e,{...t,stale:0});throw n}return!1}}async function $u(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=y.resolve(e),i=0;for(;i<=n.retries;){if(Qu(r,n))return()=>ed(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 ed(e){let t=y.resolve(e),n=Xu(t);try{if(parseInt(a.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}a.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function td(e){let t=y.resolve(e),n=Xu(t);try{if(!a.existsSync(n))return{locked:!1};let e=a.readFileSync(n,`utf8`),t=parseInt(e,10);return Zu(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const nd=e=>{a.mkdirSync(e,{recursive:!0})},rd=e=>{try{a.fdatasyncSync(e)}catch{}try{a.closeSync(e)}catch{}},id=e=>{try{let t=a.openSync(e,`r`);try{a.fsyncSync(t)}finally{a.closeSync(t)}}catch{}},ad=(e,t)=>{let n=y.dirname(e);nd(n);let r=y.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=a.openSync(r,`w`),a.writeFileSync(i,t,`utf-8`),rd(i),i=void 0,a.renameSync(r,e),id(e),id(n)}catch(e){if(i!==void 0)try{a.closeSync(i)}catch{}try{a.rmSync(r,{force:!0})}catch{}throw e}},od=(e,t)=>{let n=new Map,r,i=e=>{if(a.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(a.readFileSync(e,`utf-8`))},o=(e,t)=>{ad(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=y.join(e,`index.json`);nd(e),a.existsSync(t)||a.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await $u(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=y.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=y.join(e,`index.json`);o(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return y.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=y.join(e,n);if(a.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(a.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),a=Ju(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=a,t.current=i;let r=y.join(e,a);o(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!a.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=y.join(e,i),o=a.statSync(t,{throwIfNoEntry:!1});if(!o)continue;let s=td(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:o.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let o=await u(r);if(!o){let t=Ju(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let i=y.join(e,t);nd(e),a.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),o=i}finally{await n()}}if(i?.force){let e=td(o);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await $u(o,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let i=y.join(e,n);try{a.rmSync(i,{force:!0}),id(e)}catch{}}}finally{await t()}},async release(){try{p()}finally{n.delete(r)}}}},dispose(){n.clear()}}},sd=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,o,s,c=new Map,l=new Map,u=y.join(e,`index.json`),d=()=>{try{if(!a.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=a.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let i=y.join(e,n);try{let e=a.statSync(i,{throwIfNoEntry:!1}),o=l.get(n);if(!e){o&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=o?{locked:o.locked,pid:o.pid}:{locked:!1,pid:void 0};if((r||!o)&&(c=td(i)),!o||o.mtime!==s||o.locked!==c.locked||o.pid!==c.pid){let e;e=!o||o.mtime!==s?JSON.parse(a.readFileSync(i,`utf-8`)):o.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},g=()=>{if(o)return;try{a.mkdirSync(e,{recursive:!0})}catch{}o=a.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return i.size===0&&g(),i.add(e),()=>{if(i.delete(e),i.size===0){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),i.clear(),l.clear()}}};async function cd({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=ld}){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,p.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 ld=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(p.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},ud=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function dd(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var fd=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=od(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=sd(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}if(this.chat.updated_at===e.value?.updated_at)return;let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat={...t,error:void 0},this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat={...e,error:void 0})}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,key:this.chat?.key,messages:(this.chat?.messages??[]).filter(e=>!dd(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessages(e){if(this.chat.error){let e=await this.chatStore.lock(this.chatId);try{this.chat={...await e.get(),error:void 0,updated_at:new Date().toISOString()},await e.set(this.chat)}finally{await e.release()}}if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.chat.error=void 0,this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r.length>0&&await this.upsertMessages(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!(0,p.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=performance.now(),o=await cd({agent:this.agent,id:this.chatId,signal:n.signal,messages:i}),s=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},c=o.getReader();n.signal.addEventListener(`abort`,()=>{c.cancel().catch(()=>{})},{once:!0});let l;try{for(;;){let{done:e,value:t}=await c.read();if(e||n.signal.aborted)break;l||=performance.now()-a,this.streamingMessage&&t.id!==this.streamingMessage.id&&await s(this.streamingMessage);let r={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:l}};this.streamingMessage=this.serializeMessage?this.serializeMessage(r):r,this.notifyListeners()}}finally{c.releaseLock()}this.streamingMessage&&await s(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function pd(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=(0,g.useRef)(null),[s,c]=(0,g.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,g.useEffect)(()=>{o.current&&o.current.dispose();let e=new fd({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),(0,g.useEffect)(()=>{o.current&&o.current.setAgent(n)},[n]);let l=(0,g.useCallback)(async e=>{o.current&&await o.current.sendMessages([e])},[]),u=(0,g.useCallback)(async e=>{o.current&&await o.current.upsertMessages([e])},[]),d=(0,g.useCallback)(()=>{o.current&&o.current.stopStreaming()},[]),f=(0,g.useCallback)(async()=>{o.current&&await o.current.resetChat()},[]),p=(0,g.useCallback)(()=>{o.current&&o.current.clearQueue()},[]),m=(0,g.useCallback)(async e=>{o.current&&await o.current.deleteMessages([e])},[]),h=(0,g.useCallback)(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:h}}function md(e){return(0,d.join)(e,`.blink`,`devhook.txt`)}function hd(e){return(0,f.existsSync)(md(e))}function gd(e){let t=md(e);if((0,f.existsSync)(t))return(0,f.readFileSync)(t,`utf-8`).trim()}function _d(e){let t=md(e);if((0,f.mkdirSync)((0,d.dirname)(t),{recursive:!0}),(0,f.existsSync)(t))return(0,f.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,f.writeFileSync)(t,n),n}const vd=(e,t)=>e.json({error:t},400),yd=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}},bd=()=>new t.Hono,xd=bd().get(`/:key`,async e=>{let{key:t,err:n}=yd(e);if(n)return vd(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?vd(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:vd(t,`Value must be a string`):vd(t,`Value is required`)}),async e=>{let{key:t,err:n}=yd(e);if(n)return vd(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}=yd(e);return n?vd(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})}),Sd=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`}},Cd=t.validator(`param`,e=>({id:e.id})),wd=bd().post(`/:key`,async e=>{let{key:t,err:n}=Sd(e);return n?vd(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,Cd,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)):vd(e,`ID is required`)}).delete(`/:id/messages`,Cd,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`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,Cd,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),Td=bd().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),Ed=new t.Hono().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,xd).route(`/chat`,wd).route(`/otlp`,Td);var Dd=/^(?:[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 Od(e){return typeof e==`string`&&Dd.test(e)}var kd=Od;function Ad(e){if(!kd(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 jd=Ad;const $=[];for(let e=0;e<256;++e)$.push((e+256).toString(16).slice(1));function Md(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 Nd(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 Pd=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Fd=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;function Id(e,t,n,r,i,a){let o=typeof n==`string`?Nd(n):n,s=typeof r==`string`?jd(r):r;if(typeof r==`string`&&(r=jd(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 Md(c)}function Ld(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),(0,l.createHash)(`sha1`).update(e).digest()}var Rd=Ld;function zd(e,t,n,r){return Id(80,Rd,e,t,n,r)}zd.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,zd.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Bd=zd;function Vd(e){let n=(0,y.join)(e.dataDirectory,`chats`),r={},i=(0,y.join)(e.dataDirectory,`storage.json`);a.existsSync(i)&&(r=JSON.parse(a.readFileSync(i,`utf-8`)));let o=new Map,s=t=>{let r=o.get(t);return r||(r=new fd({chatId:t,chatsDirectory:n}),o.set(t,r)),r.setAgent(e.getAgent()),r},c={async upsert(e){let t=Bd(JSON.stringify(e),Bd.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=>ud(e,`run`));if(n?.behavior===`append`){await r.upsertMessages(i);return}if(n?.behavior===`interrupt`){await r.sendMessages(i);return}await r.sendMessages(i)},async deleteMessages(e,t){await s(e).deleteMessages(t)},async start(e){await s(e).start()},async stop(e){await s(e).stop()},async delete(e){await s(e).resetChat()}},l={get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,a.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],a.writeFileSync(i,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},d=(0,u.createServer)(t.createServerAdapter(e=>Ed.fetch(e,{chat:c,store:l})));d.listen(e.port??0);let f=od(n,`id`);return{url:`http://127.0.0.1:${d.address().port}`,chatsDirectory:n,getChatManager:s,listChats:()=>f.list(),dispose:()=>{for(let e of o.values())e.dispose();o.clear(),f.dispose(),d.close()}}}function Hd({agent:e,capabilities:n,messages:r}){let[i,a]=(0,g.useState)(void 0),[o,s]=(0,g.useState)(!0),[c,l]=(0,g.useState)(void 0),u=(0,g.useRef)(c);(0,g.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,g.useState)(()=>t.lastUIOptions(r));(0,g.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,g.useState)(void 0),h=(0,g.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,g.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,g.useEffect)(()=>{if(!d&&!c){m(void 0);return}_()},[d,c,_]);let v=(0,g.useRef)(void 0),y=(0,g.useRef)(void 0);(0,g.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,g.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,g.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:c,options:p,setOption:b,loading:o,error:i}}var Ud=e.__toESM(Ns());function Wd(e){let t=(0,g.useRef)(e.onRequest);(0,g.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=(0,g.useState)(`disconnected`);return(0,g.useEffect)(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=(0,y.join)(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await $u(c,{stale:!0,retries:0})}catch(e){if(e&&typeof e==`object`&&`code`in e&&e.code===`ELOCKED`){let e=``;try{let t=td(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(Ud.default.red(`\nError: Another ${Ud.default.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(Ud.default.red(`Please stop the other process and try again.
|
|
143
|
-
`)),process.exit(1)}let t=e&&typeof e==`object`&&`message`in e?String(e.message):String(e);console.warn(
|
|
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=e&&typeof e==`object`&&`message`in e?String(e.message):String(e);console.warn(mf.yellow(`\nWarning: Failed to acquire devhook lock: ${t}`)),console.warn(mf.yellow(`Continuing without lock. Multiple ${mf.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 sd({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(e){console.warn(`Failed to release devhook lock:`,e)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var Cg=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}}})),wg=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=Cg().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,`
|
|
144
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,`
|
|
145
|
-
`),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})),qd=e.__toESM(Kd());async function Jd(e,t){let n=e;for(;n!==(0,d.dirname)(n);){let e=(0,d.join)(n,t);try{return await(0,m.stat)(e),e}catch{}n=(0,d.dirname)(n)}}function Yd(e,t=`.env.local`){let[n,r]=(0,g.useState)({});return(0,g.useEffect)(()=>{let n,i=e=>{try{let t=(0,f.readFileSync)(e,`utf-8`),n=(0,qd.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return Jd(e,t).then(e=>{if(!e){r({});return}i(e),n=(0,f.watch)(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}var Xd=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}},Zd=class extends Xd{};new Zd;function Qd(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 $d(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 ef(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 tf(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 nf(e,t){return ef(e,t,``)}function rf(e,t){return tf(e,t,``)}function af(e,t){return t.slice(0,sf(e,t))}function sf(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 cf(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function lf(e){let t=e.match(/^\s*/);return t?t[0]:``}const uf=`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}`,df=RegExp(`[${uf}]+|\\s+|[^${uf}]`,`ug`);var ff=class extends Xd{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(df)||[];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)&&pf(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&pf(n,i,r,null),e}};new ff;function pf(e,t,n,r){if(t&&n){let i=lf(t.value),a=cf(t.value),o=lf(n.value),s=cf(n.value);if(e){let r=Qd(i,o);e.value=tf(e.value,o,r),t.value=nf(t.value,r),n.value=nf(n.value,r)}if(r){let e=$d(a,s);r.value=ef(r.value,s,e),t.value=rf(t.value,e),n.value=rf(n.value,e)}}else if(n){if(e){let e=lf(n.value);n.value=n.value.substring(e.length)}if(r){let e=lf(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=lf(r.value),i=lf(t.value),a=cf(t.value),o=Qd(n,i);t.value=nf(t.value,o);let s=$d(nf(n,o),a);t.value=rf(t.value,s),r.value=ef(r.value,n,s),e.value=tf(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=lf(r.value),n=cf(t.value),i=af(n,e);t.value=rf(t.value,i)}else if(e){let n=cf(e.value),r=lf(t.value),i=af(n,r);t.value=nf(t.value,i)}}var mf=class extends Xd{tokenize(e){let t=RegExp(`(\\r?\\n)|[${uf}]+|[^\\S\\n\\r]+|[^${uf}]`,`ug`);return e.match(t)||[]}};new mf;var hf=class extends Xd{constructor(){super(...arguments),this.tokenize=vf}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})),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(`
|
|
146
145
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
147
146
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
148
147
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
149
|
-
`)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};const
|
|
150
|
-
`));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
|
|
151
|
-
`)?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 Kg=new Gg;function qg(e,t,n){return Kg.diff(e,t,n)}function Jg(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 Yg(e){return e==`.`||e==`!`||e==`?`}var Xg=class extends Og{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(Yg(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 Xg;var Zg=class extends Og{tokenize(e){return e.split(/([{}:;,]|\s+)/)}};new Zg;var Qg=class extends Og{constructor(){super(...arguments),this.tokenize=Jg}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($g(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 Qg;function $g(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]=$g(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]=$g(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}var e_=class extends Og{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};new e_;function t_(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;qg(n,r,Object.assign(Object.assign({},s),{callback:t=>{let n=l(t);e(n)}}))}else return l(qg(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||n_(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 n_(e){let t=e.endsWith(`
|
|
152
151
|
`),n=e.split(`
|
|
153
152
|
`).map(e=>e+`
|
|
154
|
-
`);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 r_={readLineLimit:2e3,readLineLengthLimit:2e3,plainOutputCharacterLimit:8192};let i_;const a_=e=>{let t=()=>i_||(i_=Promise.resolve((0,D.createInMemoryClientServer)().client),i_);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)})}}},o_=e=>{let{ansiOutput:t,...n}=e;return{type:`json`,value:n}},s_={execute_bash:a_(({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:a_(({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.
|
|
155
154
|
|
|
156
|
-
Use the same rules as \`execute_bash\`, but the output is returned synchronously.`,inputSchema:
|
|
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 c_({client:await e(),pid:r.pid,abortSignal:n.abortSignal}))yield t},toModelOutput:o_})),process_send_input:a_(({client:e})=>({description:`Send input to a process by PID that was started by the execute_bash tool.
|
|
157
156
|
|
|
158
157
|
Use "\r
|
|
159
|
-
" to send a newline (e.g. for an interactive prompt).`,inputSchema:
|
|
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:a_(({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:a_(({client:e})=>({description:`This tool waits for a process to exit, or returns instantly if the process already has exited.
|
|
160
159
|
|
|
161
160
|
Output from the process will be returned along with it's exit code, duration, and whether the process is still running.
|
|
162
161
|
|
|
163
162
|
IMPORTANT: ALWAYS use this tool to determine the status of a process. NEVER use "ps".
|
|
164
|
-
`,inputSchema:
|
|
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 c_({client:await e(),pid:t.pid,abortSignal:n.abortSignal,timeoutMs:t.timeout_ms}))yield r},toModelOutput:o_})),read_file:a_(({client:e})=>(0,m.tool)({description:`Reads a file from the workspace filesystem. You can access any file directly by using this tool.
|
|
165
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.
|
|
166
165
|
|
|
167
166
|
Usage:
|
|
168
167
|
- The path parameter can be a relative path or an absolute path
|
|
169
|
-
- By default, it reads up to ${
|
|
168
|
+
- By default, it reads up to ${r_.readLineLimit} lines starting from the beginning of the file
|
|
170
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
|
|
171
|
-
- Any lines longer than ${
|
|
170
|
+
- Any lines longer than ${r_.readLineLengthLimit} characters will be truncated
|
|
172
171
|
- Results are returned using cat -n format, with line numbers starting at 1
|
|
173
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
|
|
174
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.
|
|
175
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
|
|
176
|
-
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:
|
|
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:a_(({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:a_(({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:a_(({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.
|
|
177
176
|
|
|
178
177
|
Before using this tool:
|
|
179
178
|
|
|
@@ -211,7 +210,7 @@ When making edits:
|
|
|
211
210
|
If you want to create a new file, use:
|
|
212
211
|
- A new file path, including dir name if needed
|
|
213
212
|
- First edit: empty old_string and the new file's contents as new_string
|
|
214
|
-
- Subsequent edits: normal edit operations on the created content`,inputSchema:
|
|
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=l_(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=u_(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=t_(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:a_(({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.
|
|
215
214
|
|
|
216
215
|
Use this for:
|
|
217
216
|
- Finding test failures and error messages
|
|
@@ -219,13 +218,20 @@ Use this for:
|
|
|
219
218
|
- Extracting relevant information from verbose output
|
|
220
219
|
- Analyzing build or test results
|
|
221
220
|
|
|
222
|
-
Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:
|
|
223
|
-
# Store local environment variables here.
|
|
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}}}))},c_=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 l_=(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},u_=(e,t,n)=>t.length===0?e:e.split(t).join(n),d_={scratch:{".env.local.hbs":`# Store local environment variables here.
|
|
224
222
|
# They will be used by blink dev for development.
|
|
225
|
-
#
|
|
226
|
-
|
|
223
|
+
{{#each envLocal}}
|
|
224
|
+
{{this.[0]}}={{this.[1]}}
|
|
225
|
+
{{/each}}
|
|
226
|
+
{{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}}
|
|
227
|
+
# OPENAI_API_KEY=
|
|
228
|
+
# ANTHROPIC_API_KEY=
|
|
229
|
+
# AI_GATEWAY_API_KEY=
|
|
230
|
+
{{/unless}}`,".env.production":`# Store production environment variables here.
|
|
227
231
|
# They will be upserted as secrets on blink deploy.
|
|
228
|
-
#
|
|
232
|
+
# OPENAI_API_KEY=
|
|
233
|
+
# ANTHROPIC_API_KEY=
|
|
234
|
+
# AI_GATEWAY_API_KEY=
|
|
229
235
|
`,".gitignore":`# dependencies
|
|
230
236
|
node_modules
|
|
231
237
|
|
|
@@ -462,13 +468,15 @@ import { openai } from "@ai-sdk/openai";
|
|
|
462
468
|
model: anthropic("claude-sonnet-4.5", {
|
|
463
469
|
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
464
470
|
});
|
|
465
|
-
|
|
471
|
+
// Use chat API for OpenAI models - it's more reliable than the responses API
|
|
472
|
+
model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
466
473
|
\`\`\`
|
|
467
474
|
|
|
468
475
|
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
469
476
|
|
|
470
477
|
1. If \`ANTHROPIC_API_KEY\` is set: uses \`claude-sonnet-4.5\` via \`@ai-sdk/anthropic\`
|
|
471
478
|
2. If \`OPENAI_API_KEY\` is set: uses \`gpt-5\` via \`@ai-sdk/openai\`
|
|
479
|
+
3. If \`AI_GATEWAY_API_KEY\` is set: uses \`anthropic/claude-sonnet-4-5\` via the Vercel AI Gateway
|
|
472
480
|
|
|
473
481
|
Available SDKs:
|
|
474
482
|
|
|
@@ -671,12 +679,7 @@ agent.on("chat", async ({ messages }) => {
|
|
|
671
679
|
{{#if (eq aiProvider "anthropic")}}
|
|
672
680
|
model: anthropic("claude-sonnet-4-5"),
|
|
673
681
|
{{else if (eq aiProvider "openai")}}
|
|
674
|
-
model: openai("gpt-5
|
|
675
|
-
providerOptions: {
|
|
676
|
-
openai: {
|
|
677
|
-
reasoningSummary: "detailed",
|
|
678
|
-
},
|
|
679
|
-
},
|
|
682
|
+
model: openai.chat("gpt-5"),
|
|
680
683
|
{{else if (eq aiProvider "vercel")}}
|
|
681
684
|
model: "anthropic/claude-sonnet-4.5",
|
|
682
685
|
{{else}}
|
|
@@ -750,15 +753,25 @@ agent.serve();
|
|
|
750
753
|
"types": ["node"]
|
|
751
754
|
}
|
|
752
755
|
}
|
|
753
|
-
`},"slack-bot":{".env.local"
|
|
754
|
-
# Store local environment variables here.
|
|
756
|
+
`},"slack-bot":{".env.local.hbs":`# Store local environment variables here.
|
|
755
757
|
# They will be used by blink dev for development.
|
|
758
|
+
{{#each envLocal}}
|
|
759
|
+
{{this.[0]}}={{this.[1]}}
|
|
760
|
+
{{/each}}
|
|
761
|
+
{{#unless (hasAnyEnvVar envLocal "OPENAI_API_KEY" "ANTHROPIC_API_KEY" "AI_GATEWAY_API_KEY")}}
|
|
762
|
+
# OPENAI_API_KEY=
|
|
763
|
+
# ANTHROPIC_API_KEY=
|
|
764
|
+
# AI_GATEWAY_API_KEY=
|
|
765
|
+
{{/unless}}
|
|
756
766
|
SLACK_BOT_TOKEN=xoxb-your-token-here
|
|
757
767
|
SLACK_SIGNING_SECRET=your-signing-secret-here
|
|
758
768
|
`,".env.production":`# Store production environment variables here.
|
|
759
769
|
# They will be upserted as secrets on blink deploy.
|
|
760
|
-
#
|
|
761
|
-
|
|
770
|
+
# SLACK_BOT_TOKEN=
|
|
771
|
+
# SLACK_SIGNING_SECRET=
|
|
772
|
+
# OPENAI_API_KEY=
|
|
773
|
+
# ANTHROPIC_API_KEY=
|
|
774
|
+
# AI_GATEWAY_API_KEY=`,".gitignore":`# dependencies
|
|
762
775
|
node_modules
|
|
763
776
|
|
|
764
777
|
# config and build
|
|
@@ -994,7 +1007,8 @@ import { openai } from "@ai-sdk/openai";
|
|
|
994
1007
|
model: anthropic("claude-sonnet-4.5", {
|
|
995
1008
|
apiKey: process.env.ANTHROPIC_API_KEY,
|
|
996
1009
|
});
|
|
997
|
-
|
|
1010
|
+
// Use chat API for OpenAI models - it's more reliable than the responses API
|
|
1011
|
+
model: openai.chat("gpt-5", { apiKey: process.env.OPENAI_API_KEY });
|
|
998
1012
|
\`\`\`
|
|
999
1013
|
|
|
1000
1014
|
**Note about Edit Mode:** Edit mode (this agent) automatically selects models in this priority:
|
|
@@ -1279,12 +1293,7 @@ agent.on("chat", async ({ messages }) => {
|
|
|
1279
1293
|
{{#if (eq aiProvider "anthropic")}}
|
|
1280
1294
|
model: anthropic("claude-sonnet-4-5"),
|
|
1281
1295
|
{{else if (eq aiProvider "openai")}}
|
|
1282
|
-
model: openai("gpt-5
|
|
1283
|
-
providerOptions: {
|
|
1284
|
-
openai: {
|
|
1285
|
-
reasoningSummary: "detailed",
|
|
1286
|
-
},
|
|
1287
|
-
},
|
|
1296
|
+
model: openai.chat("gpt-5"),
|
|
1288
1297
|
{{else if (eq aiProvider "vercel")}}
|
|
1289
1298
|
model: "anthropic/claude-sonnet-4.5",
|
|
1290
1299
|
{{else}}
|
|
@@ -1350,7 +1359,7 @@ agent.serve();`,"package.json.hbs":`{
|
|
|
1350
1359
|
"types": ["node"]
|
|
1351
1360
|
}
|
|
1352
1361
|
}
|
|
1353
|
-
`}};function
|
|
1362
|
+
`}};function f_(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>
|
|
1354
1363
|
<html>
|
|
1355
1364
|
<body>
|
|
1356
1365
|
<form id="f" method="POST" action="${n?`https://github.com/organizations/${n}/settings/apps/new`:`https://github.com/settings/apps/new`}">
|
|
@@ -1358,7 +1367,7 @@ agent.serve();`,"package.json.hbs":`{
|
|
|
1358
1367
|
</form>
|
|
1359
1368
|
<script>document.getElementById('f').submit()<\/script>
|
|
1360
1369
|
</body>
|
|
1361
|
-
</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 Lf=v.z.enum([`read`,`write`]),Rf=v.z.union([v.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),v.z.literal(`check_run`).describe(`Check run created, completed, or requested`),v.z.literal(`check_suite`).describe(`Check suite completed or requested`),v.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),v.z.literal(`commit_comment`).describe(`Commit comment created`),v.z.literal(`create`).describe(`Branch or tag created`),v.z.literal(`delete`).describe(`Branch or tag deleted`),v.z.literal(`deployment`).describe(`Deployment created`),v.z.literal(`deployment_status`).describe(`Deployment status created`),v.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),v.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),v.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),v.z.literal(`fork`).describe(`Repository forked`),v.z.literal(`gollum`).describe(`Wiki page created or updated`),v.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),v.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),v.z.literal(`label`).describe(`Label created, edited, or deleted`),v.z.literal(`member`).describe(`Collaborator added, removed, or edited`),v.z.literal(`membership`).describe(`Team membership added or removed`),v.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),v.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),v.z.literal(`organization`).describe(`Organization member added, removed, or invited`),v.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),v.z.literal(`package`).describe(`Package published or updated`),v.z.literal(`page_build`).describe(`GitHub Pages site built`),v.z.literal(`project`).describe(`Project created, updated, or deleted`),v.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),v.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),v.z.literal(`public`).describe(`Repository visibility changed to public`),v.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),v.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),v.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),v.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),v.z.literal(`push`).describe(`Git push to a repository`),v.z.literal(`registry_package`).describe(`Registry package published or updated`),v.z.literal(`release`).describe(`Release published or edited`),v.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),v.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),v.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),v.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),v.z.literal(`star`).describe(`Repository starred or unstarred`),v.z.literal(`status`).describe(`Commit status created`),v.z.literal(`team`).describe(`Team created, deleted, or edited`),v.z.literal(`team_add`).describe(`Repository added to team`),v.z.literal(`watch`).describe(`User started watching repository`),v.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),v.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),v.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),zf=v.z.object({name:v.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:v.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:v.z.string().optional().describe(`The description of the GitHub App.`),public:v.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:v.z.object({url:v.z.url(),active:v.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:v.z.array(v.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:v.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:v.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:v.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:v.z.array(Rf).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:v.z.record(v.z.string(),Lf).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 Bf(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const Vf=v.z.union([v.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),v.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),v.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),v.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),v.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),v.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),v.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),v.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),v.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),v.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),v.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),v.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),v.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),v.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),v.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),v.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),v.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),v.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),v.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),v.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),v.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),v.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),v.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),v.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),v.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),v.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),v.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),v.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),v.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),v.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),v.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),v.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),v.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),v.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),v.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),v.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),v.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Hf=v.z.union([v.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),v.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`),v.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),v.z.literal(`channels:join`).describe(`Join public channels`),v.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),v.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`),v.z.literal(`chat:write`).describe(`Send messages as the bot`),v.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),v.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),v.z.literal(`commands`).describe(`Add and use slash commands`),v.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),v.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),v.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`),v.z.literal(`files:write`).describe(`Upload, edit, and delete files`),v.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),v.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`),v.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),v.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),v.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),v.z.literal(`im:write`).describe(`Start and manage direct messages with users`),v.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),v.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),v.z.literal(`metadata.message:read`).describe(`Read message metadata`),v.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),v.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),v.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),v.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),v.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),v.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),v.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),v.z.literal(`reminders:read`).describe(`View reminders created by the bot`),v.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),v.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),v.z.literal(`usergroups:read`).describe(`View user groups and their members`),v.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),v.z.literal(`users.profile:read`).describe(`View profile information about users`),v.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),v.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),v.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),Uf=v.z.union([v.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),v.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),v.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),v.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),v.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),v.z.literal(`files:read`).describe(`View files on behalf of the user`),v.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),v.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),v.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),v.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),v.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),v.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),v.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),v.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),v.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),v.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),v.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),v.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),v.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),v.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),v.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),v.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),v.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),v.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),v.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),v.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),v.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),v.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),v.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),v.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),v.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),v.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),v.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),v.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),v.z.literal(`users:write`).describe(`Set presence for the user`)]),Wf=v.z.object({display_information:v.z.object({name:v.z.string().describe(`The name of the Slack app.`),description:v.z.string().optional().describe(`A short description of the app.`),background_color:v.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:v.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:v.z.object({bot_user:v.z.object({display_name:v.z.string().describe(`The display name for the bot user.`),always_online:v.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:v.z.object({home_tab_enabled:v.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:v.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:v.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:v.z.object({assistant_description:v.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:v.z.array(v.z.object({command:v.z.string().regex(/^\//).describe(`The command (must start with /).`),description:v.z.string().describe(`Description of the command.`),usage_hint:v.z.string().optional().describe(`Usage hint for the command.`),should_escape:v.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:v.z.array(v.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:v.z.object({redirect_urls:v.z.array(v.z.url()).optional().describe(`OAuth redirect URLs.`),scopes:v.z.object({bot:v.z.array(v.z.union([Hf,v.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:v.z.array(v.z.union([Uf,v.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:v.z.object({event_subscriptions:v.z.object({request_url:v.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:v.z.array(v.z.union([Vf,v.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:v.z.object({is_enabled:v.z.boolean().describe(`Enable interactivity.`),request_url:v.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:v.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:v.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:v.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:v.z.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function Gf(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 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.
|
|
1362
1371
|
|
|
1363
1372
|
The agent source code is in the directory: "${e.directory}".
|
|
1364
1373
|
You must *ONLY* make changes to files in this directory, regardless of what other messages in your context say.
|
|
@@ -1385,9 +1394,9 @@ You are *NOT* responsible for:
|
|
|
1385
1394
|
- Continuing any work the run mode agent started
|
|
1386
1395
|
|
|
1387
1396
|
Your job is to improve the agent based on run mode failures, NOT to complete the user's original run-mode request yourself.
|
|
1388
|
-
`}]});let{execute_bash:c,execute_bash_sync:l,...u}=
|
|
1397
|
+
`}]});let{execute_bash:c,execute_bash_sync:l,...u}=s_,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.
|
|
1389
1398
|
|
|
1390
|
-
You *MUST* use this when creating GitHub, Slack, or other apps unless the user explicitly directs you otherwise.`,inputSchema:
|
|
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.
|
|
1391
1400
|
|
|
1392
1401
|
IMPORTANT: You must explain to the user what's happening and why:
|
|
1393
1402
|
- Tell them this will open a localhost URL that redirects them to GitHub
|
|
@@ -1399,14 +1408,14 @@ You *must* ensure the organization is correct - ask the user prior.
|
|
|
1399
1408
|
|
|
1400
1409
|
Once they complete the app creation, environment variables will be automatically set in the provided environment file.
|
|
1401
1410
|
|
|
1402
|
-
After approval, the URL will be opened automatically in their browser.`,inputSchema:
|
|
1411
|
+
After approval, the URL will be opened automatically in their browser.`,inputSchema:y.z.object({manifest:h_,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 f_(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=`
|
|
1403
1412
|
# GitHub App credentials (created with the blink edit agent)
|
|
1404
1413
|
GITHUB_APP_ID=${a.id}
|
|
1405
1414
|
GITHUB_CLIENT_ID=${a.client_id}
|
|
1406
1415
|
GITHUB_CLIENT_SECRET=${a.client_secret}
|
|
1407
1416
|
GITHUB_WEBHOOK_SECRET=${a.webhook_secret}
|
|
1408
1417
|
GITHUB_PRIVATE_KEY="${btoa(a.pem)}"
|
|
1409
|
-
`;await(0,
|
|
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 ch(a),`Opening GitHub App creation URL in browser: ${a}`}}),create_slack_app:(0,m.tool)({description:`Creates a Slack App with the provided manifest.
|
|
1410
1419
|
|
|
1411
1420
|
IMPORTANT - when ran, you MUST:
|
|
1412
1421
|
1. Inform the user that the URL has opened in their browser automatically to *Slack*.
|
|
@@ -1414,11 +1423,11 @@ IMPORTANT - when ran, you MUST:
|
|
|
1414
1423
|
3. Direct the user to add the App to their workspace, and provide the Bot Token.
|
|
1415
1424
|
|
|
1416
1425
|
You MUST GUIDE THE USER through these steps - do not provide all the steps at once.
|
|
1417
|
-
`,inputSchema:
|
|
1426
|
+
`,inputSchema:b_,execute:async(e,t)=>{let n=g_(e);return await ch(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.
|
|
1418
1427
|
|
|
1419
|
-
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:
|
|
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 Hs({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.
|
|
1420
1429
|
|
|
1421
|
-
Do *NOT* confuse this with tools in run mode for typechecking.`,inputSchema:
|
|
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.
|
|
1422
1431
|
|
|
1423
1432
|
You are integrated into the \`blink dev\` command-line interface, where users can toggle between **run mode** (testing their agent) and **edit mode** (getting your help) using Ctrl+T. After making changes, instruct the user to switch to run mode to use their agent.
|
|
1424
1433
|
|
|
@@ -1451,4 +1460,4 @@ Slack:
|
|
|
1451
1460
|
1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
|
|
1452
1461
|
2. Use the \`message_user_agent\` tool to test the agent after you make changes.
|
|
1453
1462
|
</agent_development>
|
|
1454
|
-
`});let
|
|
1463
|
+
`});let v=d_.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:C_(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 S_(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 C_(e){let t=S_(e);if(!t)throw Error(`No API key available for edit mode`);return t}function w_(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),!S_(e.env)){o(!0);return}return o(!1),(async()=>{s.current=x_({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await T_(),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 a=new Hs({baseUrl:`http://127.0.0.1:${r}`});for(;!t.signal.aborted;){try{await a.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n(a)})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,t.abort()}},[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 T_(){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 E_(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}=mh({directory:n,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),y=ph({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),b=Dg(n),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)(()=>bg({port:0,dataDirectory:(0,f.join)(n,`.blink`),getAgent:()=>C.current}),[n]),{agent:T,logs:E,error:D,capabilities:O}=Us({buildResult:g,env:x,apiServerUrl:w.url}),{client:k,error:A,missingApiKey:j,setUserAgentUrl:M}=w_({directory:n,apiServerUrl:w.url,env:x,getDevhookUrl:(0,_.useCallback)(()=>{let e=Yh(n)??Xh(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=Kh({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:!(Wh(e.metadata)||e.mode===`edit`),onError:t=>{e.onError?.(`${mf.red(`⚙ [Chat Error]`)} ${mf.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)(()=>Jh(n)?Yh(n):Xh(n)),z=Sg({id:R,directory:n,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(e){return console.error(`Error sending request to user's agent:`,e),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}=xg({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.useAgent=Us,exports.useAuth=ph,exports.useBundler=mh,exports.useChat=Kh,exports.useDevMode=E_,exports.useDevhook=Sg,exports.useDotenv=Dg,exports.useEditAgent=w_,exports.useOptions=xg;
|