blink 1.1.35 → 1.1.36

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.
Files changed (156) hide show
  1. package/dist/cli/{dist-Ceoe3h7v.js → auth-B9qq4cSL.js} +108 -65
  2. package/dist/cli/chat-DY4IWEHl.js +1 -0
  3. package/dist/cli/{chat-manager-cUXPlLU4.js → chat-manager-CIKM5Z0y.js} +1 -1
  4. package/dist/cli/{compute-server-BFNeHOmk.js → compute-server-qi2ObZrP.js} +1 -1
  5. package/dist/cli/config-jZRQMoaY.js +1 -0
  6. package/dist/cli/connect-CrE2QpMS.js +1 -0
  7. package/dist/cli/connect-CxdtUbca.js +1 -0
  8. package/dist/cli/{create-github-app-CaCP607a.js → create-github-app-BeSDE8GT.js} +1 -1
  9. package/dist/cli/{dev-DOvBAIjm.js → dev-DRc-HUQD.js} +69 -69
  10. package/dist/cli/{esm-BiWxO8S7.js → esm-C6nUlmX4.js} +1 -1
  11. package/dist/cli/{getMachineId-bsd-BfwVPdTh.js → getMachineId-bsd-B09GfpQE.js} +1 -1
  12. package/dist/cli/{getMachineId-bsd-BmhpEQU_.js → getMachineId-bsd-B5inCcKX.js} +1 -1
  13. package/dist/cli/{getMachineId-bsd-C1eeoY31.js → getMachineId-bsd-BVOanLuZ.js} +1 -1
  14. package/dist/cli/{getMachineId-bsd-CO9ne--Y.js → getMachineId-bsd-BXrGuboa.js} +1 -1
  15. package/dist/cli/getMachineId-bsd-CBL_TGNf.js +1 -0
  16. package/dist/cli/getMachineId-bsd-CbC9XZ_w.js +1 -0
  17. package/dist/cli/{getMachineId-bsd-D4uBPoNF.js → getMachineId-bsd-CrOdTUu4.js} +1 -1
  18. package/dist/cli/getMachineId-bsd-Cxy148LG.js +1 -0
  19. package/dist/cli/{getMachineId-darwin-C0EZ3sY3.js → getMachineId-darwin-BU-w-BnC.js} +1 -1
  20. package/dist/cli/{getMachineId-darwin-CSfD7gS4.js → getMachineId-darwin-BWTc5KWy.js} +1 -1
  21. package/dist/cli/{getMachineId-darwin-CgQ9n4TU.js → getMachineId-darwin-BbUfrHce.js} +1 -1
  22. package/dist/cli/{getMachineId-darwin-CuAzoP7O.js → getMachineId-darwin-BlZzCAQ6.js} +1 -1
  23. package/dist/cli/getMachineId-darwin-BmmSRa_d.js +2 -0
  24. package/dist/cli/{getMachineId-darwin-Cpq0Lloc.js → getMachineId-darwin-UHAuN405.js} +1 -1
  25. package/dist/cli/getMachineId-darwin-hJWBup80.js +2 -0
  26. package/dist/cli/getMachineId-darwin-rxU3ohHe.js +2 -0
  27. package/dist/cli/{getMachineId-linux-B1XJTHUh.js → getMachineId-linux-B4EFTMpj.js} +1 -1
  28. package/dist/cli/{getMachineId-linux-CRUR6LbQ.js → getMachineId-linux-CKBueRrt.js} +1 -1
  29. package/dist/cli/{getMachineId-linux-CVQNNGui.js → getMachineId-linux-CNhTYXGA.js} +1 -1
  30. package/dist/cli/{getMachineId-linux-CtdZRCaX.js → getMachineId-linux-D3K2OTZn.js} +1 -1
  31. package/dist/cli/getMachineId-linux-DaUV--ii.js +1 -0
  32. package/dist/cli/getMachineId-linux-DrZ26-WQ.js +1 -0
  33. package/dist/cli/getMachineId-linux-DzK7jzi5.js +1 -0
  34. package/dist/cli/getMachineId-linux-fpVhDYCz.js +1 -0
  35. package/dist/cli/{getMachineId-unsupported-B-xvzil1.js → getMachineId-unsupported-16ooXsXU.js} +1 -1
  36. package/dist/cli/{getMachineId-unsupported-BA3eQjiV.js → getMachineId-unsupported-72ceFIVM.js} +1 -1
  37. package/dist/cli/{getMachineId-unsupported-BZCOxs7n.js → getMachineId-unsupported-BKotHSFu.js} +1 -1
  38. package/dist/cli/{getMachineId-unsupported-BjGFauqb.js → getMachineId-unsupported-BSdFT2aC.js} +1 -1
  39. package/dist/cli/getMachineId-unsupported-CDM0TBdr.js +1 -0
  40. package/dist/cli/getMachineId-unsupported-Cw89MFW-.js +1 -0
  41. package/dist/cli/getMachineId-unsupported-DBSoWxG_.js +1 -0
  42. package/dist/cli/getMachineId-unsupported-cHJvhp02.js +1 -0
  43. package/dist/cli/{getMachineId-win-AW-Mv9PG.js → getMachineId-win-BAPC_wWc.js} +1 -1
  44. package/dist/cli/{getMachineId-win-B_2C1cwE.js → getMachineId-win-Bn_WM7bG.js} +1 -1
  45. package/dist/cli/{getMachineId-win-CUeKGXdr.js → getMachineId-win-Cc69o1Nq.js} +1 -1
  46. package/dist/cli/{getMachineId-win-BbYxddZ9.js → getMachineId-win-DR3Dm4-5.js} +1 -1
  47. package/dist/cli/{getMachineId-win-BkozcdSh.js → getMachineId-win-DdInvJHL.js} +1 -1
  48. package/dist/cli/getMachineId-win-Dig4HMmA.js +1 -0
  49. package/dist/cli/getMachineId-win-DwHWO0Id.js +1 -0
  50. package/dist/cli/getMachineId-win-gVqg_Qhn.js +1 -0
  51. package/dist/cli/index.js +9 -9
  52. package/dist/cli/{init-LtTUYXzn.js → init-CO5TBme9.js} +1 -1
  53. package/dist/cli/{init-templates-jGRvqLQ6.js → init-templates-Br3bKUNT.js} +3 -3
  54. package/dist/cli/login-C60LmqjM.js +1 -0
  55. package/dist/cli/logout-2bj6PyZi.js +1 -0
  56. package/dist/cli/pull-BGcjDkHJ.js +18 -0
  57. package/dist/cli/run-SQMvtzUV.js +1 -0
  58. package/dist/cli/setup-github-app-DOhdofIm.js +9 -0
  59. package/dist/cli/{token-v4NJW7VU.js → token-MaTAy4hv.js} +1 -1
  60. package/dist/cli/{token-util-BgEcL2NM.js → token-util-Bn01WxFK.js} +1 -1
  61. package/dist/cli/token-util-DbgI6oFx.js +1 -0
  62. package/dist/cli/undici-mM2IfLwA.js +1 -0
  63. package/dist/cli/{util-k3x8m_i5.js → util-DcqmsBrE.js} +1 -1
  64. package/dist/node/agent/index.node.cjs +1 -1
  65. package/dist/node/agent/index.node.d.ts +1 -1
  66. package/dist/node/agent/index.node.js +1 -1
  67. package/dist/node/build/index.cjs +1 -1
  68. package/dist/node/build/index.d.ts +1 -1
  69. package/dist/node/build/index.js +1 -1
  70. package/dist/node/context-Ch5QyxHM.js +1 -0
  71. package/dist/node/context-Cp_cUqvc.cjs +1 -0
  72. package/dist/node/esm-CSXsVdYr.js +1 -0
  73. package/dist/node/esm-DAl5TNhv.cjs +1 -0
  74. package/dist/node/{getMachineId-bsd-O0bNSuuh.cjs → getMachineId-bsd-C0y5EQEK.cjs} +1 -1
  75. package/dist/node/getMachineId-bsd-j5NqIOc8.js +1 -0
  76. package/dist/node/getMachineId-darwin-EKLAsCHs.js +2 -0
  77. package/dist/node/{getMachineId-darwin-DivkCgLG.cjs → getMachineId-darwin-QptN2GTZ.cjs} +1 -1
  78. package/dist/node/{getMachineId-linux-C8A0ak4z.cjs → getMachineId-linux-B7sBt1Ji.cjs} +1 -1
  79. package/dist/node/getMachineId-linux-BkKZQ4pT.js +1 -0
  80. package/dist/node/getMachineId-unsupported-C_PGk8nf.js +1 -0
  81. package/dist/node/{getMachineId-unsupported-DSRCXJha.cjs → getMachineId-unsupported-DwYXVQg7.cjs} +1 -1
  82. package/dist/node/getMachineId-win-BJspkM2m.js +1 -0
  83. package/dist/node/{getMachineId-win-B_okYUv6.cjs → getMachineId-win-C2mMnKyH.cjs} +1 -1
  84. package/dist/node/index.node-CU27y0G9.js +50 -0
  85. package/dist/node/index.node-DfJSk6zl.cjs +50 -0
  86. package/dist/node/internal/index.cjs +1 -0
  87. package/dist/node/internal/index.d.cts +24 -0
  88. package/dist/node/internal/index.d.ts +24 -0
  89. package/dist/node/internal/index.js +1 -0
  90. package/dist/node/react/index.node.cjs +110 -110
  91. package/dist/node/react/index.node.d.ts +2 -2
  92. package/dist/node/react/index.node.js +48 -48
  93. package/dist/node/{token-BQ-EqDMB.cjs → token-BQFROC8n.cjs} +1 -1
  94. package/dist/node/{token-B2MtKe6w.js → token-Qko9jH1t.js} +1 -1
  95. package/dist/node/token-util-BRjrHLnr.cjs +1 -0
  96. package/dist/node/{token-util-CtaB7NzM.js → token-util-uzFo5Esl.js} +1 -1
  97. package/package.json +7 -1
  98. package/dist/cli/auth-DbpOUCTO.js +0 -2
  99. package/dist/cli/chat-BfOX7Zpn.js +0 -1
  100. package/dist/cli/connect-3pBvxI6u.js +0 -1
  101. package/dist/cli/connect-XRcF_tn8.js +0 -1
  102. package/dist/cli/getMachineId-bsd-DVGtITCk.js +0 -1
  103. package/dist/cli/getMachineId-bsd-MA4oFaCa.js +0 -1
  104. package/dist/cli/getMachineId-bsd-dbToLPez.js +0 -1
  105. package/dist/cli/getMachineId-darwin-D6_tdcZj.js +0 -2
  106. package/dist/cli/getMachineId-darwin-DkExT2qu.js +0 -2
  107. package/dist/cli/getMachineId-darwin-xoAzTD7x.js +0 -2
  108. package/dist/cli/getMachineId-linux-DMILcDJR.js +0 -1
  109. package/dist/cli/getMachineId-linux-Deja7F2k.js +0 -1
  110. package/dist/cli/getMachineId-linux-DqOGXYgv.js +0 -1
  111. package/dist/cli/getMachineId-linux-FRx9q8NV.js +0 -1
  112. package/dist/cli/getMachineId-unsupported-CLWxRb7f.js +0 -1
  113. package/dist/cli/getMachineId-unsupported-CSVFDvWp.js +0 -1
  114. package/dist/cli/getMachineId-unsupported-Cp_95R-6.js +0 -1
  115. package/dist/cli/getMachineId-unsupported-Nd0_Z7NT.js +0 -1
  116. package/dist/cli/getMachineId-win-CPhFagnx.js +0 -1
  117. package/dist/cli/getMachineId-win-D3-sMfSu.js +0 -1
  118. package/dist/cli/getMachineId-win-DFVpvzl3.js +0 -1
  119. package/dist/cli/login-POW3H6LQ.js +0 -1
  120. package/dist/cli/run-BHKBjgkK.js +0 -1
  121. package/dist/cli/setup-github-app-DBiuq7cy.js +0 -9
  122. package/dist/cli/token-util-3NkPUSqu.js +0 -1
  123. package/dist/cli/undici-JD4hDNWZ.js +0 -1
  124. package/dist/cli/util-CUfifM0g.js +0 -5
  125. package/dist/node/esm-0UNjvroT.cjs +0 -1
  126. package/dist/node/esm-CbZfjZBn.js +0 -1
  127. package/dist/node/getMachineId-bsd-Ckr9jSoT.js +0 -1
  128. package/dist/node/getMachineId-darwin-36SFRv2R.js +0 -2
  129. package/dist/node/getMachineId-linux-ZoT5w75D.js +0 -1
  130. package/dist/node/getMachineId-unsupported-XVp8oFCM.js +0 -1
  131. package/dist/node/getMachineId-win-CGqZ4f4O.js +0 -1
  132. package/dist/node/index.node-CFR7FTuY.cjs +0 -50
  133. package/dist/node/index.node-CITcyk6b.js +0 -50
  134. package/dist/node/token-util-P8_cV3Yu.cjs +0 -1
  135. /package/dist/cli/{devtools-CwQnB6v7.js → devtools-CS3ukAFj.js} +0 -0
  136. /package/dist/cli/{execAsync-4IyNgpoN.js → execAsync-9jtK4I3l.js} +0 -0
  137. /package/dist/cli/{execAsync-B6xSGvuk.js → execAsync-B4_pEoEJ.js} +0 -0
  138. /package/dist/cli/{execAsync-B8_ZTafx.js → execAsync-BdK7RB6d.js} +0 -0
  139. /package/dist/cli/{execAsync-B8nelpRN.js → execAsync-Bjxs-bO2.js} +0 -0
  140. /package/dist/cli/{execAsync-Cj_jF8MF.js → execAsync-CM_C8SBr.js} +0 -0
  141. /package/dist/cli/{execAsync-Ckbi9Yqe.js → execAsync-CNFaXJjR.js} +0 -0
  142. /package/dist/cli/{execAsync-CvOpnFex.js → execAsync-Dl3hbWiU.js} +0 -0
  143. /package/dist/cli/{execAsync-DDBH3pWg.js → execAsync-qGIZ8XA8.js} +0 -0
  144. /package/dist/cli/{ignore-NA4V6Pjc.js → ignore-ltyKbzfl.js} +0 -0
  145. /package/dist/cli/{token-error-BHDo_48c.js → token-error-CGIVaIg6.js} +0 -0
  146. /package/dist/cli/{undici-B5tM_IT9.js → undici-BiTrd9-R.js} +0 -0
  147. /package/dist/cli/{usingCtx-B1FpoePI.js → usingCtx-CCxav2be.js} +0 -0
  148. /package/dist/cli/{utils-B3iC7vdW.js → utils-BWKsfIcI.js} +0 -0
  149. /package/dist/node/{build-EgdtUZTI.cjs → build-BoU84guF.cjs} +0 -0
  150. /package/dist/node/{build-DYI55eX2.js → build-DBcSkHHH.js} +0 -0
  151. /package/dist/node/{execAsync-BMxJf0Eg.cjs → execAsync-BN6E2M46.cjs} +0 -0
  152. /package/dist/node/{execAsync-CY8juV7n.js → execAsync-CoM0jMb2.js} +0 -0
  153. /package/dist/node/{index-B4OXlWm3.d.ts → index-BcKU69uH.d.ts} +0 -0
  154. /package/dist/node/{index.node-BbqFCkOX.d.ts → index.node-Cl9AwUCW.d.ts} +0 -0
  155. /package/dist/node/{token-util--zh4M6Ze.cjs → token-util-CzDIlVhL.cjs} +0 -0
  156. /package/dist/node/{token-util-RdQsj3MK.js → token-util-DwGWB0np.js} +0 -0
@@ -1,8 +1,8 @@
1
- import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EmptyResponseBodyError as u,EventSourceParserStream as d,Hono as f,InvalidArgumentError as p,InvalidPromptError as m,InvalidResponseDataError as h,JSONParseError as g,LoadAPIKeyError as _,NoSuchModelError as v,StreamResponseFormatHeader as y,TooManyEmbeddingValuesForCallError as b,TypeValidationError as x,UnsupportedFunctionalityError as S,createGatewayProvider as C,createServerAdapter as w,hc as T,isToolApprovalOutput as E,lastUIOptions as D,tools as O,validator as k}from"../index.node-CITcyk6b.js";import"../token-error-488npYdU.js";import"../esm-CbZfjZBn.js";import{resolveConfig as A}from"../build-DYI55eX2.js";import{createRequire as j}from"node:module";import M,{z as N}from"zod/v4";import{ZodFirstPartyTypeKind as ee}from"zod/v3";import{Buffer as te}from"node:buffer";import*as P from"node:fs";import F,{existsSync as I,mkdirSync as ne,readFileSync as L,unlinkSync as re,writeFileSync as R}from"node:fs";import{fileURLToPath as ie}from"node:url";import{Writable as z}from"node:stream";import{promisify as ae,stripVTControlCharacters as oe}from"node:util";import{createHash as se}from"node:crypto";import ce,{createServer as le}from"http";import{dirname as B,join as ue}from"path";import{existsSync as de,mkdirSync as fe,readFileSync as pe,watch as me,writeFileSync as he}from"fs";import{convertToModelMessages as ge,isToolOrDynamicToolUIPart as _e,readUIMessageStream as ve,streamText as ye,tool as be}from"ai";import{readFile as xe,stat as V,writeFile as Se}from"fs/promises";import{spawn as Ce}from"child_process";import{createContext as we,useCallback as H,useEffect as U,useMemo as Te,useRef as W,useState as G}from"react";import K,{z as q}from"zod";import*as Ee from"node:path";import De,{dirname as Oe,join as ke}from"node:path";import J,{stdin as Ae,stdout as je}from"node:process";import Me from"node:os";import Ne from"node:tty";import*as Pe from"node:readline";import Fe from"node:readline";import Ie,{execFile as Le}from"node:child_process";import Re,{constants as ze}from"node:fs/promises";import"@blink-sdk/compute-protocol/client";import{createInMemoryClientServer as Be}from"@blink-sdk/compute-protocol/transport";function Ve(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function He(e){return Object.fromEntries([...e.headers])}function Ue(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 We(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Ge(e,...t){let n=We(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ke=(({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 p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function qe(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Je=[`fetch failed`,`failed to fetch`];function Ye({error:e,url:t,requestBodyValues:n}){if(qe(e))return e;if(e instanceof TypeError&&Je.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Xe=`3.0.10`;function Ze({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Qe=/"__proto__"\s*:/,$e=/"constructor"\s*:/;function et(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Qe.test(e)===!1&&$e.test(e)===!1?t:tt(t)}function tt(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 nt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return et(e)}finally{Error.stackTraceLimit=t}}var rt=Symbol.for(`vercel.ai.validator`);function it(e){return{[rt]:!0,validate:e}}function at(e){return typeof e==`object`&&!!e&&rt in e&&e[rt]===!0&&`validate`in e}function ot(e){return at(e)?e:st(e)}function st(e){return it(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function ct({value:e,schema:t}){let n=await lt({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function lt({value:e,schema:t}){let n=ot(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:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function ut({text:e,schema:t}){try{let n=nt(e);return t==null?n:ct({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function dt({text:e,schema:t}){try{let n=nt(e);return t==null?{success:!0,value:n,rawValue:n}:await lt({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function ft({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await dt({text:e,schema:t}))}}))}async function pt({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await lt({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var mt=()=>globalThis.fetch,ht=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>gt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),gt=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=mt()})=>{try{let c=await o(e,{method:`POST`,headers:Ge(t,`ai-sdk/provider-utils/${Xe}`,Ue()),body:n.content,signal:a}),l=He(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw qe(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(qe(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Ye({error:t,url:e,requestBodyValues:n.values})}};function _t(e){return e}function vt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function yt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({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 bt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var xt=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=He(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await ut({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},St=e=>async({response:t})=>{let n=He(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:ft({stream:t.body,schema:e})}},Ct=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await dt({text:i,schema:e}),o=He(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:wt,atob:Tt}=globalThis;function Et(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return wt(t)}function Dt(e){return e instanceof Uint8Array?Et(e):e}function Ot(e){return e?.replace(/\/$/,``)}var kt=`2.0.23`,At=N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),jt=xt({errorSchema:At,errorToMessage:e=>e.error.message}),Mt=N.object({citations:N.object({enabled:N.boolean()}).optional(),title:N.string().optional(),context:N.string().optional()}),Nt=N.object({sendReasoning:N.boolean().optional(),thinking:N.object({type:N.union([N.literal(`enabled`),N.literal(`disabled`)]),budgetTokens:N.number().optional()}).optional(),disableParallelToolUse:N.boolean().optional(),cacheControl:N.object({type:N.literal(`ephemeral`),ttl:N.union([N.literal(`5m`),N.literal(`1h`)]).optional()}).optional()});function Pt(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Ft=N.object({maxCharacters:N.number().optional()}),It=vt({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),Lt=(e={})=>It(e),Rt=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),userLocation:N.object({type:N.literal(`approximate`),city:N.string().optional(),region:N.string().optional(),country:N.string().optional(),timezone:N.string().optional()}).optional()}),zt=N.array(N.object({url:N.string(),title:N.string(),pageAge:N.string().nullable(),encryptedContent:N.string(),type:N.literal(`web_search_result`)})),Bt=yt({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:N.object({query:N.string()}),outputSchema:zt}),Vt=(e={})=>Bt(e),Ht=N.object({maxUses:N.number().optional(),allowedDomains:N.array(N.string()).optional(),blockedDomains:N.array(N.string()).optional(),citations:N.object({enabled:N.boolean()}).optional(),maxContentTokens:N.number().optional()}),Ut=N.object({type:N.literal(`web_fetch_result`),url:N.string(),content:N.object({type:N.literal(`document`),title:N.string(),citations:N.object({enabled:N.boolean()}).optional(),source:N.union([N.object({type:N.literal(`base64`),mediaType:N.literal(`application/pdf`),data:N.string()}),N.object({type:N.literal(`text`),mediaType:N.literal(`text/plain`),data:N.string()})])}),retrievedAt:N.string().nullable()}),Wt=yt({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:N.object({url:N.string()}),outputSchema:Ut}),Gt=(e={})=>Wt(e);function Kt({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=Pt(t.providerOptions);a.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`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.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`:i.add(`computer-use-2024-10-22`),a.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`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Ft.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=Ht.parse(t.args);a.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=Rt.parse(t.args);a.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:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new S({functionality:`tool choice type: ${o}`})}}var qt=N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),Jt=yt({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:N.object({code:N.string()}),outputSchema:qt}),Yt=(e={})=>Jt(e);function Xt(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 S({functionality:`URL-based text documents are not supported for citations`}):new S({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Zt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=Qt(e),a,o=[];async function s(e){return(await pt({provider:`anthropic`,providerOptions:e,schema:Mt}))?.citations?.enabled??!1}async function c(e){let t=await pt({provider:`anthropic`,providerOptions:e,schema:Mt});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new S({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pt(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=Pt(a.providerOptions)??(o?Pt(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:Dt(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Dt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new S({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=Pt(r.providerOptions)??(a?Pt(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.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 S({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=Pt(s.providerOptions)??(c?Pt(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await pt({provider:`anthropic`,providerOptions:s.providerOptions,schema:cn});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.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 n.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}):n.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`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=qt.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Ut.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=zt.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function Qt(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 $t({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 en={webSearchResult:N.object({type:N.literal(`web_search_result_location`),cited_text:N.string(),url:N.string(),title:N.string(),encrypted_index:N.string()}),pageLocation:N.object({type:N.literal(`page_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_page_number:N.number(),end_page_number:N.number()}),charLocation:N.object({type:N.literal(`char_location`),cited_text:N.string(),document_index:N.number(),document_title:N.string().nullable(),start_char_index:N.number(),end_char_index:N.number()})},tn=N.discriminatedUnion(`type`,[en.webSearchResult,en.pageLocation,en.charLocation]);N.discriminatedUnion(`type`,[en.pageLocation,en.charLocation]);function nn(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rn(e,t,n);i&&r(i)}}function rn(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 an=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??Ke}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:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await pt({provider:`anthropic`,providerOptions:f,schema:Nt}),{prompt:g,betas:_}=await Zt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,b={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new S({functionality:`thinking requires a budget`});b.temperature!=null&&(b.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(b.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(b.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),b.max_tokens=t+y}let{tools:x,toolChoice:C,toolWarnings:w,betas:T}=Kt(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...b,tools:x,tool_choice:C},warnings:[...p,...w],betas:new Set([..._,...T]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return Ve(await bt(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 ht({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:jt,successfulResponseHandler:Ct(on),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)nn(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:$t({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 ht({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:jt,successfulResponseHandler:St(sn),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;nn(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=$t({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}}}},on=N.object({type:N.literal(`message`),id:N.string().nullish(),model:N.string().nullish(),content:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string(),citations:N.array(tn).optional()}),N.object({type:N.literal(`thinking`),thinking:N.string(),signature:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string(),input:N.unknown()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])),stop_reason:N.string().nullish(),stop_sequence:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})}),sn=N.discriminatedUnion(`type`,[N.object({type:N.literal(`message_start`),message:N.object({id:N.string().nullish(),model:N.string().nullish(),usage:N.looseObject({input_tokens:N.number(),cache_creation_input_tokens:N.number().nullish(),cache_read_input_tokens:N.number().nullish()})})}),N.object({type:N.literal(`content_block_start`),index:N.number(),content_block:N.discriminatedUnion(`type`,[N.object({type:N.literal(`text`),text:N.string()}),N.object({type:N.literal(`thinking`),thinking:N.string()}),N.object({type:N.literal(`tool_use`),id:N.string(),name:N.string()}),N.object({type:N.literal(`redacted_thinking`),data:N.string()}),N.object({type:N.literal(`server_tool_use`),id:N.string(),name:N.string(),input:N.record(N.string(),N.unknown()).nullish()}),N.object({type:N.literal(`web_fetch_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`web_fetch_result`),url:N.string(),retrieved_at:N.string(),content:N.object({type:N.literal(`document`),title:N.string().nullable(),citations:N.object({enabled:N.boolean()}).optional(),source:N.object({type:N.literal(`text`),media_type:N.string(),data:N.string()})})}),N.object({type:N.literal(`web_fetch_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`web_search_tool_result`),tool_use_id:N.string(),content:N.union([N.array(N.object({type:N.literal(`web_search_result`),url:N.string(),title:N.string(),encrypted_content:N.string(),page_age:N.string().nullish()})),N.object({type:N.literal(`web_search_tool_result_error`),error_code:N.string()})])}),N.object({type:N.literal(`code_execution_tool_result`),tool_use_id:N.string(),content:N.union([N.object({type:N.literal(`code_execution_result`),stdout:N.string(),stderr:N.string(),return_code:N.number()}),N.object({type:N.literal(`code_execution_tool_result_error`),error_code:N.string()})])})])}),N.object({type:N.literal(`content_block_delta`),index:N.number(),delta:N.discriminatedUnion(`type`,[N.object({type:N.literal(`input_json_delta`),partial_json:N.string()}),N.object({type:N.literal(`text_delta`),text:N.string()}),N.object({type:N.literal(`thinking_delta`),thinking:N.string()}),N.object({type:N.literal(`signature_delta`),signature:N.string()}),N.object({type:N.literal(`citations_delta`),citation:tn})])}),N.object({type:N.literal(`content_block_stop`),index:N.number()}),N.object({type:N.literal(`error`),error:N.object({type:N.string(),message:N.string()})}),N.object({type:N.literal(`message_delta`),delta:N.object({stop_reason:N.string().nullish(),stop_sequence:N.string().nullish()}),usage:N.looseObject({output_tokens:N.number(),cache_creation_input_tokens:N.number().nullish()})}),N.object({type:N.literal(`message_stop`)}),N.object({type:N.literal(`ping`)})]),cn=N.object({signature:N.string().optional(),redactedData:N.string().optional()}),ln=vt({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),un=vt({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:M.object({command:M.string(),restart:M.boolean().optional()})}),dn=vt({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:N.object({action:N.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:N.array(N.number().int()).optional(),text:N.string().optional()})}),fn=vt({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:N.object({action:N.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:N.tuple([N.number().int(),N.number().int()]).optional(),duration:N.number().optional(),scroll_amount:N.number().optional(),scroll_direction:N.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:N.tuple([N.number().int(),N.number().int()]).optional(),text:N.string().optional()})}),pn=vt({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),mn=vt({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),hn=vt({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:N.object({command:N.enum([`view`,`create`,`str_replace`,`insert`]),path:N.string(),file_text:N.string().optional(),insert_line:N.number().int().optional(),new_str:N.string().optional(),old_str:N.string().optional(),view_range:N.array(N.number().int()).optional()})}),gn={bash_20241022:ln,bash_20250124:un,codeExecution_20250522:Yt,computer_20241022:dn,computer_20250124:fn,textEditor_20241022:pn,textEditor_20250124:mn,textEditor_20250429:hn,textEditor_20250728:Lt,webFetch_20250910:Gt,webSearch_20250305:Vt};function _n(e={}){let t=Ot(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>Ge({"anthropic-version":`2023-06-01`,"x-api-key":Ze({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${kt}`),r=r=>new an(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??Ke,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new v({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new v({modelId:e,modelType:`imageModel`})},i.tools=gn,i}_n();function vn(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yn(e){return Object.fromEntries([...e.headers])}function bn(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 xn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Sn(e,...t){let n=xn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Cn=(({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 p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function wn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Tn=[`fetch failed`,`failed to fetch`];function En({error:e,url:t,requestBodyValues:n}){if(wn(e))return e;if(e instanceof TypeError&&Tn.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Dn=`3.0.10`;function On({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var kn=/"__proto__"\s*:/,An=/"constructor"\s*:/;function jn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||kn.test(e)===!1&&An.test(e)===!1?t:Mn(t)}function Mn(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 Nn(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return jn(e)}finally{Error.stackTraceLimit=t}}var Pn=Symbol.for(`vercel.ai.validator`);function Fn(e){return{[Pn]:!0,validate:e}}function In(e){return typeof e==`object`&&!!e&&Pn in e&&e[Pn]===!0&&`validate`in e}function Ln(e){return In(e)?e:Rn(e)}function Rn(e){return Fn(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function zn({value:e,schema:t}){let n=await Bn({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Bn({value:e,schema:t}){let n=Ln(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:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Vn({text:e,schema:t}){try{let n=Nn(e);return t==null?n:zn({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function Hn({text:e,schema:t}){try{let n=Nn(e);return t==null?{success:!0,value:n,rawValue:n}:await Bn({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function Un({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await Hn({text:e,schema:t}))}}))}async function Wn({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Bn({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Gn=()=>globalThis.fetch,Kn=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>qn({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),qn=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Gn()})=>{try{let c=await o(e,{method:`POST`,headers:Sn(t,`ai-sdk/provider-utils/${Dn}`,bn()),body:n.content,signal:a}),l=yn(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw wn(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(wn(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw En({error:t,url:e,requestBodyValues:n.values})}};function Jn(e){return e}function Yn({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Xn({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({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 Zn(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var Qn=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=yn(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Vn({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},$n=e=>async({response:t})=>{let n=yn(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:Un({stream:t.body,schema:e})}},er=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await Hn({text:i,schema:e}),o=yn(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:tr,atob:nr}=globalThis;function rr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return tr(t)}function ir(e){return e instanceof Uint8Array?rr(e):e}function ar(e){return e?.replace(/\/$/,``)}var or=`2.0.17`,sr=N.object({error:N.object({code:N.number().nullable(),message:N.string(),status:N.string()})}),cr=Qn({errorSchema:sr,errorToMessage:e=>e.error.message}),lr=N.object({outputDimensionality:N.number().optional(),taskType:N.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),ur=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:t,abortSignal:n,providerOptions:r}){let i=await Wn({provider:`google`,providerOptions:r,schema:lr});if(e.length>this.maxEmbeddingsPerCall)throw new b({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=vn(await Zn(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:cr,successfulResponseHandler:er(fr),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:cr,successfulResponseHandler:er(dr),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},dr=N.object({embeddings:N.array(N.object({values:N.array(N.number())}))}),fr=N.object({embedding:N.object({values:N.array(N.number())})});function pr(e){if(e==null||mr(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]=pr(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(pr):pr(a)),o&&(p.allOf=o.map(pr)),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=pr(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(pr),p.nullable=!0}else p.anyOf=s.map(pr);return c&&(p.oneOf=c.map(pr)),d!==void 0&&(p.minLength=d),p}function mr(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function hr(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new S({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)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:ir(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.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 S({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new S({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:ir(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`:{i=!1;let e=[];for(let t of a){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}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
1
+ import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"../chunk-D9KrCrVq.js";import{APICallError as s,APIServerURLEnvironmentVariable as c,Agent as l,EmptyResponseBodyError as u,EventSourceParserStream as d,Hono as f,InvalidArgumentError as p,InvalidPromptError as m,InvalidResponseDataError as h,JSONParseError as g,LoadAPIKeyError as _,NoSuchModelError as v,StreamResponseFormatHeader as y,TooManyEmbeddingValuesForCallError as b,TypeValidationError as x,UnsupportedFunctionalityError as S,createGatewayProvider as C,createServerAdapter as w,hc as ee,isToolApprovalOutput as T,lastUIOptions as E,tools as D,validator as O}from"../index.node-CU27y0G9.js";import"../token-error-488npYdU.js";import"../esm-CSXsVdYr.js";import"../context-Ch5QyxHM.js";import{resolveConfig as k}from"../build-DBcSkHHH.js";import{createRequire as A}from"node:module";import j,{z as M}from"zod/v4";import{ZodFirstPartyTypeKind as te}from"zod/v3";import{Buffer as ne}from"node:buffer";import*as N from"node:fs";import P,{existsSync as F,mkdirSync as re,readFileSync as I,unlinkSync as ie,writeFileSync as L}from"node:fs";import{fileURLToPath as ae}from"node:url";import{Writable as R}from"node:stream";import{promisify as oe,stripVTControlCharacters as se}from"node:util";import{createHash as ce}from"node:crypto";import le,{createServer as ue}from"http";import{dirname as z,join as de}from"path";import{existsSync as fe,mkdirSync as pe,readFileSync as me,watch as he,writeFileSync as ge}from"fs";import{convertToModelMessages as _e,isToolOrDynamicToolUIPart as ve,readUIMessageStream as ye,streamText as be,tool as xe}from"ai";import{readFile as Se,stat as B,writeFile as Ce}from"fs/promises";import{spawn as we}from"child_process";import{createContext as Te,useCallback as V,useEffect as H,useMemo as Ee,useRef as U,useState as W}from"react";import G,{z as K}from"zod";import*as q from"node:path";import De,{dirname as Oe,join as ke}from"node:path";import J,{stdin as Ae,stdout as je}from"node:process";import*as Me from"node:readline";import Ne from"node:readline";import Pe from"node:os";import Fe from"node:tty";import Ie,{execFile as Le}from"node:child_process";import Re,{constants as ze}from"node:fs/promises";import"@blink-sdk/compute-protocol/client";import{createInMemoryClientServer as Be}from"@blink-sdk/compute-protocol/transport";function Ve(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function He(e){return Object.fromEntries([...e.headers])}function Ue(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 We(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Ge(e,...t){let n=We(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Ke=(({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 p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function qe(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Je=[`fetch failed`,`failed to fetch`];function Ye({error:e,url:t,requestBodyValues:n}){if(qe(e))return e;if(e instanceof TypeError&&Je.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Xe=`3.0.10`;function Ze({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Qe=/"__proto__"\s*:/,$e=/"constructor"\s*:/;function et(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Qe.test(e)===!1&&$e.test(e)===!1?t:tt(t)}function tt(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 nt(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return et(e)}finally{Error.stackTraceLimit=t}}var rt=Symbol.for(`vercel.ai.validator`);function it(e){return{[rt]:!0,validate:e}}function at(e){return typeof e==`object`&&!!e&&rt in e&&e[rt]===!0&&`validate`in e}function ot(e){return at(e)?e:st(e)}function st(e){return it(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function ct({value:e,schema:t}){let n=await lt({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function lt({value:e,schema:t}){let n=ot(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:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function ut({text:e,schema:t}){try{let n=nt(e);return t==null?n:ct({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function dt({text:e,schema:t}){try{let n=nt(e);return t==null?{success:!0,value:n,rawValue:n}:await lt({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function ft({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await dt({text:e,schema:t}))}}))}async function pt({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await lt({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var mt=()=>globalThis.fetch,ht=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>gt({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),gt=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=mt()})=>{try{let c=await o(e,{method:`POST`,headers:Ge(t,`ai-sdk/provider-utils/${Xe}`,Ue()),body:n.content,signal:a}),l=He(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw qe(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(qe(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Ye({error:t,url:e,requestBodyValues:n.values})}};function _t(e){return e}function vt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function yt({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>_t({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 bt(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var xt=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=He(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await ut({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},St=e=>async({response:t})=>{let n=He(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:ft({stream:t.body,schema:e})}},Ct=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await dt({text:i,schema:e}),o=He(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:wt,atob:Tt}=globalThis;function Et(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return wt(t)}function Dt(e){return e instanceof Uint8Array?Et(e):e}function Ot(e){return e?.replace(/\/$/,``)}var kt=`2.0.23`,At=M.object({type:M.literal(`error`),error:M.object({type:M.string(),message:M.string()})}),jt=xt({errorSchema:At,errorToMessage:e=>e.error.message}),Mt=M.object({citations:M.object({enabled:M.boolean()}).optional(),title:M.string().optional(),context:M.string().optional()}),Nt=M.object({sendReasoning:M.boolean().optional(),thinking:M.object({type:M.union([M.literal(`enabled`),M.literal(`disabled`)]),budgetTokens:M.number().optional()}).optional(),disableParallelToolUse:M.boolean().optional(),cacheControl:M.object({type:M.literal(`ephemeral`),ttl:M.union([M.literal(`5m`),M.literal(`1h`)]).optional()}).optional()});function Pt(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var Ft=M.object({maxCharacters:M.number().optional()}),It=vt({id:`anthropic.text_editor_20250728`,name:`str_replace_based_edit_tool`,inputSchema:M.object({command:M.enum([`view`,`create`,`str_replace`,`insert`]),path:M.string(),file_text:M.string().optional(),insert_line:M.number().int().optional(),new_str:M.string().optional(),old_str:M.string().optional(),view_range:M.array(M.number().int()).optional()})}),Lt=(e={})=>It(e),Rt=M.object({maxUses:M.number().optional(),allowedDomains:M.array(M.string()).optional(),blockedDomains:M.array(M.string()).optional(),userLocation:M.object({type:M.literal(`approximate`),city:M.string().optional(),region:M.string().optional(),country:M.string().optional(),timezone:M.string().optional()}).optional()}),zt=M.array(M.object({url:M.string(),title:M.string(),pageAge:M.string().nullable(),encryptedContent:M.string(),type:M.literal(`web_search_result`)})),Bt=yt({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:M.object({query:M.string()}),outputSchema:zt}),Vt=(e={})=>Bt(e),Ht=M.object({maxUses:M.number().optional(),allowedDomains:M.array(M.string()).optional(),blockedDomains:M.array(M.string()).optional(),citations:M.object({enabled:M.boolean()}).optional(),maxContentTokens:M.number().optional()}),Ut=M.object({type:M.literal(`web_fetch_result`),url:M.string(),content:M.object({type:M.literal(`document`),title:M.string(),citations:M.object({enabled:M.boolean()}).optional(),source:M.union([M.object({type:M.literal(`base64`),mediaType:M.literal(`application/pdf`),data:M.string()}),M.object({type:M.literal(`text`),mediaType:M.literal(`text/plain`),data:M.string()})])}),retrievedAt:M.string().nullable()}),Wt=yt({id:`anthropic.web_fetch_20250910`,name:`web_fetch`,inputSchema:M.object({url:M.string()}),outputSchema:Ut}),Gt=(e={})=>Wt(e);function Kt({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e)switch(t.type){case`function`:{let e=Pt(t.providerOptions);a.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`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.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`:i.add(`computer-use-2024-10-22`),a.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`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.text_editor_20250728`:{let e=Ft.parse(t.args);a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters});break}case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_fetch_20250910`:{i.add(`web-fetch-2025-09-10`);let e=Ht.parse(t.args);a.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=Rt.parse(t.args);a.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:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:throw new S({functionality:`tool choice type: ${o}`})}}var qt=M.object({type:M.literal(`code_execution_result`),stdout:M.string(),stderr:M.string(),return_code:M.number()}),Jt=yt({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:M.object({code:M.string()}),outputSchema:qt}),Yt=(e={})=>Jt(e);function Xt(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 S({functionality:`URL-based text documents are not supported for citations`}):new S({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Zt({prompt:e,sendReasoning:t,warnings:n}){let r=new Set,i=Qt(e),a,o=[];async function s(e){return(await pt({provider:`anthropic`,providerOptions:e,schema:Mt}))?.citations?.enabled??!1}async function c(e){let t=await pt({provider:`anthropic`,providerOptions:e,schema:Mt});return{title:t?.title,context:t?.context}}for(let e=0;e<i.length;e++){let l=i[e],u=e===i.length-1,d=l.type;switch(d){case`system`:if(a!=null)throw new S({functionality:`Multiple system messages that are separated by user/assistant messages`});a=l.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Pt(t)}));break;case`user`:{let e=[];for(let t of l.messages){let{role:n,content:i}=t;switch(n){case`user`:for(let n=0;n<i.length;n++){let a=i[n],o=n===i.length-1,l=Pt(a.providerOptions)??(o?Pt(t.providerOptions):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:l});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:Dt(a.data)},cache_control:l});else if(a.mediaType===`application/pdf`){r.add(`pdfs-2024-09-25`);let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Dt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else if(a.mediaType===`text/plain`){let t=await s(a.providerOptions),n=await c(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:Xt(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:l})}else throw new S({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<i.length;n++){let r=i[n],a=n===i.length-1,o=Pt(r.providerOptions)??(a?Pt(t.providerOptions):void 0),s=r.output,c;switch(s.type){case`content`:c=s.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 S({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:c=s.value;break;case`json`:case`error-json`:default:c=JSON.stringify(s.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:c,is_error:s.type===`error-text`||s.type===`error-json`?!0:void 0,cache_control:o})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}o.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<l.messages.length;r++){let i=l.messages[r],a=r===l.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let s=o[r],c=r===o.length-1,l=Pt(s.providerOptions)??(c?Pt(i.providerOptions):void 0);switch(s.type){case`text`:e.push({type:`text`,text:u&&a&&c?s.text.trim():s.text,cache_control:l});break;case`reasoning`:if(t){let t=await pt({provider:`anthropic`,providerOptions:s.providerOptions,schema:cn});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.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 n.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}):n.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`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=qt.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:s.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:l});break}if(s.toolName===`web_fetch`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=Ut.parse(t.value);e.push({type:`web_fetch_tool_result`,tool_use_id:s.toolCallId,content:{type:`web_fetch_result`,url:r.url,retrieved_at:r.retrievedAt,content:{type:`document`,title:r.content.title,citations:r.content.citations,source:{type:r.content.source.type,media_type:r.content.source.mediaType,data:r.content.source.data}}},cache_control:l});break}if(s.toolName===`web_search`){let t=s.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${s.toolName} is not supported`});break}let r=zt.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:s.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:l});break}n.push({type:`other`,message:`provider executed tool result for tool ${s.toolName} is not supported`});break}}}o.push({role:`assistant`,content:e});break}default:{let e=d;throw Error(`content type: ${e}`)}}}return{prompt:{system:a,messages:o},betas:r}}function Qt(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 $t({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 en={webSearchResult:M.object({type:M.literal(`web_search_result_location`),cited_text:M.string(),url:M.string(),title:M.string(),encrypted_index:M.string()}),pageLocation:M.object({type:M.literal(`page_location`),cited_text:M.string(),document_index:M.number(),document_title:M.string().nullable(),start_page_number:M.number(),end_page_number:M.number()}),charLocation:M.object({type:M.literal(`char_location`),cited_text:M.string(),document_index:M.number(),document_title:M.string().nullable(),start_char_index:M.number(),end_char_index:M.number()})},tn=M.discriminatedUnion(`type`,[en.webSearchResult,en.pageLocation,en.charLocation]);M.discriminatedUnion(`type`,[en.pageLocation,en.charLocation]);function nn(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=rn(e,t,n);i&&r(i)}}function rn(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 an=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??Ke}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:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[];a!=null&&p.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&p.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&p.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&p.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let m=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,h=await pt({provider:`anthropic`,providerOptions:f,schema:Nt}),{prompt:g,betas:_}=await Zt({prompt:e,sendReasoning:h?.sendReasoning??!0,warnings:p}),v=h?.thinking?.type===`enabled`,y=h?.thinking?.budgetTokens,b={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...v&&{thinking:{type:`enabled`,budget_tokens:y}},system:g.system,messages:g.messages};if(v){if(y==null)throw new S({functionality:`thinking requires a budget`});b.temperature!=null&&(b.temperature=void 0,p.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(b.top_k=void 0,p.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(b.top_p=void 0,p.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),b.max_tokens=t+y}let{tools:x,toolChoice:C,toolWarnings:w,betas:ee}=Kt(m==null?{tools:u??[],toolChoice:d,disableParallelToolUse:h?.disableParallelToolUse}:{tools:[m],toolChoice:{type:`tool`,toolName:m.name},disableParallelToolUse:!0});return{args:{...b,tools:x,tool_choice:C},warnings:[...p,...w],betas:new Set([..._,...ee]),usesJsonResponseTool:m!=null}}async getHeaders({betas:e,headers:t}){return Ve(await bt(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 ht({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:jt,successfulResponseHandler:Ct(on),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)nn(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:$t({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 ht({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:jt,successfulResponseHandler:St(sn),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;nn(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=$t({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}}}},on=M.object({type:M.literal(`message`),id:M.string().nullish(),model:M.string().nullish(),content:M.array(M.discriminatedUnion(`type`,[M.object({type:M.literal(`text`),text:M.string(),citations:M.array(tn).optional()}),M.object({type:M.literal(`thinking`),thinking:M.string(),signature:M.string()}),M.object({type:M.literal(`redacted_thinking`),data:M.string()}),M.object({type:M.literal(`tool_use`),id:M.string(),name:M.string(),input:M.unknown()}),M.object({type:M.literal(`server_tool_use`),id:M.string(),name:M.string(),input:M.record(M.string(),M.unknown()).nullish()}),M.object({type:M.literal(`web_fetch_tool_result`),tool_use_id:M.string(),content:M.union([M.object({type:M.literal(`web_fetch_result`),url:M.string(),retrieved_at:M.string(),content:M.object({type:M.literal(`document`),title:M.string().nullable(),citations:M.object({enabled:M.boolean()}).optional(),source:M.object({type:M.literal(`text`),media_type:M.string(),data:M.string()})})}),M.object({type:M.literal(`web_fetch_tool_result_error`),error_code:M.string()})])}),M.object({type:M.literal(`web_search_tool_result`),tool_use_id:M.string(),content:M.union([M.array(M.object({type:M.literal(`web_search_result`),url:M.string(),title:M.string(),encrypted_content:M.string(),page_age:M.string().nullish()})),M.object({type:M.literal(`web_search_tool_result_error`),error_code:M.string()})])}),M.object({type:M.literal(`code_execution_tool_result`),tool_use_id:M.string(),content:M.union([M.object({type:M.literal(`code_execution_result`),stdout:M.string(),stderr:M.string(),return_code:M.number()}),M.object({type:M.literal(`code_execution_tool_result_error`),error_code:M.string()})])})])),stop_reason:M.string().nullish(),stop_sequence:M.string().nullish(),usage:M.looseObject({input_tokens:M.number(),output_tokens:M.number(),cache_creation_input_tokens:M.number().nullish(),cache_read_input_tokens:M.number().nullish()})}),sn=M.discriminatedUnion(`type`,[M.object({type:M.literal(`message_start`),message:M.object({id:M.string().nullish(),model:M.string().nullish(),usage:M.looseObject({input_tokens:M.number(),cache_creation_input_tokens:M.number().nullish(),cache_read_input_tokens:M.number().nullish()})})}),M.object({type:M.literal(`content_block_start`),index:M.number(),content_block:M.discriminatedUnion(`type`,[M.object({type:M.literal(`text`),text:M.string()}),M.object({type:M.literal(`thinking`),thinking:M.string()}),M.object({type:M.literal(`tool_use`),id:M.string(),name:M.string()}),M.object({type:M.literal(`redacted_thinking`),data:M.string()}),M.object({type:M.literal(`server_tool_use`),id:M.string(),name:M.string(),input:M.record(M.string(),M.unknown()).nullish()}),M.object({type:M.literal(`web_fetch_tool_result`),tool_use_id:M.string(),content:M.union([M.object({type:M.literal(`web_fetch_result`),url:M.string(),retrieved_at:M.string(),content:M.object({type:M.literal(`document`),title:M.string().nullable(),citations:M.object({enabled:M.boolean()}).optional(),source:M.object({type:M.literal(`text`),media_type:M.string(),data:M.string()})})}),M.object({type:M.literal(`web_fetch_tool_result_error`),error_code:M.string()})])}),M.object({type:M.literal(`web_search_tool_result`),tool_use_id:M.string(),content:M.union([M.array(M.object({type:M.literal(`web_search_result`),url:M.string(),title:M.string(),encrypted_content:M.string(),page_age:M.string().nullish()})),M.object({type:M.literal(`web_search_tool_result_error`),error_code:M.string()})])}),M.object({type:M.literal(`code_execution_tool_result`),tool_use_id:M.string(),content:M.union([M.object({type:M.literal(`code_execution_result`),stdout:M.string(),stderr:M.string(),return_code:M.number()}),M.object({type:M.literal(`code_execution_tool_result_error`),error_code:M.string()})])})])}),M.object({type:M.literal(`content_block_delta`),index:M.number(),delta:M.discriminatedUnion(`type`,[M.object({type:M.literal(`input_json_delta`),partial_json:M.string()}),M.object({type:M.literal(`text_delta`),text:M.string()}),M.object({type:M.literal(`thinking_delta`),thinking:M.string()}),M.object({type:M.literal(`signature_delta`),signature:M.string()}),M.object({type:M.literal(`citations_delta`),citation:tn})])}),M.object({type:M.literal(`content_block_stop`),index:M.number()}),M.object({type:M.literal(`error`),error:M.object({type:M.string(),message:M.string()})}),M.object({type:M.literal(`message_delta`),delta:M.object({stop_reason:M.string().nullish(),stop_sequence:M.string().nullish()}),usage:M.looseObject({output_tokens:M.number(),cache_creation_input_tokens:M.number().nullish()})}),M.object({type:M.literal(`message_stop`)}),M.object({type:M.literal(`ping`)})]),cn=M.object({signature:M.string().optional(),redactedData:M.string().optional()}),ln=vt({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:j.object({command:j.string(),restart:j.boolean().optional()})}),un=vt({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:j.object({command:j.string(),restart:j.boolean().optional()})}),dn=vt({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:M.object({action:M.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:M.array(M.number().int()).optional(),text:M.string().optional()})}),fn=vt({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:M.object({action:M.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:M.tuple([M.number().int(),M.number().int()]).optional(),duration:M.number().optional(),scroll_amount:M.number().optional(),scroll_direction:M.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:M.tuple([M.number().int(),M.number().int()]).optional(),text:M.string().optional()})}),pn=vt({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:M.object({command:M.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:M.string(),file_text:M.string().optional(),insert_line:M.number().int().optional(),new_str:M.string().optional(),old_str:M.string().optional(),view_range:M.array(M.number().int()).optional()})}),mn=vt({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:M.object({command:M.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:M.string(),file_text:M.string().optional(),insert_line:M.number().int().optional(),new_str:M.string().optional(),old_str:M.string().optional(),view_range:M.array(M.number().int()).optional()})}),hn=vt({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:M.object({command:M.enum([`view`,`create`,`str_replace`,`insert`]),path:M.string(),file_text:M.string().optional(),insert_line:M.number().int().optional(),new_str:M.string().optional(),old_str:M.string().optional(),view_range:M.array(M.number().int()).optional()})}),gn={bash_20241022:ln,bash_20250124:un,codeExecution_20250522:Yt,computer_20241022:dn,computer_20250124:fn,textEditor_20241022:pn,textEditor_20250124:mn,textEditor_20250429:hn,textEditor_20250728:Lt,webFetch_20250910:Gt,webSearch_20250305:Vt};function _n(e={}){let t=Ot(e.baseURL)??`https://api.anthropic.com/v1`,n=()=>Ge({"anthropic-version":`2023-06-01`,"x-api-key":Ze({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${kt}`),r=r=>new an(r,{provider:`anthropic.messages`,baseURL:t,headers:n,fetch:e.fetch,generateId:e.generateId??Ke,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),i=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return r(e)};return i.languageModel=r,i.chat=r,i.messages=r,i.textEmbeddingModel=e=>{throw new v({modelId:e,modelType:`textEmbeddingModel`})},i.imageModel=e=>{throw new v({modelId:e,modelType:`imageModel`})},i.tools=gn,i}_n();function vn(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function yn(e){return Object.fromEntries([...e.headers])}function bn(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 xn(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Sn(e,...t){let n=xn(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Cn=(({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 p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function wn(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Tn=[`fetch failed`,`failed to fetch`];function En({error:e,url:t,requestBodyValues:n}){if(wn(e))return e;if(e instanceof TypeError&&Tn.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Dn=`3.0.10`;function On({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var kn=/"__proto__"\s*:/,An=/"constructor"\s*:/;function jn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||kn.test(e)===!1&&An.test(e)===!1?t:Mn(t)}function Mn(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 Nn(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return jn(e)}finally{Error.stackTraceLimit=t}}var Pn=Symbol.for(`vercel.ai.validator`);function Fn(e){return{[Pn]:!0,validate:e}}function In(e){return typeof e==`object`&&!!e&&Pn in e&&e[Pn]===!0&&`validate`in e}function Ln(e){return In(e)?e:Rn(e)}function Rn(e){return Fn(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function zn({value:e,schema:t}){let n=await Bn({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Bn({value:e,schema:t}){let n=Ln(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:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Vn({text:e,schema:t}){try{let n=Nn(e);return t==null?n:zn({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function Hn({text:e,schema:t}){try{let n=Nn(e);return t==null?{success:!0,value:n,rawValue:n}:await Bn({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function Un({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await Hn({text:e,schema:t}))}}))}async function Wn({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Bn({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Gn=()=>globalThis.fetch,Kn=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>qn({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),qn=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Gn()})=>{try{let c=await o(e,{method:`POST`,headers:Sn(t,`ai-sdk/provider-utils/${Dn}`,bn()),body:n.content,signal:a}),l=yn(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw wn(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(wn(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw En({error:t,url:e,requestBodyValues:n.values})}};function Jn(e){return e}function Yn({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Xn({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>Jn({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 Zn(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var Qn=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=yn(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Vn({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},$n=e=>async({response:t})=>{let n=yn(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:Un({stream:t.body,schema:e})}},er=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await Hn({text:i,schema:e}),o=yn(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:tr,atob:nr}=globalThis;function rr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return tr(t)}function ir(e){return e instanceof Uint8Array?rr(e):e}function ar(e){return e?.replace(/\/$/,``)}var or=`2.0.17`,sr=M.object({error:M.object({code:M.number().nullable(),message:M.string(),status:M.string()})}),cr=Qn({errorSchema:sr,errorToMessage:e=>e.error.message}),lr=M.object({outputDimensionality:M.number().optional(),taskType:M.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),ur=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:t,abortSignal:n,providerOptions:r}){let i=await Wn({provider:`google`,providerOptions:r,schema:lr});if(e.length>this.maxEmbeddingsPerCall)throw new b({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=vn(await Zn(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:cr,successfulResponseHandler:er(fr),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await Kn({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:cr,successfulResponseHandler:er(dr),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},dr=M.object({embeddings:M.array(M.object({values:M.array(M.number())}))}),fr=M.object({embedding:M.object({values:M.array(M.number())})});function pr(e){if(e==null||mr(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]=pr(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(pr):pr(a)),o&&(p.allOf=o.map(pr)),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=pr(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(pr),p.nullable=!0}else p.anyOf=s.map(pr);return c&&(p.oneOf=c.map(pr)),d!==void 0&&(p.minLength=d),p}function mr(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function hr(e,t){let n=[],r=[],i=!0,a=t?.isGemmaModel??!1;for(let{role:t,content:a}of e)switch(t){case`system`:if(!i)throw new S({functionality:`system messages are only supported at the beginning of the conversation`});n.push({text:a});break;case`user`:{i=!1;let e=[];for(let t of a)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:ir(t.data)}});break}}r.push({role:`user`,parts:e});break}case`assistant`:i=!1,r.push({role:`model`,parts:a.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 S({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new S({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:ir(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`:{i=!1;let e=[];for(let t of a){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}}})}r.push({role:`user`,parts:e});break}}if(a&&n.length>0&&r.length>0&&r[0].role===`user`){let e=n.map(e=>e.text).join(`
2
2
 
3
3
  `);r[0].parts.unshift({text:e+`
4
4
 
5
- `})}return{systemInstruction:n.length>0&&!a?{parts:n}:void 0,contents:r}}function gr(e){return e.includes(`/`)?e:`models/${e}`}var _r=N.object({responseModalities:N.array(N.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:N.object({thinkingBudget:N.number().optional(),includeThoughts:N.boolean().optional()}).optional(),cachedContent:N.string().optional(),structuredOutputs:N.boolean().optional(),safetySettings:N.array(N.object({category:N.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:N.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:N.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:N.boolean().optional(),labels:N.record(N.string(),N.string()).optional()});function vr({tools:e,toolChoice:t,modelId:n}){e=e?.length?e:void 0;let r=[],i=n.includes(`gemini-2`),a=n.includes(`gemini-1.5-flash`)&&!n.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:r};let o=e.some(e=>e.type===`function`),s=e.some(e=>e.type===`provider-defined`);if(o&&s&&r.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.`}),s){let t={};return e.filter(e=>e.type===`provider-defined`).forEach(e=>{switch(e.id){case`google.google_search`:i?t.googleSearch={}:a?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:i?t.urlContext={}:r.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`:i?t.codeExecution={}:r.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:r.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:r}}let c=[];for(let t of e)switch(t.type){case`function`:c.push({name:t.name,description:t.description??``,parameters:pr(t.inputSchema)});break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:{functionDeclarations:c},toolConfig:void 0,toolWarnings:r};let l=t.type;switch(l){case`auto`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:r};case`none`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:r};case`required`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:r};case`tool`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:r};default:throw new S({functionality:`tool choice type: ${l}`})}}function yr({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 br=N.object({web:N.object({uri:N.string(),title:N.string()}).nullish(),retrievedContext:N.object({uri:N.string(),title:N.string()}).nullish()}),xr=N.object({webSearchQueries:N.array(N.string()).nullish(),retrievalQueries:N.array(N.string()).nullish(),searchEntryPoint:N.object({renderedContent:N.string()}).nullish(),groundingChunks:N.array(br).nullish(),groundingSupports:N.array(N.object({segment:N.object({startIndex:N.number().nullish(),endIndex:N.number().nullish(),text:N.string().nullish()}),segment_text:N.string().nullish(),groundingChunkIndices:N.array(N.number()).nullish(),supportChunkIndices:N.array(N.number()).nullish(),confidenceScores:N.array(N.number()).nullish(),confidenceScore:N.array(N.number()).nullish()})).nullish(),retrievalMetadata:N.union([N.object({webDynamicRetrievalScore:N.number()}),N.object({})]).nullish()}),Sr=Yn({id:`google.google_search`,name:`google_search`,inputSchema:N.object({mode:N.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:N.number().default(1)})}),Cr=N.object({retrievedUrl:N.string(),urlRetrievalStatus:N.string()}),wr=N.object({urlMetadata:N.array(Cr)}),Tr=Yn({id:`google.url_context`,name:`url_context`,inputSchema:N.object({})}),Er=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??Cn}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 Wn({provider:`google`,providerOptions:f,schema:_r});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:_}=hr(e,{isGemmaModel:h}),{tools:v,toolConfig:y,toolWarnings:b}=vr({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)?pr(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=vn(await Zn(this.config.headers),e.headers),{responseHeaders:a,value:o,rawValue:s}=await Kn({url:`${this.config.baseURL}/${gr(this.modelId)}:generateContent`,headers:i,body:t,failedResponseHandler:cr,successfulResponseHandler:er(Nr),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=kr({groundingMetadata:c.groundingMetadata,generateId:this.config.generateId})??[];for(let e of p)l.push(e);return{content:l,finishReason:yr({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=vn(await Zn(this.config.headers),e.headers),{responseHeaders:a,value:o}=await Kn({url:`${this.config.baseURL}/${gr(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:cr,successfulResponseHandler:$n(Pr),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,_=kr({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=Or(o.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=Dr({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=yr({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 Dr({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 Or(e){return e?.filter(e=>`inlineData`in e)}function kr({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 Ar=N.object({parts:N.array(N.union([N.object({functionCall:N.object({name:N.string(),args:N.unknown()}),thoughtSignature:N.string().nullish()}),N.object({inlineData:N.object({mimeType:N.string(),data:N.string()})}),N.object({executableCode:N.object({language:N.string(),code:N.string()}).nullish(),codeExecutionResult:N.object({outcome:N.string(),output:N.string()}).nullish(),text:N.string().nullish(),thought:N.boolean().nullish(),thoughtSignature:N.string().nullish()})])).nullish()}),jr=N.object({category:N.string().nullish(),probability:N.string().nullish(),probabilityScore:N.number().nullish(),severity:N.string().nullish(),severityScore:N.number().nullish(),blocked:N.boolean().nullish()}),Mr=N.object({cachedContentTokenCount:N.number().nullish(),thoughtsTokenCount:N.number().nullish(),promptTokenCount:N.number().nullish(),candidatesTokenCount:N.number().nullish(),totalTokenCount:N.number().nullish()}),Nr=N.object({candidates:N.array(N.object({content:Ar.nullish().or(N.object({}).strict()),finishReason:N.string().nullish(),safetyRatings:N.array(jr).nullish(),groundingMetadata:xr.nullish(),urlContextMetadata:wr.nullish()})),usageMetadata:Mr.nullish(),promptFeedback:N.object({blockReason:N.string().nullish(),safetyRatings:N.array(jr).nullish()}).nullish()}),Pr=N.object({candidates:N.array(N.object({content:Ar.nullish(),finishReason:N.string().nullish(),safetyRatings:N.array(jr).nullish(),groundingMetadata:xr.nullish(),urlContextMetadata:wr.nullish()})).nullish(),usageMetadata:Mr.nullish(),promptFeedback:N.object({blockReason:N.string().nullish(),safetyRatings:N.array(jr).nullish()}).nullish()}),Fr=Xn({id:`google.code_execution`,name:`code_execution`,inputSchema:N.object({language:N.string().describe(`The programming language of the code.`),code:N.string().describe(`The code to be executed.`)}),outputSchema:N.object({outcome:N.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:N.string().describe(`The output from the code execution.`)})}),Ir={googleSearch:Sr,urlContext:Tr,codeExecution:Fr},Lr=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 Wn({provider:`google`,providerOptions:s,schema:zr}),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 Kn({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:vn(await Zn(this.config.headers),c),body:m,failedResponseHandler:cr,successfulResponseHandler:er(Rr),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}}}},Rr=N.object({predictions:N.array(N.object({bytesBase64Encoded:N.string()})).default([])}),zr=N.object({personGeneration:N.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:N.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function Br(e={}){let t=ar(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=()=>Sn({"x-goog-api-key":On({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${or}`),r=r=>new Er(r,{provider:`google.generative-ai`,baseURL:t,headers:n,generateId:e.generateId??Cn,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 ur(r,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),a=(r,i={})=>new Lr(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=Ir,o}Br();function Vr(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function Hr(e){return Object.fromEntries([...e.headers])}function Ur(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 Wr(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Gr(e,...t){let n=Wr(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Kr=(({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 p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function qr(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Jr=[`fetch failed`,`failed to fetch`];function Yr({error:e,url:t,requestBodyValues:n}){if(qr(e))return e;if(e instanceof TypeError&&Jr.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Xr=`3.0.10`;function Zr({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Qr({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 $r(e){let[t,n=``]=e.toLowerCase().split(`/`);return{mpeg:`mp3`,"x-wav":`wav`,opus:`ogg`,mp4:`m4a`,"x-m4a":`m4a`}[n]??n}var ei=/"__proto__"\s*:/,ti=/"constructor"\s*:/;function ni(e){let t=JSON.parse(e);return typeof t!=`object`||!t||ei.test(e)===!1&&ti.test(e)===!1?t:ri(t)}function ri(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 ii(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return ni(e)}finally{Error.stackTraceLimit=t}}var ai=Symbol.for(`vercel.ai.validator`);function oi(e){return{[ai]:!0,validate:e}}function si(e){return typeof e==`object`&&!!e&&ai in e&&e[ai]===!0&&`validate`in e}function ci(e){return si(e)?e:li(e)}function li(e){return oi(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function ui({value:e,schema:t}){let n=await di({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function di({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:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function fi({text:e,schema:t}){try{let n=ii(e);return t==null?n:ui({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function pi({text:e,schema:t}){try{let n=ii(e);return t==null?{success:!0,value:n,rawValue:n}:await di({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function mi(e){try{return ii(e),!0}catch{return!1}}function hi({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await pi({text:e,schema:t}))}}))}async function gi({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await di({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var _i=()=>globalThis.fetch,vi=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>bi({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),yi=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>bi({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),bi=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=_i()})=>{try{let c=await o(e,{method:`POST`,headers:Gr(t,`ai-sdk/provider-utils/${Xr}`,Ur()),body:n.content,signal:a}),l=Hr(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw qr(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(qr(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Yr({error:t,url:e,requestBodyValues:n.values})}};function xi(e){return e}function Si({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>xi({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Ci({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>xi({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}var wi=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=Hr(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await fi({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},Ti=e=>async({response:t})=>{let n=Hr(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:hi({stream:t.body,schema:e})}},Ei=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await pi({text:i,schema:e}),o=Hr(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},Di=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=Hr(e);if(!e.body)throw new s({message:`Response body is empty`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new s({message:`Failed to read response as array buffer`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},{btoa:Oi,atob:ki}=globalThis;function Ai(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=ki(t);return Uint8Array.from(n,e=>e.codePointAt(0))}function ji(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Oi(t)}function Mi(e){return e instanceof Uint8Array?ji(e):e}function Ni(e){return e?.replace(/\/$/,``)}var Pi=N.object({error:N.object({message:N.string(),type:N.string().nullish(),param:N.any().nullish(),code:N.union([N.string(),N.number()]).nullish()})}),Fi=wi({errorSchema:Pi,errorToMessage:e=>e.error.message});function Ii({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:i,content:a}of e)switch(i){case`system`:switch(t){case`system`:n.push({role:`system`,content:a});break;case`developer`:n.push({role:`developer`,content:a});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:if(a.length===1&&a[0].type===`text`){n.push({role:`user`,content:a[0].text});break}n.push({role:`user`,content:a.map((e,t)=>{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,${Mi(e.data)}`,detail:e.providerOptions?.openai?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new S({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:Mi(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:Mi(e.data),format:`mp3`}};default:throw new S({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new S({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-${t}.pdf`,file_data:`data:application/pdf;base64,${Mi(e.data)}`}}}else throw new S({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of a)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 a){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=i;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function Li({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 Ri(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 zi=N.object({logitBias:N.record(N.coerce.number(),N.number()).optional(),logprobs:N.union([N.boolean(),N.number()]).optional(),parallelToolCalls:N.boolean().optional(),user:N.string().optional(),reasoningEffort:N.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:N.number().optional(),store:N.boolean().optional(),metadata:N.record(N.string().max(64),N.string().max(512)).optional(),prediction:N.record(N.string(),N.any()).optional(),structuredOutputs:N.boolean().optional(),serviceTier:N.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:N.boolean().optional(),textVerbosity:N.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:N.string().optional(),safetyIdentifier:N.string().optional()});function Bi({tools:e,toolChoice:t,structuredOutputs: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`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:n?r:void 0}});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=t.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:i};default:throw new S({functionality:`tool choice type: ${o}`})}}var Vi=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 gi({provider:`openai`,providerOptions:f,schema:zi})??{},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:_}=Ii({prompt:e,systemMessageMode:Ji(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};Gi(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`&&!Ki(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`&&!qi(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}=Bi({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 vi({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:t,failedResponseHandler:Fi,successfulResponseHandler:Ei(Ui),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??Kr(),toolName:e.function.name,input:e.function.arguments});for(let e of o.message.annotations??[])s.push({type:`source`,sourceType:`url`,id:Kr(),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:Ri(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:{...Li(i),headers:r,body:a},warnings:n,providerMetadata:d}}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 vi({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:r,failedResponseHandler:Fi,successfulResponseHandler:Ti(Wi),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=[],s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0,u=!1,d={openai:{}};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){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}l&&(l=!1,n.enqueue({type:`response-metadata`,...Li(r)})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens??void 0,c.outputTokens=r.usage.completion_tokens??void 0,c.totalTokens=r.usage.total_tokens??void 0,c.reasoningTokens=r.usage.completion_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=r.usage.prompt_tokens_details?.cached_tokens??void 0,r.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=r.usage.completion_tokens_details?.accepted_prediction_tokens),r.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=r.usage.completion_tokens_details?.rejected_prediction_tokens));let i=r.choices[0];if(i?.finish_reason!=null&&(s=Ri(i.finish_reason)),i?.logprobs?.content!=null&&(d.openai.logprobs=i.logprobs.content),i?.delta==null)return;let a=i.delta;if(a.content!=null&&(u||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:a.content})),a.tool_calls!=null)for(let e of a.tool_calls){let t=e.index;if(o[t]==null){if(e.type!==`function`)throw new h({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new h({data:e,message:`Expected 'id' to be a string.`});if(e.function?.name==null)throw new h({data:e,message:`Expected 'function.name' to be a string.`});n.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),o[t]={id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments??``},hasFinished:!1};let r=o[t];r.function?.name!=null&&r.function?.arguments!=null&&(r.function.arguments.length>0&&n.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments}),mi(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??Kr(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}let r=o[t];r.hasFinished||(e.function?.arguments!=null&&(r.function.arguments+=e.function?.arguments??``),n.enqueue({type:`tool-input-delta`,id:r.id,delta:e.function.arguments??``}),r.function?.name!=null&&r.function?.arguments!=null&&mi(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??Kr(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(a.annotations!=null)for(let e of a.annotations)n.enqueue({type:`source`,sourceType:`url`,id:Kr(),url:e.url,title:e.title})},flush(e){u&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,usage:c,...d==null?{}:{providerMetadata:d}})}})),request:{body:r},response:{headers:i}}}},Hi=N.object({prompt_tokens:N.number().nullish(),completion_tokens:N.number().nullish(),total_tokens:N.number().nullish(),prompt_tokens_details:N.object({cached_tokens:N.number().nullish()}).nullish(),completion_tokens_details:N.object({reasoning_tokens:N.number().nullish(),accepted_prediction_tokens:N.number().nullish(),rejected_prediction_tokens:N.number().nullish()}).nullish()}).nullish(),Ui=N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({message:N.object({role:N.literal(`assistant`).nullish(),content:N.string().nullish(),tool_calls:N.array(N.object({id:N.string().nullish(),type:N.literal(`function`),function:N.object({name:N.string(),arguments:N.string()})})).nullish(),annotations:N.array(N.object({type:N.literal(`url_citation`),start_index:N.number(),end_index:N.number(),url:N.string(),title:N.string()})).nullish()}),index:N.number(),logprobs:N.object({content:N.array(N.object({token:N.string(),logprob:N.number(),top_logprobs:N.array(N.object({token:N.string(),logprob:N.number()}))})).nullish()}).nullish(),finish_reason:N.string().nullish()})),usage:Hi}),Wi=N.union([N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({delta:N.object({role:N.enum([`assistant`]).nullish(),content:N.string().nullish(),tool_calls:N.array(N.object({index:N.number(),id:N.string().nullish(),type:N.literal(`function`).nullish(),function:N.object({name:N.string().nullish(),arguments:N.string().nullish()})})).nullish(),annotations:N.array(N.object({type:N.literal(`url_citation`),start_index:N.number(),end_index:N.number(),url:N.string(),title:N.string()})).nullish()}).nullish(),logprobs:N.object({content:N.array(N.object({token:N.string(),logprob:N.number(),top_logprobs:N.array(N.object({token:N.string(),logprob:N.number()}))})).nullish()}).nullish(),finish_reason:N.string().nullish(),index:N.number()})),usage:Hi}),Pi]);function Gi(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function Ki(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function qi(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 Ji(e){return Gi(e)?Yi[e]?.systemMessageMode??`developer`:`system`}var Yi={"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 Xi({prompt:e,user:t=`user`,assistant:n=`assistant`}){let r=``;e[0].role===`system`&&(r+=`${e[0].content}
5
+ `})}return{systemInstruction:n.length>0&&!a?{parts:n}:void 0,contents:r}}function gr(e){return e.includes(`/`)?e:`models/${e}`}var _r=M.object({responseModalities:M.array(M.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:M.object({thinkingBudget:M.number().optional(),includeThoughts:M.boolean().optional()}).optional(),cachedContent:M.string().optional(),structuredOutputs:M.boolean().optional(),safetySettings:M.array(M.object({category:M.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:M.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:M.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:M.boolean().optional(),labels:M.record(M.string(),M.string()).optional()});function vr({tools:e,toolChoice:t,modelId:n}){e=e?.length?e:void 0;let r=[],i=n.includes(`gemini-2`),a=n.includes(`gemini-1.5-flash`)&&!n.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:r};let o=e.some(e=>e.type===`function`),s=e.some(e=>e.type===`provider-defined`);if(o&&s&&r.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.`}),s){let t={};return e.filter(e=>e.type===`provider-defined`).forEach(e=>{switch(e.id){case`google.google_search`:i?t.googleSearch={}:a?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:i?t.urlContext={}:r.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`:i?t.codeExecution={}:r.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:r.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:r}}let c=[];for(let t of e)switch(t.type){case`function`:c.push({name:t.name,description:t.description??``,parameters:pr(t.inputSchema)});break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:{functionDeclarations:c},toolConfig:void 0,toolWarnings:r};let l=t.type;switch(l){case`auto`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:r};case`none`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:r};case`required`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:r};case`tool`:return{tools:{functionDeclarations:c},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:r};default:throw new S({functionality:`tool choice type: ${l}`})}}function yr({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 br=M.object({web:M.object({uri:M.string(),title:M.string()}).nullish(),retrievedContext:M.object({uri:M.string(),title:M.string()}).nullish()}),xr=M.object({webSearchQueries:M.array(M.string()).nullish(),retrievalQueries:M.array(M.string()).nullish(),searchEntryPoint:M.object({renderedContent:M.string()}).nullish(),groundingChunks:M.array(br).nullish(),groundingSupports:M.array(M.object({segment:M.object({startIndex:M.number().nullish(),endIndex:M.number().nullish(),text:M.string().nullish()}),segment_text:M.string().nullish(),groundingChunkIndices:M.array(M.number()).nullish(),supportChunkIndices:M.array(M.number()).nullish(),confidenceScores:M.array(M.number()).nullish(),confidenceScore:M.array(M.number()).nullish()})).nullish(),retrievalMetadata:M.union([M.object({webDynamicRetrievalScore:M.number()}),M.object({})]).nullish()}),Sr=Yn({id:`google.google_search`,name:`google_search`,inputSchema:M.object({mode:M.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:M.number().default(1)})}),Cr=M.object({retrievedUrl:M.string(),urlRetrievalStatus:M.string()}),wr=M.object({urlMetadata:M.array(Cr)}),Tr=Yn({id:`google.url_context`,name:`url_context`,inputSchema:M.object({})}),Er=class{constructor(e,t){this.specificationVersion=`v2`,this.modelId=e,this.config=t,this.generateId=t.generateId??Cn}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 Wn({provider:`google`,providerOptions:f,schema:_r});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:_}=hr(e,{isGemmaModel:h}),{tools:v,toolConfig:y,toolWarnings:b}=vr({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)?pr(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=vn(await Zn(this.config.headers),e.headers),{responseHeaders:a,value:o,rawValue:s}=await Kn({url:`${this.config.baseURL}/${gr(this.modelId)}:generateContent`,headers:i,body:t,failedResponseHandler:cr,successfulResponseHandler:er(Nr),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=kr({groundingMetadata:c.groundingMetadata,generateId:this.config.generateId})??[];for(let e of p)l.push(e);return{content:l,finishReason:yr({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=vn(await Zn(this.config.headers),e.headers),{responseHeaders:a,value:o}=await Kn({url:`${this.config.baseURL}/${gr(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:cr,successfulResponseHandler:$n(Pr),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,_=kr({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=Or(o.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=Dr({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=yr({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 Dr({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 Or(e){return e?.filter(e=>`inlineData`in e)}function kr({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 Ar=M.object({parts:M.array(M.union([M.object({functionCall:M.object({name:M.string(),args:M.unknown()}),thoughtSignature:M.string().nullish()}),M.object({inlineData:M.object({mimeType:M.string(),data:M.string()})}),M.object({executableCode:M.object({language:M.string(),code:M.string()}).nullish(),codeExecutionResult:M.object({outcome:M.string(),output:M.string()}).nullish(),text:M.string().nullish(),thought:M.boolean().nullish(),thoughtSignature:M.string().nullish()})])).nullish()}),jr=M.object({category:M.string().nullish(),probability:M.string().nullish(),probabilityScore:M.number().nullish(),severity:M.string().nullish(),severityScore:M.number().nullish(),blocked:M.boolean().nullish()}),Mr=M.object({cachedContentTokenCount:M.number().nullish(),thoughtsTokenCount:M.number().nullish(),promptTokenCount:M.number().nullish(),candidatesTokenCount:M.number().nullish(),totalTokenCount:M.number().nullish()}),Nr=M.object({candidates:M.array(M.object({content:Ar.nullish().or(M.object({}).strict()),finishReason:M.string().nullish(),safetyRatings:M.array(jr).nullish(),groundingMetadata:xr.nullish(),urlContextMetadata:wr.nullish()})),usageMetadata:Mr.nullish(),promptFeedback:M.object({blockReason:M.string().nullish(),safetyRatings:M.array(jr).nullish()}).nullish()}),Pr=M.object({candidates:M.array(M.object({content:Ar.nullish(),finishReason:M.string().nullish(),safetyRatings:M.array(jr).nullish(),groundingMetadata:xr.nullish(),urlContextMetadata:wr.nullish()})).nullish(),usageMetadata:Mr.nullish(),promptFeedback:M.object({blockReason:M.string().nullish(),safetyRatings:M.array(jr).nullish()}).nullish()}),Fr=Xn({id:`google.code_execution`,name:`code_execution`,inputSchema:M.object({language:M.string().describe(`The programming language of the code.`),code:M.string().describe(`The code to be executed.`)}),outputSchema:M.object({outcome:M.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:M.string().describe(`The output from the code execution.`)})}),Ir={googleSearch:Sr,urlContext:Tr,codeExecution:Fr},Lr=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 Wn({provider:`google`,providerOptions:s,schema:zr}),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 Kn({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:vn(await Zn(this.config.headers),c),body:m,failedResponseHandler:cr,successfulResponseHandler:er(Rr),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}}}},Rr=M.object({predictions:M.array(M.object({bytesBase64Encoded:M.string()})).default([])}),zr=M.object({personGeneration:M.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:M.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function Br(e={}){let t=ar(e.baseURL)??`https://generativelanguage.googleapis.com/v1beta`,n=()=>Sn({"x-goog-api-key":On({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers},`ai-sdk/google/${or}`),r=r=>new Er(r,{provider:`google.generative-ai`,baseURL:t,headers:n,generateId:e.generateId??Cn,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 ur(r,{provider:`google.generative-ai`,baseURL:t,headers:n,fetch:e.fetch}),a=(r,i={})=>new Lr(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=Ir,o}Br();function Vr(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function Hr(e){return Object.fromEntries([...e.headers])}function Ur(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 Wr(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function Gr(e,...t){let n=Wr(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var Kr=(({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 p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function qr(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Jr=[`fetch failed`,`failed to fetch`];function Yr({error:e,url:t,requestBodyValues:n}){if(qr(e))return e;if(e instanceof TypeError&&Jr.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Xr=`3.0.10`;function Zr({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Qr({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 $r(e){let[t,n=``]=e.toLowerCase().split(`/`);return{mpeg:`mp3`,"x-wav":`wav`,opus:`ogg`,mp4:`m4a`,"x-m4a":`m4a`}[n]??n}var ei=/"__proto__"\s*:/,ti=/"constructor"\s*:/;function ni(e){let t=JSON.parse(e);return typeof t!=`object`||!t||ei.test(e)===!1&&ti.test(e)===!1?t:ri(t)}function ri(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 ii(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return ni(e)}finally{Error.stackTraceLimit=t}}var ai=Symbol.for(`vercel.ai.validator`);function oi(e){return{[ai]:!0,validate:e}}function si(e){return typeof e==`object`&&!!e&&ai in e&&e[ai]===!0&&`validate`in e}function ci(e){return si(e)?e:li(e)}function li(e){return oi(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function ui({value:e,schema:t}){let n=await di({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function di({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:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function fi({text:e,schema:t}){try{let n=ii(e);return t==null?n:ui({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function pi({text:e,schema:t}){try{let n=ii(e);return t==null?{success:!0,value:n,rawValue:n}:await di({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function mi(e){try{return ii(e),!0}catch{return!1}}function hi({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await pi({text:e,schema:t}))}}))}async function gi({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await di({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var _i=()=>globalThis.fetch,vi=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>bi({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),yi=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>bi({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),bi=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=_i()})=>{try{let c=await o(e,{method:`POST`,headers:Gr(t,`ai-sdk/provider-utils/${Xr}`,Ur()),body:n.content,signal:a}),l=Hr(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw qr(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(qr(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Yr({error:t,url:e,requestBodyValues:n.values})}};function xi(e){return e}function Si({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>xi({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Ci({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>xi({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}var wi=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=Hr(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await fi({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},Ti=e=>async({response:t})=>{let n=Hr(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:hi({stream:t.body,schema:e})}},Ei=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await pi({text:i,schema:e}),o=Hr(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},Di=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=Hr(e);if(!e.body)throw new s({message:`Response body is empty`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new s({message:`Failed to read response as array buffer`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},{btoa:Oi,atob:ki}=globalThis;function Ai(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=ki(t);return Uint8Array.from(n,e=>e.codePointAt(0))}function ji(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Oi(t)}function Mi(e){return e instanceof Uint8Array?ji(e):e}function Ni(e){return e?.replace(/\/$/,``)}var Pi=M.object({error:M.object({message:M.string(),type:M.string().nullish(),param:M.any().nullish(),code:M.union([M.string(),M.number()]).nullish()})}),Fi=wi({errorSchema:Pi,errorToMessage:e=>e.error.message});function Ii({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:i,content:a}of e)switch(i){case`system`:switch(t){case`system`:n.push({role:`system`,content:a});break;case`developer`:n.push({role:`developer`,content:a});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:if(a.length===1&&a[0].type===`text`){n.push({role:`user`,content:a[0].text});break}n.push({role:`user`,content:a.map((e,t)=>{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,${Mi(e.data)}`,detail:e.providerOptions?.openai?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new S({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:Mi(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:Mi(e.data),format:`mp3`}};default:throw new S({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new S({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-${t}.pdf`,file_data:`data:application/pdf;base64,${Mi(e.data)}`}}}else throw new S({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of a)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 a){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=i;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function Li({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 Ri(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 zi=M.object({logitBias:M.record(M.coerce.number(),M.number()).optional(),logprobs:M.union([M.boolean(),M.number()]).optional(),parallelToolCalls:M.boolean().optional(),user:M.string().optional(),reasoningEffort:M.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:M.number().optional(),store:M.boolean().optional(),metadata:M.record(M.string().max(64),M.string().max(512)).optional(),prediction:M.record(M.string(),M.any()).optional(),structuredOutputs:M.boolean().optional(),serviceTier:M.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:M.boolean().optional(),textVerbosity:M.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:M.string().optional(),safetyIdentifier:M.string().optional()});function Bi({tools:e,toolChoice:t,structuredOutputs: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`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:n?r:void 0}});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=t.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:i};default:throw new S({functionality:`tool choice type: ${o}`})}}var Vi=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 gi({provider:`openai`,providerOptions:f,schema:zi})??{},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:_}=Ii({prompt:e,systemMessageMode:Ji(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};Gi(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`&&!Ki(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`&&!qi(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}=Bi({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 vi({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:t,failedResponseHandler:Fi,successfulResponseHandler:Ei(Ui),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??Kr(),toolName:e.function.name,input:e.function.arguments});for(let e of o.message.annotations??[])s.push({type:`source`,sourceType:`url`,id:Kr(),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:Ri(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:{...Li(i),headers:r,body:a},warnings:n,providerMetadata:d}}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 vi({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:r,failedResponseHandler:Fi,successfulResponseHandler:Ti(Wi),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=[],s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0,u=!1,d={openai:{}};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){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}l&&(l=!1,n.enqueue({type:`response-metadata`,...Li(r)})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens??void 0,c.outputTokens=r.usage.completion_tokens??void 0,c.totalTokens=r.usage.total_tokens??void 0,c.reasoningTokens=r.usage.completion_tokens_details?.reasoning_tokens??void 0,c.cachedInputTokens=r.usage.prompt_tokens_details?.cached_tokens??void 0,r.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=r.usage.completion_tokens_details?.accepted_prediction_tokens),r.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=r.usage.completion_tokens_details?.rejected_prediction_tokens));let i=r.choices[0];if(i?.finish_reason!=null&&(s=Ri(i.finish_reason)),i?.logprobs?.content!=null&&(d.openai.logprobs=i.logprobs.content),i?.delta==null)return;let a=i.delta;if(a.content!=null&&(u||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:a.content})),a.tool_calls!=null)for(let e of a.tool_calls){let t=e.index;if(o[t]==null){if(e.type!==`function`)throw new h({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new h({data:e,message:`Expected 'id' to be a string.`});if(e.function?.name==null)throw new h({data:e,message:`Expected 'function.name' to be a string.`});n.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),o[t]={id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments??``},hasFinished:!1};let r=o[t];r.function?.name!=null&&r.function?.arguments!=null&&(r.function.arguments.length>0&&n.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments}),mi(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??Kr(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}let r=o[t];r.hasFinished||(e.function?.arguments!=null&&(r.function.arguments+=e.function?.arguments??``),n.enqueue({type:`tool-input-delta`,id:r.id,delta:e.function.arguments??``}),r.function?.name!=null&&r.function?.arguments!=null&&mi(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:r.id??Kr(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0))}if(a.annotations!=null)for(let e of a.annotations)n.enqueue({type:`source`,sourceType:`url`,id:Kr(),url:e.url,title:e.title})},flush(e){u&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,usage:c,...d==null?{}:{providerMetadata:d}})}})),request:{body:r},response:{headers:i}}}},Hi=M.object({prompt_tokens:M.number().nullish(),completion_tokens:M.number().nullish(),total_tokens:M.number().nullish(),prompt_tokens_details:M.object({cached_tokens:M.number().nullish()}).nullish(),completion_tokens_details:M.object({reasoning_tokens:M.number().nullish(),accepted_prediction_tokens:M.number().nullish(),rejected_prediction_tokens:M.number().nullish()}).nullish()}).nullish(),Ui=M.object({id:M.string().nullish(),created:M.number().nullish(),model:M.string().nullish(),choices:M.array(M.object({message:M.object({role:M.literal(`assistant`).nullish(),content:M.string().nullish(),tool_calls:M.array(M.object({id:M.string().nullish(),type:M.literal(`function`),function:M.object({name:M.string(),arguments:M.string()})})).nullish(),annotations:M.array(M.object({type:M.literal(`url_citation`),start_index:M.number(),end_index:M.number(),url:M.string(),title:M.string()})).nullish()}),index:M.number(),logprobs:M.object({content:M.array(M.object({token:M.string(),logprob:M.number(),top_logprobs:M.array(M.object({token:M.string(),logprob:M.number()}))})).nullish()}).nullish(),finish_reason:M.string().nullish()})),usage:Hi}),Wi=M.union([M.object({id:M.string().nullish(),created:M.number().nullish(),model:M.string().nullish(),choices:M.array(M.object({delta:M.object({role:M.enum([`assistant`]).nullish(),content:M.string().nullish(),tool_calls:M.array(M.object({index:M.number(),id:M.string().nullish(),type:M.literal(`function`).nullish(),function:M.object({name:M.string().nullish(),arguments:M.string().nullish()})})).nullish(),annotations:M.array(M.object({type:M.literal(`url_citation`),start_index:M.number(),end_index:M.number(),url:M.string(),title:M.string()})).nullish()}).nullish(),logprobs:M.object({content:M.array(M.object({token:M.string(),logprob:M.number(),top_logprobs:M.array(M.object({token:M.string(),logprob:M.number()}))})).nullish()}).nullish(),finish_reason:M.string().nullish(),index:M.number()})),usage:Hi}),Pi]);function Gi(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function Ki(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function qi(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 Ji(e){return Gi(e)?Yi[e]?.systemMessageMode??`developer`:`system`}var Yi={"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 Xi({prompt:e,user:t=`user`,assistant:n=`assistant`}){let r=``;e[0].role===`system`&&(r+=`${e[0].content}
6
6
 
7
7
  `,e=e.slice(1));for(let{role:i,content:a}of e)switch(i){case`system`:throw new m({message:"Unexpected system message in prompt: ${content}",prompt:e});case`user`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text}}).filter(Boolean).join(``);r+=`${t}:
8
8
  ${e}
@@ -12,78 +12,78 @@ ${e}
12
12
 
13
13
  `;break}case`tool`:throw new S({functionality:`tool messages`});default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return r+=`${n}:
14
14
  `,{prompt:r,stopSequences:[`
15
- ${t}:`]}}function Zi({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 Qi(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 $i=N.object({echo:N.boolean().optional(),logitBias:N.record(N.string(),N.number()).optional(),suffix:N.string().optional(),user:N.string().optional(),logprobs:N.union([N.boolean(),N.number()]).optional()}),ea=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 gi({provider:`openai`,providerOptions:f,schema:$i}),...await gi({provider:this.providerOptionsName,providerOptions:f,schema:$i})};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}=Xi({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 vi({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:t,failedResponseHandler:Fi,successfulResponseHandler:Ei(na),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:Qi(o.finish_reason),request:{body:t},response:{...Zi(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 vi({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:r,failedResponseHandler:Fi,successfulResponseHandler:Ti(ra),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`,...Zi(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=Qi(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}}}},ta=N.object({prompt_tokens:N.number(),completion_tokens:N.number(),total_tokens:N.number()}),na=N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({text:N.string(),finish_reason:N.string(),logprobs:N.object({tokens:N.array(N.string()),token_logprobs:N.array(N.number()),top_logprobs:N.array(N.record(N.string(),N.number())).nullish()}).nullish()})),usage:ta.nullish()}),ra=N.union([N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({text:N.string(),finish_reason:N.string().nullish(),index:N.number(),logprobs:N.object({tokens:N.array(N.string()),token_logprobs:N.array(N.number()),top_logprobs:N.array(N.record(N.string(),N.number())).nullish()}).nullish()})),usage:ta.nullish()}),Pi]),ia=N.object({dimensions:N.number().optional(),user:N.string().optional()}),aa=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:t,abortSignal:n,providerOptions:r}){if(e.length>this.maxEmbeddingsPerCall)throw new b({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let i=await gi({provider:`openai`,providerOptions:r,schema:ia})??{},{responseHeaders:a,value:o,rawValue:s}=await vi({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:Vr(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:i.dimensions,user:i.user},failedResponseHandler:Fi,successfulResponseHandler:Ei(oa),abortSignal:n,fetch:this.config.fetch});return{embeddings:o.data.map(e=>e.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,response:{headers:a,body:s}}}},oa=N.object({data:N.array(N.object({embedding:N.array(N.number())})),usage:N.object({prompt_tokens:N.number()}).nullish()}),sa={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},ca=new Set([`gpt-image-1`]),la=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return sa[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 vi({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Vr(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...ca.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:Fi,successfulResponseHandler:Ei(ua),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)}}}}},ua=N.object({data:N.array(N.object({b64_json:N.string(),revised_prompt:N.string().optional()}))}),da=N.object({code:N.string().nullish(),containerId:N.string()}),fa=N.object({outputs:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`logs`),logs:N.string()}),N.object({type:N.literal(`image`),url:N.string()})])).nullish()}),pa=N.object({container:N.union([N.string(),N.object({fileIds:N.array(N.string()).optional()})]).optional()}),ma=Ci({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:da,outputSchema:fa}),ha=(e={})=>ma(e),ga=N.object({key:N.string(),type:N.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:N.union([N.string(),N.number(),N.boolean()])}),_a=N.object({type:N.enum([`and`,`or`]),filters:N.array(N.union([ga,N.lazy(()=>_a)]))}),va=N.object({vectorStoreIds:N.array(N.string()),maxNumResults:N.number().optional(),ranking:N.object({ranker:N.string().optional(),scoreThreshold:N.number().optional()}).optional(),filters:N.union([ga,_a]).optional()}),ya=N.object({queries:N.array(N.string()),results:N.array(N.object({attributes:N.record(N.string(),N.unknown()),fileId:N.string(),filename:N.string(),score:N.number(),text:N.string()})).nullable()}),ba=Ci({id:`openai.file_search`,name:`file_search`,inputSchema:N.object({}),outputSchema:ya}),xa=N.object({background:N.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:N.enum([`low`,`high`]).optional(),inputImageMask:N.object({fileId:N.string().optional(),imageUrl:N.string().optional()}).optional(),model:N.string().optional(),moderation:N.enum([`auto`]).optional(),outputCompression:N.number().int().min(0).max(100).optional(),outputFormat:N.enum([`png`,`jpeg`,`webp`]).optional(),quality:N.enum([`auto`,`low`,`medium`,`high`]).optional(),size:N.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),Sa=N.object({result:N.string()}),Ca=Ci({id:`openai.image_generation`,name:`image_generation`,inputSchema:N.object({}),outputSchema:Sa}),wa=(e={})=>Ca(e),Ta=N.object({action:N.object({type:N.literal(`exec`),command:N.array(N.string()),timeoutMs:N.number().optional(),user:N.string().optional(),workingDirectory:N.string().optional(),env:N.record(N.string(),N.string()).optional()})}),Ea=N.object({output:N.string()}),Da=Ci({id:`openai.local_shell`,name:`local_shell`,inputSchema:Ta,outputSchema:Ea}),Oa=N.object({filters:N.object({allowedDomains:N.array(N.string()).optional()}).optional(),searchContextSize:N.enum([`low`,`medium`,`high`]).optional(),userLocation:N.object({type:N.literal(`approximate`),country:N.string().optional(),city:N.string().optional(),region:N.string().optional(),timezone:N.string().optional()}).optional()}),ka=Si({id:`openai.web_search`,name:`web_search`,inputSchema:N.object({action:N.discriminatedUnion(`type`,[N.object({type:N.literal(`search`),query:N.string().nullish()}),N.object({type:N.literal(`open_page`),url:N.string()}),N.object({type:N.literal(`find`),url:N.string(),pattern:N.string()})]).nullish()})}),Aa=(e={})=>ka(e),ja=N.object({searchContextSize:N.enum([`low`,`medium`,`high`]).optional(),userLocation:N.object({type:N.literal(`approximate`),country:N.string().optional(),city:N.string().optional(),region:N.string().optional(),timezone:N.string().optional()}).optional()}),Ma=Si({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:N.object({action:N.discriminatedUnion(`type`,[N.object({type:N.literal(`search`),query:N.string().nullish()}),N.object({type:N.literal(`open_page`),url:N.string()}),N.object({type:N.literal(`find`),url:N.string(),pattern:N.string()})]).nullish()})}),Na={codeInterpreter:ha,fileSearch:ba,imageGeneration:wa,localShell:Da,webSearchPreview:Ma,webSearch:Aa};function Pa(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Fa({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:i=!1}){let a=[],o=[];for(let{role:s,content:c}of e)switch(s){case`system`:switch(t){case`system`:a.push({role:`system`,content:c});break;case`developer`:a.push({role:`developer`,content:c});break;case`remove`:o.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:a.push({role:`user`,content:c.map((e,t)=>{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`&&Pa(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${Mi(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`&&Pa(e.data,n)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Mi(e.data)}`}};else throw new S({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of c)switch(n.type){case`text`:a.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(i&&n.toolName===`local_shell`){let e=Ta.parse(n.input);a.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}a.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`:r?a.push({type:`item_reference`,id:n.toolCallId}):o.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 gi({provider:`openai`,providerOptions:n.providerOptions,schema:Ia}),i=t?.itemId;if(i!=null){let s=e[i];if(r)s===void 0&&(a.push({type:`item_reference`,id:i}),e[i]={type:`reasoning`,id:i,summary:[]});else{let r=[];n.text.length>0?r.push({type:`summary_text`,text:n.text}):s!==void 0&&o.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),s===void 0?(e[i]={type:`reasoning`,id:i,encrypted_content:t?.reasoningEncryptedContent,summary:r},a.push(e[i])):s.summary.push(...r)}}else o.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 c){let t=e.output;if(i&&e.toolName===`local_shell`&&t.type===`json`){a.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:Ea.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}a.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=s;throw Error(`Unsupported role: ${e}`)}}return{input:a,warnings:o}}var Ia=N.object({itemId:N.string().nullish(),reasoningEncryptedContent:N.string().nullish()});function La({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 Ra({tools:e,toolChoice:t,strictJsonSchema: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)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=va.parse(t.args);i.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`:i.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=ja.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Oa.parse(t.args);i.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=pa.parse(t.args);i.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=xa.parse(t.args);i.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:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`image_generation`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:throw new S({functionality:`tool choice type: ${a}`})}}var za=N.object({type:N.literal(`web_search_call`),id:N.string(),status:N.string(),action:N.discriminatedUnion(`type`,[N.object({type:N.literal(`search`),query:N.string().nullish()}),N.object({type:N.literal(`open_page`),url:N.string()}),N.object({type:N.literal(`find`),url:N.string(),pattern:N.string()})]).nullish()}),Ba=N.object({type:N.literal(`file_search_call`),id:N.string(),queries:N.array(N.string()),results:N.array(N.object({attributes:N.record(N.string(),N.unknown()),file_id:N.string(),filename:N.string(),score:N.number(),text:N.string()})).nullish()}),Va=N.object({type:N.literal(`code_interpreter_call`),id:N.string(),code:N.string().nullable(),container_id:N.string(),outputs:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`logs`),logs:N.string()}),N.object({type:N.literal(`image`),url:N.string()})])).nullable()}),Ha=N.object({type:N.literal(`local_shell_call`),id:N.string(),call_id:N.string(),action:N.object({type:N.literal(`exec`),command:N.array(N.string()),timeout_ms:N.number().optional(),user:N.string().optional(),working_directory:N.string().optional(),env:N.record(N.string(),N.string()).optional()})}),Ua=N.object({type:N.literal(`image_generation_call`),id:N.string(),result:N.string()}),Wa=20,Ga=N.array(N.object({token:N.string(),logprob:N.number(),top_logprobs:N.array(N.object({token:N.string(),logprob:N.number()}))})),Ka=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=So(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 gi({provider:`openai`,providerOptions:l,schema:Co}),{input:g,warnings:_}=await Fa({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?Wa: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}=Ra({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:T,tool_choice:E},warnings:[...p,...D]}}async doGenerate(e){var t,n;let{args:r,warnings:i,webSearchToolName:a}=await this.getArgs(e),o=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:c,value:l,rawValue:u}=await vi({url:o,headers:Vr(this.config.headers(),e.headers),body:r,failedResponseHandler:Fi,successfulResponseHandler:Ei(N.object({id:N.string(),created_at:N.number(),error:N.object({code:N.string(),message:N.string()}).nullish(),model:N.string(),output:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`message`),role:N.literal(`assistant`),id:N.string(),content:N.array(N.object({type:N.literal(`output_text`),text:N.string(),logprobs:Ga.nullish(),annotations:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`url_citation`),start_index:N.number(),end_index:N.number(),url:N.string(),title:N.string()}),N.object({type:N.literal(`file_citation`),file_id:N.string(),filename:N.string().nullish(),index:N.number().nullish(),start_index:N.number().nullish(),end_index:N.number().nullish(),quote:N.string().nullish()}),N.object({type:N.literal(`container_file_citation`)})]))}))}),za,Ba,Va,Ua,Ha,N.object({type:N.literal(`function_call`),call_id:N.string(),name:N.string(),arguments:N.string(),id:N.string()}),N.object({type:N.literal(`computer_call`),id:N.string(),status:N.string().optional()}),N.object({type:N.literal(`reasoning`),id:N.string(),encrypted_content:N.string().nullish(),summary:N.array(N.object({type:N.literal(`summary_text`),text:N.string()}))})])),service_tier:N.string().nullish(),incomplete_details:N.object({reason:N.string()}).nullish(),usage:qa})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(l.error)throw new s({message:l.error.message,url:o,requestBodyValues:r,statusCode:400,responseHeaders:c,responseBody:u,isRetryable:!1});let d=[],f=[],p=!1;for(let r of l.output)switch(r.type){case`reasoning`:r.summary.length===0&&r.summary.push({type:`summary_text`,text:``});for(let e of r.summary)d.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:r.id,reasoningEncryptedContent:r.encrypted_content??null}}});break;case`image_generation_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`image_generation`,result:{result:r.result},providerExecuted:!0});break;case`local_shell_call`:d.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 i of r.content){e.providerOptions?.openai?.logprobs&&i.logprobs&&f.push(i.logprobs),d.push({type:`text`,text:i.text,providerMetadata:{openai:{itemId:r.id}}});for(let e of i.annotations)e.type===`url_citation`?d.push({type:`source`,sourceType:`url`,id:(t=this.config).generateId?.call(t)??Kr(),url:e.url,title:e.title}):e.type===`file_citation`&&d.push({type:`source`,sourceType:`document`,id:(n=this.config).generateId?.call(n)??Kr(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:p=!0,d.push({type:`tool-call`,toolCallId:r.call_id,toolName:r.name,input:r.arguments,providerMetadata:{openai:{itemId:r.id}}});break;case`web_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:a??`web_search`,input:JSON.stringify({action:r.action}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:a??`web_search`,result:{status:r.status},providerExecuted:!0});break;case`computer_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`computer_use`,input:``,providerExecuted:!0}),d.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`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),d.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`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`code_interpreter`,input:JSON.stringify({code:r.code,containerId:r.container_id}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`code_interpreter`,result:{outputs:r.outputs},providerExecuted:!0});break}let m={openai:{responseId:l.id}};return f.length>0&&(m.openai.logprobs=f),typeof l.service_tier==`string`&&(m.openai.serviceTier=l.service_tier),{content:d,finishReason:La({finishReason:l.incomplete_details?.reason,hasFunctionCall:p}),usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,reasoningTokens:l.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:l.usage.input_tokens_details?.cached_tokens??void 0},request:{body:r},response:{id:l.id,timestamp:new Date(l.created_at*1e3),modelId:l.model,headers:c,body:u},providerMetadata:m,warnings:i}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await vi({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Fi,successfulResponseHandler:Ti(oo),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(go(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}}}):_o(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(co(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(lo(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(po(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(mo(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(ho(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 fo(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})):so(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):yo(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}}})):bo(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):uo(g)?(s=La({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)):vo(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??Kr(),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)??Kr(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):xo(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}}}},qa=N.object({input_tokens:N.number(),input_tokens_details:N.object({cached_tokens:N.number().nullish()}).nullish(),output_tokens:N.number(),output_tokens_details:N.object({reasoning_tokens:N.number().nullish()}).nullish()}),Ja=N.object({type:N.literal(`response.output_text.delta`),item_id:N.string(),delta:N.string(),logprobs:Ga.nullish()}),Ya=N.object({type:N.literal(`error`),code:N.string(),message:N.string(),param:N.string().nullish(),sequence_number:N.number()}),Xa=N.object({type:N.enum([`response.completed`,`response.incomplete`]),response:N.object({incomplete_details:N.object({reason:N.string()}).nullish(),usage:qa,service_tier:N.string().nullish()})}),Za=N.object({type:N.literal(`response.created`),response:N.object({id:N.string(),created_at:N.number(),model:N.string(),service_tier:N.string().nullish()})}),Qa=N.object({type:N.literal(`response.output_item.added`),output_index:N.number(),item:N.discriminatedUnion(`type`,[N.object({type:N.literal(`message`),id:N.string()}),N.object({type:N.literal(`reasoning`),id:N.string(),encrypted_content:N.string().nullish()}),N.object({type:N.literal(`function_call`),id:N.string(),call_id:N.string(),name:N.string(),arguments:N.string()}),N.object({type:N.literal(`web_search_call`),id:N.string(),status:N.string(),action:N.object({type:N.literal(`search`),query:N.string().optional()}).nullish()}),N.object({type:N.literal(`computer_call`),id:N.string(),status:N.string()}),N.object({type:N.literal(`file_search_call`),id:N.string()}),N.object({type:N.literal(`image_generation_call`),id:N.string()}),N.object({type:N.literal(`code_interpreter_call`),id:N.string(),container_id:N.string(),code:N.string().nullable(),outputs:N.array(N.discriminatedUnion(`type`,[N.object({type:N.literal(`logs`),logs:N.string()}),N.object({type:N.literal(`image`),url:N.string()})])).nullable(),status:N.string()})])}),$a=N.object({type:N.literal(`response.output_item.done`),output_index:N.number(),item:N.discriminatedUnion(`type`,[N.object({type:N.literal(`message`),id:N.string()}),N.object({type:N.literal(`reasoning`),id:N.string(),encrypted_content:N.string().nullish()}),N.object({type:N.literal(`function_call`),id:N.string(),call_id:N.string(),name:N.string(),arguments:N.string(),status:N.literal(`completed`)}),Va,Ua,za,Ba,Ha,N.object({type:N.literal(`computer_call`),id:N.string(),status:N.literal(`completed`)})])}),eo=N.object({type:N.literal(`response.function_call_arguments.delta`),item_id:N.string(),output_index:N.number(),delta:N.string()}),to=N.object({type:N.literal(`response.code_interpreter_call_code.delta`),item_id:N.string(),output_index:N.number(),delta:N.string()}),no=N.object({type:N.literal(`response.code_interpreter_call_code.done`),item_id:N.string(),output_index:N.number(),code:N.string()}),ro=N.object({type:N.literal(`response.output_text.annotation.added`),annotation:N.discriminatedUnion(`type`,[N.object({type:N.literal(`url_citation`),url:N.string(),title:N.string()}),N.object({type:N.literal(`file_citation`),file_id:N.string(),filename:N.string().nullish(),index:N.number().nullish(),start_index:N.number().nullish(),end_index:N.number().nullish(),quote:N.string().nullish()})])}),io=N.object({type:N.literal(`response.reasoning_summary_part.added`),item_id:N.string(),summary_index:N.number()}),ao=N.object({type:N.literal(`response.reasoning_summary_text.delta`),item_id:N.string(),summary_index:N.number(),delta:N.string()}),oo=N.union([Ja,Xa,Za,Qa,$a,eo,to,no,ro,io,ao,Ya,N.object({type:N.string()}).loose()]);function so(e){return e.type===`response.output_text.delta`}function co(e){return e.type===`response.output_item.done`}function lo(e){return co(e)&&e.item.type===`reasoning`}function uo(e){return e.type===`response.completed`||e.type===`response.incomplete`}function fo(e){return e.type===`response.created`}function po(e){return e.type===`response.function_call_arguments.delta`}function mo(e){return e.type===`response.code_interpreter_call_code.delta`}function ho(e){return e.type===`response.code_interpreter_call_code.done`}function go(e){return e.type===`response.output_item.added`}function _o(e){return go(e)&&e.item.type===`reasoning`}function vo(e){return e.type===`response.output_text.annotation.added`}function yo(e){return e.type===`response.reasoning_summary_part.added`}function bo(e){return e.type===`response.reasoning_summary_text.delta`}function xo(e){return e.type===`error`}function So(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 Co=N.object({include:N.array(N.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:N.string().nullish(),logprobs:N.union([N.boolean(),N.number().min(1).max(Wa)]).optional(),maxToolCalls:N.number().nullish(),metadata:N.any().nullish(),parallelToolCalls:N.boolean().nullish(),previousResponseId:N.string().nullish(),promptCacheKey:N.string().nullish(),reasoningEffort:N.string().nullish(),reasoningSummary:N.string().nullish(),safetyIdentifier:N.string().nullish(),serviceTier:N.enum([`auto`,`flex`,`priority`]).nullish(),store:N.boolean().nullish(),strictJsonSchema:N.boolean().nullish(),textVerbosity:N.enum([`low`,`medium`,`high`]).nullish(),user:N.string().nullish()}),wo=N.object({instructions:N.string().nullish(),speed:N.number().min(.25).max(4).default(1).nullish()}),To=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 gi({provider:`openai`,providerOptions:o,schema:wo}),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 vi({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:r,failedResponseHandler:Fi,successfulResponseHandler:Di(),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}}}},Eo=N.object({include:N.array(N.string()).optional(),language:N.string().optional(),prompt:N.string().optional(),temperature:N.number().min(0).max(1).default(0).optional(),timestampGranularities:N.array(N.enum([`word`,`segment`])).default([`segment`]).optional()}),Do={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`},Oo=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 gi({provider:`openai`,providerOptions:n,schema:Eo}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([Ai(e)]);a.append(`model`,this.modelId);let s=$r(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 yi({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),formData:r,failedResponseHandler:Fi,successfulResponseHandler:Ei(ko),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in Do?Do[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}}}},ko=N.object({text:N.string(),language:N.string().nullish(),duration:N.number().nullish(),words:N.array(N.object({word:N.string(),start:N.number(),end:N.number()})).nullish(),segments:N.array(N.object({id:N.number(),seek:N.number(),start:N.number(),end:N.number(),text:N.string(),tokens:N.array(N.number()),temperature:N.number(),avg_logprob:N.number(),compression_ratio:N.number(),no_speech_prob:N.number()})).nullish()}),Ao=`2.0.42`;function jo(e={}){let t=Ni(Qr({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>Gr({Authorization:`Bearer ${Zr({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Ao}`),i=i=>new Vi(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new ea(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new aa(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new la(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new Oo(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new To(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 Ka(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=Na,f}jo();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)}(({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 p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function Lo(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Ro=[`fetch failed`,`failed to fetch`];function zo({error:e,url:t,requestBodyValues:n}){if(Lo(e))return e;if(e instanceof TypeError&&Ro.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Bo=`3.0.10`,Vo=/"__proto__"\s*:/,Ho=/"constructor"\s*:/;function Uo(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Vo.test(e)===!1&&Ho.test(e)===!1?t:Wo(t)}function Wo(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 Go(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Uo(e)}finally{Error.stackTraceLimit=t}}var Ko=Symbol.for(`vercel.ai.validator`);function qo(e){return{[Ko]:!0,validate:e}}function Jo(e){return typeof e==`object`&&!!e&&Ko in e&&e[Ko]===!0&&`validate`in e}function Yo(e){return Jo(e)?e:Xo(e)}function Xo(e){return qo(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function Zo({value:e,schema:t}){let n=await Qo({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Qo({value:e,schema:t}){let n=Yo(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:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function $o({text:e,schema:t}){try{let n=Go(e);return t==null?n:Zo({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function es({text:e,schema:t}){try{let n=Go(e);return t==null?{success:!0,value:n,rawValue:n}:await Qo({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}var ts=()=>globalThis.fetch,ns=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>rs({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),rs=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=ts()})=>{try{let c=await o(e,{method:`POST`,headers:Io(t,`ai-sdk/provider-utils/${Bo}`,Po()),body:n.content,signal:a}),l=No(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw Lo(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Lo(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw zo({error:t,url:e,requestBodyValues:n.values})}},os=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=No(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await $o({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},ss=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await es({text:i,schema:e}),o=No(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:cs,atob:ls}=globalThis;N.object({user:N.string().optional(),reasoningEffort:N.string().optional()});var us={errorSchema:N.object({error:N.object({message:N.string(),type:N.string().nullish(),param:N.any().nullish(),code:N.union([N.string(),N.number()]).nullish()})}),errorToMessage:e=>e.error.message},ds=N.object({prompt_tokens:N.number().nullish(),completion_tokens:N.number().nullish(),total_tokens:N.number().nullish(),prompt_tokens_details:N.object({cached_tokens:N.number().nullish()}).nullish(),completion_tokens_details:N.object({reasoning_tokens:N.number().nullish(),accepted_prediction_tokens:N.number().nullish(),rejected_prediction_tokens:N.number().nullish()}).nullish()}).nullish();N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({message:N.object({role:N.literal(`assistant`).nullish(),content:N.string().nullish(),reasoning_content:N.string().nullish(),reasoning:N.string().nullish(),tool_calls:N.array(N.object({id:N.string().nullish(),function:N.object({name:N.string(),arguments:N.string()})})).nullish()}),finish_reason:N.string().nullish()})),usage:ds}),N.object({echo:N.boolean().optional(),logitBias:N.record(N.string(),N.number()).optional(),suffix:N.string().optional(),user:N.string().optional()});var fs=N.object({prompt_tokens:N.number(),completion_tokens:N.number(),total_tokens:N.number()});N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({text:N.string(),finish_reason:N.string()})),usage:fs.nullish()}),N.object({dimensions:N.number().optional(),user:N.string().optional()}),N.object({data:N.array(N.object({embedding:N.array(N.number())})),usage:N.object({prompt_tokens:N.number()}).nullish(),providerMetadata:N.record(N.string(),N.record(N.string(),N.any())).optional()});var ps=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 ns({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Mo(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:os(this.config.errorStructure??us),successfulResponseHandler:ss(ms),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}}}},ms=N.object({data:N.array(N.object({b64_json:N.string()}))});function hs(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function gs(e){return Object.fromEntries([...e.headers])}function _s(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 vs(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function ys(e,...t){let n=vs(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var bs=(({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 p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function xs(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Ss=[`fetch failed`,`failed to fetch`];function Cs({error:e,url:t,requestBodyValues:n}){if(xs(e))return e;if(e instanceof TypeError&&Ss.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var ws=`3.0.10`;function Ts({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Es=/"__proto__"\s*:/,Ds=/"constructor"\s*:/;function Os(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Es.test(e)===!1&&Ds.test(e)===!1?t:ks(t)}function ks(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 As(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Os(e)}finally{Error.stackTraceLimit=t}}var js=Symbol.for(`vercel.ai.validator`);function Ms(e){return{[js]:!0,validate:e}}function Ns(e){return typeof e==`object`&&!!e&&js in e&&e[js]===!0&&`validate`in e}function Ps(e){return Ns(e)?e:Fs(e)}function Fs(e){return Ms(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function Is({value:e,schema:t}){let n=await Ls({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Ls({value:e,schema:t}){let n=Ps(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:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Rs({text:e,schema:t}){try{let n=As(e);return t==null?n:Is({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function zs({text:e,schema:t}){try{let n=As(e);return t==null?{success:!0,value:n,rawValue:n}:await Ls({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function Bs({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await zs({text:e,schema:t}))}}))}async function Vs({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Ls({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Hs=()=>globalThis.fetch,Us=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Ws({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Ws=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Hs()})=>{try{let c=await o(e,{method:`POST`,headers:ys(t,`ai-sdk/provider-utils/${ws}`,_s()),body:n.content,signal:a}),l=gs(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw xs(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(xs(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Cs({error:t,url:e,requestBodyValues:n.values})}},Gs=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=gs(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Rs({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},Ks=e=>async({response:t})=>{let n=gs(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:Bs({stream:t.body,schema:e})}},qs=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await zs({text:i,schema:e}),o=gs(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:Js,atob:Ys}=globalThis;function Xs(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Js(t)}function Zs(e){return e instanceof Uint8Array?Xs(e):e}function Qs(e){return e?.replace(/\/$/,``)}function $s(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.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,${Zs(e.data)}`}}}else throw new S({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function ec({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 tc(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 nc=N.object({type:N.literal(`web`),country:N.string().length(2).optional(),excludedWebsites:N.array(N.string()).max(5).optional(),allowedWebsites:N.array(N.string()).max(5).optional(),safeSearch:N.boolean().optional()}),rc=N.object({type:N.literal(`x`),excludedXHandles:N.array(N.string()).optional(),includedXHandles:N.array(N.string()).optional(),postFavoriteCount:N.number().int().optional(),postViewCount:N.number().int().optional(),xHandles:N.array(N.string()).optional()}),ic=N.object({type:N.literal(`news`),country:N.string().length(2).optional(),excludedWebsites:N.array(N.string()).max(5).optional(),safeSearch:N.boolean().optional()}),ac=N.object({type:N.literal(`rss`),links:N.array(N.string().url()).max(1)}),oc=N.discriminatedUnion(`type`,[nc,rc,ic,ac]),sc=N.object({reasoningEffort:N.enum([`low`,`high`]).optional(),searchParameters:N.object({mode:N.enum([`off`,`auto`,`on`]),returnCitations:N.boolean().optional(),fromDate:N.string().optional(),toDate:N.string().optional(),maxSearchResults:N.number().min(1).max(50).optional(),sources:N.array(oc).optional()}).optional()}),cc=N.object({error:N.object({message:N.string(),type:N.string().nullish(),param:N.any().nullish(),code:N.union([N.string(),N.number()]).nullish()})}),lc=Gs({errorSchema:cc,errorToMessage:e=>e.error.message});function uc({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new S({functionality:`tool choice type: ${i}`})}}var dc=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 Vs({provider:`xai`,providerOptions:u,schema:sc})??{};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}=$s(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=uc({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 Us({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:hs(this.config.headers(),e.headers),body:t,failedResponseHandler:lc,successfulResponseHandler:qs(pc),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:tc(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:{...ec(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 Us({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:hs(this.config.headers(),e.headers),body:r,failedResponseHandler:lc,successfulResponseHandler:Ks(mc),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`,...ec(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=tc(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}}}},fc=N.object({prompt_tokens:N.number(),completion_tokens:N.number(),total_tokens:N.number(),completion_tokens_details:N.object({reasoning_tokens:N.number().nullish()}).nullish()}),pc=N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({message:N.object({role:N.literal(`assistant`),content:N.string().nullish(),reasoning_content:N.string().nullish(),tool_calls:N.array(N.object({id:N.string(),type:N.literal(`function`),function:N.object({name:N.string(),arguments:N.string()})})).nullish()}),index:N.number(),finish_reason:N.string().nullish()})),object:N.literal(`chat.completion`),usage:fc,citations:N.array(N.string().url()).nullish()}),mc=N.object({id:N.string().nullish(),created:N.number().nullish(),model:N.string().nullish(),choices:N.array(N.object({delta:N.object({role:N.enum([`assistant`]).optional(),content:N.string().nullish(),reasoning_content:N.string().nullish(),tool_calls:N.array(N.object({id:N.string(),type:N.literal(`function`),function:N.object({name:N.string(),arguments:N.string()})})).nullish()}),finish_reason:N.string().nullish(),index:N.number()})),usage:fc.nullish(),citations:N.array(N.string().url()).nullish()}),hc=`2.0.23`,gc={errorSchema:cc,errorToMessage:e=>e.error.message};function _c(e={}){let t=Qs(e.baseURL??`https://api.x.ai/v1`),n=()=>ys({Authorization:`Bearer ${Ts({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${hc}`),r=r=>new dc(r,{provider:`xai.chat`,baseURL:t,headers:n,generateId:bs,fetch:e.fetch}),i=r=>new ps(r,{provider:`xai.image`,url:({path:e})=>`${t}${e}`,headers:n,fetch:e.fetch,errorStructure:gc}),a=e=>r(e);return a.languageModel=r,a.chat=r,a.textEmbeddingModel=e=>{throw new v({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=i,a.image=i,a}_c();function vc(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(y);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new d).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 n=e=>ye({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(jo({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(jo({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(_n({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(Br({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(_c({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}function yc(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var bc=class{_lockP=null;async lock(){let e=this._lockP,{promise:t,resolve:n}=yc();return this._lockP=t,await e,n}withLock(e){return Sc(this.lock(),e)}},xc=class{_lock=new bc;_writeP=null;_readP=[];read(){return this._lock.withLock(async()=>{await this._writeP;let{promise:e,resolve:t}=yc();return this._readP.push(e),t})}withRead(e){return Sc(this.read(),e)}async write(){return await this._lock.withLock(async()=>{await this._writeP,await Promise.all(this._readP);let{promise:e,resolve:t}=yc();return this._writeP=e,this._readP=[],t})}withWrite(e){return Sc(this.write(),e)}};async function Sc(e,t){let n=await e;try{return await t()}finally{n()}}var Cc=class{constructor(e){this.onRelease=e}[Symbol.dispose](){this.onRelease()}},wc=class{constructor(e){this.onRelease=e}[Symbol.dispose](){this.onRelease()}},Tc=class{_lock=new xc;async read(){let e=await this._lock.read();return new Cc(e)}async write(){let e=await this._lock.write();return new wc(e)}},Ec=class{baseUrl;client;constructor(e){this.client=T(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),vc(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 Dc(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}function Oc(e){let[t,n]=G(void 0),[r,i]=G([]),[a,o]=G(void 0),[s,l]=G(e.buildResult),[u,d]=G(e.env),[f,p]=G(e.apiServerUrl),[m,h]=G(void 0);return U(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),U(()=>{if(!s||`error`in s){n(void 0),i([]),o(void 0),h(void 0);return}let e=new AbortController,t=!1;o(void 0),n(void 0),h(void 0);let r;return(async()=>{let t=await kc(),a=Ce(`node`,[`--no-deprecation`,s.entry],{stdio:`pipe`,env:{...process.env,...u,[c]:f,PORT:t.toString(),HOST:`127.0.0.1`},detached:!1}),o=()=>{try{a.kill()}catch{}};process.once(`exit`,o),process.once(`SIGINT`,o),process.once(`SIGTERM`,o),process.once(`uncaughtException`,o),e.signal.addEventListener(`abort`,()=>{process.off(`exit`,o),process.off(`SIGINT`,o),process.off(`SIGTERM`,o),process.off(`uncaughtException`,o),o()});let l=!1;a.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!l&&t.startsWith(`Agent server listening on`)||(l||console.log(`stdout: ${t}`),t.length&&i(e=>[...e,{level:`log`,message:t}]))}),a.stderr.on(`data`,e=>{l||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&i(e=>[...e,{level:`error`,message:t}])}),a.on(`error`,t=>{e.abort(t)}),a.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let d=new Ec({baseUrl:`http://127.0.0.1:${t}`}),p=new Tc;for(r=p;!e.signal.aborted;){try{await d.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;l=!0;let m=await d.capabilities();h(m),n({client:d,lock:p})})().catch(e=>{t||o(e instanceof Error?e:Error(String(e)))}),()=>{t=!0,(async()=>{try{var t=Dc();t.u(await r?.write()),e.abort()}catch(e){t.e=e}finally{t.d()}})()}},[s,u,f]),Te(()=>({agent:t,logs:r,error:a,capabilities:m}),[t,r,a,m])}async function kc(){let e=le();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var Ac=Object.getOwnPropertyNames,jc=(e,t)=>function(){return t||(0,e[Ac(e)[0]])((t={exports:{}}).exports,t),t.exports},Y=j(import.meta.url);q.object({email:q.string().email(),password:q.string().min(8)}),q.object({email:q.string().email(),code:q.string()}),q.object({email:q.string().email(),password:q.string().min(8)});var Mc=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))}})}},Nc=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 Pc(e){}function Fc(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Pc,onError:n=Pc,onRetry:r=Pc,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Ic(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
15
+ ${t}:`]}}function Zi({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 Qi(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 $i=M.object({echo:M.boolean().optional(),logitBias:M.record(M.string(),M.number()).optional(),suffix:M.string().optional(),user:M.string().optional(),logprobs:M.union([M.boolean(),M.number()]).optional()}),ea=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 gi({provider:`openai`,providerOptions:f,schema:$i}),...await gi({provider:this.providerOptionsName,providerOptions:f,schema:$i})};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}=Xi({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 vi({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:t,failedResponseHandler:Fi,successfulResponseHandler:Ei(na),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:Qi(o.finish_reason),request:{body:t},response:{...Zi(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 vi({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:r,failedResponseHandler:Fi,successfulResponseHandler:Ti(ra),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`,...Zi(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=Qi(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}}}},ta=M.object({prompt_tokens:M.number(),completion_tokens:M.number(),total_tokens:M.number()}),na=M.object({id:M.string().nullish(),created:M.number().nullish(),model:M.string().nullish(),choices:M.array(M.object({text:M.string(),finish_reason:M.string(),logprobs:M.object({tokens:M.array(M.string()),token_logprobs:M.array(M.number()),top_logprobs:M.array(M.record(M.string(),M.number())).nullish()}).nullish()})),usage:ta.nullish()}),ra=M.union([M.object({id:M.string().nullish(),created:M.number().nullish(),model:M.string().nullish(),choices:M.array(M.object({text:M.string(),finish_reason:M.string().nullish(),index:M.number(),logprobs:M.object({tokens:M.array(M.string()),token_logprobs:M.array(M.number()),top_logprobs:M.array(M.record(M.string(),M.number())).nullish()}).nullish()})),usage:ta.nullish()}),Pi]),ia=M.object({dimensions:M.number().optional(),user:M.string().optional()}),aa=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:t,abortSignal:n,providerOptions:r}){if(e.length>this.maxEmbeddingsPerCall)throw new b({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let i=await gi({provider:`openai`,providerOptions:r,schema:ia})??{},{responseHeaders:a,value:o,rawValue:s}=await vi({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:Vr(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:i.dimensions,user:i.user},failedResponseHandler:Fi,successfulResponseHandler:Ei(oa),abortSignal:n,fetch:this.config.fetch});return{embeddings:o.data.map(e=>e.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,response:{headers:a,body:s}}}},oa=M.object({data:M.array(M.object({embedding:M.array(M.number())})),usage:M.object({prompt_tokens:M.number()}).nullish()}),sa={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},ca=new Set([`gpt-image-1`]),la=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){return sa[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 vi({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Vr(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},...ca.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:Fi,successfulResponseHandler:Ei(ua),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)}}}}},ua=M.object({data:M.array(M.object({b64_json:M.string(),revised_prompt:M.string().optional()}))}),da=M.object({code:M.string().nullish(),containerId:M.string()}),fa=M.object({outputs:M.array(M.discriminatedUnion(`type`,[M.object({type:M.literal(`logs`),logs:M.string()}),M.object({type:M.literal(`image`),url:M.string()})])).nullish()}),pa=M.object({container:M.union([M.string(),M.object({fileIds:M.array(M.string()).optional()})]).optional()}),ma=Ci({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:da,outputSchema:fa}),ha=(e={})=>ma(e),ga=M.object({key:M.string(),type:M.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:M.union([M.string(),M.number(),M.boolean()])}),_a=M.object({type:M.enum([`and`,`or`]),filters:M.array(M.union([ga,M.lazy(()=>_a)]))}),va=M.object({vectorStoreIds:M.array(M.string()),maxNumResults:M.number().optional(),ranking:M.object({ranker:M.string().optional(),scoreThreshold:M.number().optional()}).optional(),filters:M.union([ga,_a]).optional()}),ya=M.object({queries:M.array(M.string()),results:M.array(M.object({attributes:M.record(M.string(),M.unknown()),fileId:M.string(),filename:M.string(),score:M.number(),text:M.string()})).nullable()}),ba=Ci({id:`openai.file_search`,name:`file_search`,inputSchema:M.object({}),outputSchema:ya}),xa=M.object({background:M.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:M.enum([`low`,`high`]).optional(),inputImageMask:M.object({fileId:M.string().optional(),imageUrl:M.string().optional()}).optional(),model:M.string().optional(),moderation:M.enum([`auto`]).optional(),outputCompression:M.number().int().min(0).max(100).optional(),outputFormat:M.enum([`png`,`jpeg`,`webp`]).optional(),quality:M.enum([`auto`,`low`,`medium`,`high`]).optional(),size:M.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict(),Sa=M.object({result:M.string()}),Ca=Ci({id:`openai.image_generation`,name:`image_generation`,inputSchema:M.object({}),outputSchema:Sa}),wa=(e={})=>Ca(e),Ta=M.object({action:M.object({type:M.literal(`exec`),command:M.array(M.string()),timeoutMs:M.number().optional(),user:M.string().optional(),workingDirectory:M.string().optional(),env:M.record(M.string(),M.string()).optional()})}),Ea=M.object({output:M.string()}),Da=Ci({id:`openai.local_shell`,name:`local_shell`,inputSchema:Ta,outputSchema:Ea}),Oa=M.object({filters:M.object({allowedDomains:M.array(M.string()).optional()}).optional(),searchContextSize:M.enum([`low`,`medium`,`high`]).optional(),userLocation:M.object({type:M.literal(`approximate`),country:M.string().optional(),city:M.string().optional(),region:M.string().optional(),timezone:M.string().optional()}).optional()}),ka=Si({id:`openai.web_search`,name:`web_search`,inputSchema:M.object({action:M.discriminatedUnion(`type`,[M.object({type:M.literal(`search`),query:M.string().nullish()}),M.object({type:M.literal(`open_page`),url:M.string()}),M.object({type:M.literal(`find`),url:M.string(),pattern:M.string()})]).nullish()})}),Aa=(e={})=>ka(e),ja=M.object({searchContextSize:M.enum([`low`,`medium`,`high`]).optional(),userLocation:M.object({type:M.literal(`approximate`),country:M.string().optional(),city:M.string().optional(),region:M.string().optional(),timezone:M.string().optional()}).optional()}),Ma=Si({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:M.object({action:M.discriminatedUnion(`type`,[M.object({type:M.literal(`search`),query:M.string().nullish()}),M.object({type:M.literal(`open_page`),url:M.string()}),M.object({type:M.literal(`find`),url:M.string(),pattern:M.string()})]).nullish()})}),Na={codeInterpreter:ha,fileSearch:ba,imageGeneration:wa,localShell:Da,webSearchPreview:Ma,webSearch:Aa};function Pa(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Fa({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:i=!1}){let a=[],o=[];for(let{role:s,content:c}of e)switch(s){case`system`:switch(t){case`system`:a.push({role:`system`,content:c});break;case`developer`:a.push({role:`developer`,content:c});break;case`remove`:o.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:a.push({role:`user`,content:c.map((e,t)=>{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`&&Pa(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${Mi(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`&&Pa(e.data,n)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Mi(e.data)}`}};else throw new S({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={},t={};for(let n of c)switch(n.type){case`text`:a.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(i&&n.toolName===`local_shell`){let e=Ta.parse(n.input);a.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}a.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`:r?a.push({type:`item_reference`,id:n.toolCallId}):o.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 gi({provider:`openai`,providerOptions:n.providerOptions,schema:Ia}),i=t?.itemId;if(i!=null){let s=e[i];if(r)s===void 0&&(a.push({type:`item_reference`,id:i}),e[i]={type:`reasoning`,id:i,summary:[]});else{let r=[];n.text.length>0?r.push({type:`summary_text`,text:n.text}):s!==void 0&&o.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),s===void 0?(e[i]={type:`reasoning`,id:i,encrypted_content:t?.reasoningEncryptedContent,summary:r},a.push(e[i])):s.summary.push(...r)}}else o.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 c){let t=e.output;if(i&&e.toolName===`local_shell`&&t.type===`json`){a.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:Ea.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}a.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=s;throw Error(`Unsupported role: ${e}`)}}return{input:a,warnings:o}}var Ia=M.object({itemId:M.string().nullish(),reasoningEncryptedContent:M.string().nullish()});function La({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 Ra({tools:e,toolChoice:t,strictJsonSchema: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)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=va.parse(t.args);i.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`:i.push({type:`local_shell`});break;case`openai.web_search_preview`:{let e=ja.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Oa.parse(t.args);i.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=pa.parse(t.args);i.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=xa.parse(t.args);i.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:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`image_generation`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:throw new S({functionality:`tool choice type: ${a}`})}}var za=M.object({type:M.literal(`web_search_call`),id:M.string(),status:M.string(),action:M.discriminatedUnion(`type`,[M.object({type:M.literal(`search`),query:M.string().nullish()}),M.object({type:M.literal(`open_page`),url:M.string()}),M.object({type:M.literal(`find`),url:M.string(),pattern:M.string()})]).nullish()}),Ba=M.object({type:M.literal(`file_search_call`),id:M.string(),queries:M.array(M.string()),results:M.array(M.object({attributes:M.record(M.string(),M.unknown()),file_id:M.string(),filename:M.string(),score:M.number(),text:M.string()})).nullish()}),Va=M.object({type:M.literal(`code_interpreter_call`),id:M.string(),code:M.string().nullable(),container_id:M.string(),outputs:M.array(M.discriminatedUnion(`type`,[M.object({type:M.literal(`logs`),logs:M.string()}),M.object({type:M.literal(`image`),url:M.string()})])).nullable()}),Ha=M.object({type:M.literal(`local_shell_call`),id:M.string(),call_id:M.string(),action:M.object({type:M.literal(`exec`),command:M.array(M.string()),timeout_ms:M.number().optional(),user:M.string().optional(),working_directory:M.string().optional(),env:M.record(M.string(),M.string()).optional()})}),Ua=M.object({type:M.literal(`image_generation_call`),id:M.string(),result:M.string()}),Wa=20,Ga=M.array(M.object({token:M.string(),logprob:M.number(),top_logprobs:M.array(M.object({token:M.string(),logprob:M.number()}))})),Ka=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=So(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 gi({provider:`openai`,providerOptions:l,schema:Co}),{input:g,warnings:_}=await Fa({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?Wa: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:ee,toolChoice:T,toolWarnings:E}=Ra({tools:u,toolChoice:d,strictJsonSchema:v});return{webSearchToolName:C,args:{...w,tools:ee,tool_choice:T},warnings:[...p,...E]}}async doGenerate(e){var t,n;let{args:r,warnings:i,webSearchToolName:a}=await this.getArgs(e),o=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:c,value:l,rawValue:u}=await vi({url:o,headers:Vr(this.config.headers(),e.headers),body:r,failedResponseHandler:Fi,successfulResponseHandler:Ei(M.object({id:M.string(),created_at:M.number(),error:M.object({code:M.string(),message:M.string()}).nullish(),model:M.string(),output:M.array(M.discriminatedUnion(`type`,[M.object({type:M.literal(`message`),role:M.literal(`assistant`),id:M.string(),content:M.array(M.object({type:M.literal(`output_text`),text:M.string(),logprobs:Ga.nullish(),annotations:M.array(M.discriminatedUnion(`type`,[M.object({type:M.literal(`url_citation`),start_index:M.number(),end_index:M.number(),url:M.string(),title:M.string()}),M.object({type:M.literal(`file_citation`),file_id:M.string(),filename:M.string().nullish(),index:M.number().nullish(),start_index:M.number().nullish(),end_index:M.number().nullish(),quote:M.string().nullish()}),M.object({type:M.literal(`container_file_citation`)})]))}))}),za,Ba,Va,Ua,Ha,M.object({type:M.literal(`function_call`),call_id:M.string(),name:M.string(),arguments:M.string(),id:M.string()}),M.object({type:M.literal(`computer_call`),id:M.string(),status:M.string().optional()}),M.object({type:M.literal(`reasoning`),id:M.string(),encrypted_content:M.string().nullish(),summary:M.array(M.object({type:M.literal(`summary_text`),text:M.string()}))})])),service_tier:M.string().nullish(),incomplete_details:M.object({reason:M.string()}).nullish(),usage:qa})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(l.error)throw new s({message:l.error.message,url:o,requestBodyValues:r,statusCode:400,responseHeaders:c,responseBody:u,isRetryable:!1});let d=[],f=[],p=!1;for(let r of l.output)switch(r.type){case`reasoning`:r.summary.length===0&&r.summary.push({type:`summary_text`,text:``});for(let e of r.summary)d.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:r.id,reasoningEncryptedContent:r.encrypted_content??null}}});break;case`image_generation_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`image_generation`,input:`{}`,providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`image_generation`,result:{result:r.result},providerExecuted:!0});break;case`local_shell_call`:d.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 i of r.content){e.providerOptions?.openai?.logprobs&&i.logprobs&&f.push(i.logprobs),d.push({type:`text`,text:i.text,providerMetadata:{openai:{itemId:r.id}}});for(let e of i.annotations)e.type===`url_citation`?d.push({type:`source`,sourceType:`url`,id:(t=this.config).generateId?.call(t)??Kr(),url:e.url,title:e.title}):e.type===`file_citation`&&d.push({type:`source`,sourceType:`document`,id:(n=this.config).generateId?.call(n)??Kr(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id})}break;case`function_call`:p=!0,d.push({type:`tool-call`,toolCallId:r.call_id,toolName:r.name,input:r.arguments,providerMetadata:{openai:{itemId:r.id}}});break;case`web_search_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:a??`web_search`,input:JSON.stringify({action:r.action}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:a??`web_search`,result:{status:r.status},providerExecuted:!0});break;case`computer_call`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`computer_use`,input:``,providerExecuted:!0}),d.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`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`file_search`,input:`{}`,providerExecuted:!0}),d.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`:d.push({type:`tool-call`,toolCallId:r.id,toolName:`code_interpreter`,input:JSON.stringify({code:r.code,containerId:r.container_id}),providerExecuted:!0}),d.push({type:`tool-result`,toolCallId:r.id,toolName:`code_interpreter`,result:{outputs:r.outputs},providerExecuted:!0});break}let m={openai:{responseId:l.id}};return f.length>0&&(m.openai.logprobs=f),typeof l.service_tier==`string`&&(m.openai.serviceTier=l.service_tier),{content:d,finishReason:La({finishReason:l.incomplete_details?.reason,hasFunctionCall:p}),usage:{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,reasoningTokens:l.usage.output_tokens_details?.reasoning_tokens??void 0,cachedInputTokens:l.usage.input_tokens_details?.cached_tokens??void 0},request:{body:r},response:{id:l.id,timestamp:new Date(l.created_at*1e3),modelId:l.model,headers:c,body:u},providerMetadata:m,warnings:i}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await vi({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Fi,successfulResponseHandler:Ti(oo),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(go(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}}}):_o(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(co(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(lo(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(po(g)){let e=d[g.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:g.delta})}else if(mo(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(ho(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 fo(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})):so(g)?(n.enqueue({type:`text-delta`,id:g.item_id,delta:g.delta}),e.providerOptions?.openai?.logprobs&&g.logprobs&&l.push(g.logprobs)):yo(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}}})):bo(g)?n.enqueue({type:`reasoning-delta`,id:`${g.item_id}:${g.summary_index}`,delta:g.delta,providerMetadata:{openai:{itemId:g.item_id}}}):uo(g)?(s=La({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)):vo(g)?g.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=o.config).generateId?.call(a)??Kr(),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)??Kr(),mediaType:`text/plain`,title:g.annotation.quote??g.annotation.filename??`Document`,filename:g.annotation.filename??g.annotation.file_id}):xo(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}}}},qa=M.object({input_tokens:M.number(),input_tokens_details:M.object({cached_tokens:M.number().nullish()}).nullish(),output_tokens:M.number(),output_tokens_details:M.object({reasoning_tokens:M.number().nullish()}).nullish()}),Ja=M.object({type:M.literal(`response.output_text.delta`),item_id:M.string(),delta:M.string(),logprobs:Ga.nullish()}),Ya=M.object({type:M.literal(`error`),code:M.string(),message:M.string(),param:M.string().nullish(),sequence_number:M.number()}),Xa=M.object({type:M.enum([`response.completed`,`response.incomplete`]),response:M.object({incomplete_details:M.object({reason:M.string()}).nullish(),usage:qa,service_tier:M.string().nullish()})}),Za=M.object({type:M.literal(`response.created`),response:M.object({id:M.string(),created_at:M.number(),model:M.string(),service_tier:M.string().nullish()})}),Qa=M.object({type:M.literal(`response.output_item.added`),output_index:M.number(),item:M.discriminatedUnion(`type`,[M.object({type:M.literal(`message`),id:M.string()}),M.object({type:M.literal(`reasoning`),id:M.string(),encrypted_content:M.string().nullish()}),M.object({type:M.literal(`function_call`),id:M.string(),call_id:M.string(),name:M.string(),arguments:M.string()}),M.object({type:M.literal(`web_search_call`),id:M.string(),status:M.string(),action:M.object({type:M.literal(`search`),query:M.string().optional()}).nullish()}),M.object({type:M.literal(`computer_call`),id:M.string(),status:M.string()}),M.object({type:M.literal(`file_search_call`),id:M.string()}),M.object({type:M.literal(`image_generation_call`),id:M.string()}),M.object({type:M.literal(`code_interpreter_call`),id:M.string(),container_id:M.string(),code:M.string().nullable(),outputs:M.array(M.discriminatedUnion(`type`,[M.object({type:M.literal(`logs`),logs:M.string()}),M.object({type:M.literal(`image`),url:M.string()})])).nullable(),status:M.string()})])}),$a=M.object({type:M.literal(`response.output_item.done`),output_index:M.number(),item:M.discriminatedUnion(`type`,[M.object({type:M.literal(`message`),id:M.string()}),M.object({type:M.literal(`reasoning`),id:M.string(),encrypted_content:M.string().nullish()}),M.object({type:M.literal(`function_call`),id:M.string(),call_id:M.string(),name:M.string(),arguments:M.string(),status:M.literal(`completed`)}),Va,Ua,za,Ba,Ha,M.object({type:M.literal(`computer_call`),id:M.string(),status:M.literal(`completed`)})])}),eo=M.object({type:M.literal(`response.function_call_arguments.delta`),item_id:M.string(),output_index:M.number(),delta:M.string()}),to=M.object({type:M.literal(`response.code_interpreter_call_code.delta`),item_id:M.string(),output_index:M.number(),delta:M.string()}),no=M.object({type:M.literal(`response.code_interpreter_call_code.done`),item_id:M.string(),output_index:M.number(),code:M.string()}),ro=M.object({type:M.literal(`response.output_text.annotation.added`),annotation:M.discriminatedUnion(`type`,[M.object({type:M.literal(`url_citation`),url:M.string(),title:M.string()}),M.object({type:M.literal(`file_citation`),file_id:M.string(),filename:M.string().nullish(),index:M.number().nullish(),start_index:M.number().nullish(),end_index:M.number().nullish(),quote:M.string().nullish()})])}),io=M.object({type:M.literal(`response.reasoning_summary_part.added`),item_id:M.string(),summary_index:M.number()}),ao=M.object({type:M.literal(`response.reasoning_summary_text.delta`),item_id:M.string(),summary_index:M.number(),delta:M.string()}),oo=M.union([Ja,Xa,Za,Qa,$a,eo,to,no,ro,io,ao,Ya,M.object({type:M.string()}).loose()]);function so(e){return e.type===`response.output_text.delta`}function co(e){return e.type===`response.output_item.done`}function lo(e){return co(e)&&e.item.type===`reasoning`}function uo(e){return e.type===`response.completed`||e.type===`response.incomplete`}function fo(e){return e.type===`response.created`}function po(e){return e.type===`response.function_call_arguments.delta`}function mo(e){return e.type===`response.code_interpreter_call_code.delta`}function ho(e){return e.type===`response.code_interpreter_call_code.done`}function go(e){return e.type===`response.output_item.added`}function _o(e){return go(e)&&e.item.type===`reasoning`}function vo(e){return e.type===`response.output_text.annotation.added`}function yo(e){return e.type===`response.reasoning_summary_part.added`}function bo(e){return e.type===`response.reasoning_summary_text.delta`}function xo(e){return e.type===`error`}function So(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 Co=M.object({include:M.array(M.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:M.string().nullish(),logprobs:M.union([M.boolean(),M.number().min(1).max(Wa)]).optional(),maxToolCalls:M.number().nullish(),metadata:M.any().nullish(),parallelToolCalls:M.boolean().nullish(),previousResponseId:M.string().nullish(),promptCacheKey:M.string().nullish(),reasoningEffort:M.string().nullish(),reasoningSummary:M.string().nullish(),safetyIdentifier:M.string().nullish(),serviceTier:M.enum([`auto`,`flex`,`priority`]).nullish(),store:M.boolean().nullish(),strictJsonSchema:M.boolean().nullish(),textVerbosity:M.enum([`low`,`medium`,`high`]).nullish(),user:M.string().nullish()}),wo=M.object({instructions:M.string().nullish(),speed:M.number().min(.25).max(4).default(1).nullish()}),To=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 gi({provider:`openai`,providerOptions:o,schema:wo}),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 vi({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),body:r,failedResponseHandler:Fi,successfulResponseHandler:Di(),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}}}},Eo=M.object({include:M.array(M.string()).optional(),language:M.string().optional(),prompt:M.string().optional(),temperature:M.number().min(0).max(1).default(0).optional(),timestampGranularities:M.array(M.enum([`word`,`segment`])).default([`segment`]).optional()}),Do={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`},Oo=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 gi({provider:`openai`,providerOptions:n,schema:Eo}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([Ai(e)]);a.append(`model`,this.modelId);let s=$r(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 yi({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:Vr(this.config.headers(),e.headers),formData:r,failedResponseHandler:Fi,successfulResponseHandler:Ei(ko),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=a.language!=null&&a.language in Do?Do[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}}}},ko=M.object({text:M.string(),language:M.string().nullish(),duration:M.number().nullish(),words:M.array(M.object({word:M.string(),start:M.number(),end:M.number()})).nullish(),segments:M.array(M.object({id:M.number(),seek:M.number(),start:M.number(),end:M.number(),text:M.string(),tokens:M.array(M.number()),temperature:M.number(),avg_logprob:M.number(),compression_ratio:M.number(),no_speech_prob:M.number()})).nullish()}),Ao=`2.0.42`;function jo(e={}){let t=Ni(Qr({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>Gr({Authorization:`Bearer ${Zr({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Ao}`),i=i=>new Vi(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new ea(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new aa(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new la(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new Oo(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new To(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 Ka(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=Na,f}jo();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)}(({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 p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function Lo(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Ro=[`fetch failed`,`failed to fetch`];function zo({error:e,url:t,requestBodyValues:n}){if(Lo(e))return e;if(e instanceof TypeError&&Ro.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var Bo=`3.0.10`,Vo=/"__proto__"\s*:/,Ho=/"constructor"\s*:/;function Uo(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Vo.test(e)===!1&&Ho.test(e)===!1?t:Wo(t)}function Wo(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 Go(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Uo(e)}finally{Error.stackTraceLimit=t}}var Ko=Symbol.for(`vercel.ai.validator`);function qo(e){return{[Ko]:!0,validate:e}}function Jo(e){return typeof e==`object`&&!!e&&Ko in e&&e[Ko]===!0&&`validate`in e}function Yo(e){return Jo(e)?e:Xo(e)}function Xo(e){return qo(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function Zo({value:e,schema:t}){let n=await Qo({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Qo({value:e,schema:t}){let n=Yo(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:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function $o({text:e,schema:t}){try{let n=Go(e);return t==null?n:Zo({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function es({text:e,schema:t}){try{let n=Go(e);return t==null?{success:!0,value:n,rawValue:n}:await Qo({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}var ts=()=>globalThis.fetch,ns=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>rs({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),rs=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=ts()})=>{try{let c=await o(e,{method:`POST`,headers:Io(t,`ai-sdk/provider-utils/${Bo}`,Po()),body:n.content,signal:a}),l=No(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw Lo(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Lo(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw zo({error:t,url:e,requestBodyValues:n.values})}},os=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=No(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await $o({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},ss=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await es({text:i,schema:e}),o=No(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:cs,atob:ls}=globalThis;M.object({user:M.string().optional(),reasoningEffort:M.string().optional()});var us={errorSchema:M.object({error:M.object({message:M.string(),type:M.string().nullish(),param:M.any().nullish(),code:M.union([M.string(),M.number()]).nullish()})}),errorToMessage:e=>e.error.message},ds=M.object({prompt_tokens:M.number().nullish(),completion_tokens:M.number().nullish(),total_tokens:M.number().nullish(),prompt_tokens_details:M.object({cached_tokens:M.number().nullish()}).nullish(),completion_tokens_details:M.object({reasoning_tokens:M.number().nullish(),accepted_prediction_tokens:M.number().nullish(),rejected_prediction_tokens:M.number().nullish()}).nullish()}).nullish();M.object({id:M.string().nullish(),created:M.number().nullish(),model:M.string().nullish(),choices:M.array(M.object({message:M.object({role:M.literal(`assistant`).nullish(),content:M.string().nullish(),reasoning_content:M.string().nullish(),reasoning:M.string().nullish(),tool_calls:M.array(M.object({id:M.string().nullish(),function:M.object({name:M.string(),arguments:M.string()})})).nullish()}),finish_reason:M.string().nullish()})),usage:ds}),M.object({echo:M.boolean().optional(),logitBias:M.record(M.string(),M.number()).optional(),suffix:M.string().optional(),user:M.string().optional()});var fs=M.object({prompt_tokens:M.number(),completion_tokens:M.number(),total_tokens:M.number()});M.object({id:M.string().nullish(),created:M.number().nullish(),model:M.string().nullish(),choices:M.array(M.object({text:M.string(),finish_reason:M.string()})),usage:fs.nullish()}),M.object({dimensions:M.number().optional(),user:M.string().optional()}),M.object({data:M.array(M.object({embedding:M.array(M.number())})),usage:M.object({prompt_tokens:M.number()}).nullish(),providerMetadata:M.record(M.string(),M.record(M.string(),M.any())).optional()});var ps=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 ns({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Mo(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...a.openai??{},response_format:`b64_json`},failedResponseHandler:os(this.config.errorStructure??us),successfulResponseHandler:ss(ms),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}}}},ms=M.object({data:M.array(M.object({b64_json:M.string()}))});function hs(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function gs(e){return Object.fromEntries([...e.headers])}function _s(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 vs(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}function ys(e,...t){let n=vs(e??{}),r=new Headers(n),i=r.get(`user-agent`)||``;return r.set(`user-agent`,[i,...t].filter(Boolean).join(` `)),Object.fromEntries(r)}var bs=(({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 p({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();function xs(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Ss=[`fetch failed`,`failed to fetch`];function Cs({error:e,url:t,requestBodyValues:n}){if(xs(e))return e;if(e instanceof TypeError&&Ss.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new s({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}var ws=`3.0.10`;function Ts({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new _({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new _({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new _({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var Es=/"__proto__"\s*:/,Ds=/"constructor"\s*:/;function Os(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Es.test(e)===!1&&Ds.test(e)===!1?t:ks(t)}function ks(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 As(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Os(e)}finally{Error.stackTraceLimit=t}}var js=Symbol.for(`vercel.ai.validator`);function Ms(e){return{[js]:!0,validate:e}}function Ns(e){return typeof e==`object`&&!!e&&js in e&&e[js]===!0&&`validate`in e}function Ps(e){return Ns(e)?e:Fs(e)}function Fs(e){return Ms(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new x({value:t,cause:n.issues})}})}async function Is({value:e,schema:t}){let n=await Ls({value:e,schema:t});if(!n.success)throw x.wrap({value:e,cause:n.error});return n.value}async function Ls({value:e,schema:t}){let n=Ps(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:x.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:x.wrap({value:e,cause:t}),rawValue:e}}}async function Rs({text:e,schema:t}){try{let n=As(e);return t==null?n:Is({value:n,schema:t})}catch(t){throw g.isInstance(t)||x.isInstance(t)?t:new g({text:e,cause:t})}}async function zs({text:e,schema:t}){try{let n=As(e);return t==null?{success:!0,value:n,rawValue:n}:await Ls({value:n,schema:t})}catch(t){return{success:!1,error:g.isInstance(t)?t:new g({text:e,cause:t}),rawValue:void 0}}}function Bs({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new d).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await zs({text:e,schema:t}))}}))}async function Vs({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await Ls({value:t[e],schema:n});if(!r.success)throw new p({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var Hs=()=>globalThis.fetch,Us=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Ws({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Ws=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=Hs()})=>{try{let c=await o(e,{method:`POST`,headers:ys(t,`ai-sdk/provider-utils/${ws}`,_s()),body:n.content,signal:a}),l=gs(c);if(!c.ok){let t;try{t=await i({response:c,url:e,requestBodyValues:n.values})}catch(t){throw xs(t)||s.isInstance(t)?t:new s({message:`Failed to process error response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw t.value}try{return await r({response:c,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(xs(t)||s.isInstance(t))?t:new s({message:`Failed to process successful response`,cause:t,statusCode:c.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(t){throw Cs({error:t,url:e,requestBodyValues:n.values})}},Gs=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),c=gs(r);if(o.trim()===``)return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})};try{let l=await Rs({text:o,schema:e});return{responseHeaders:c,value:new s({message:t(l),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,data:l,isRetryable:n?.(r,l)})}}catch{return{responseHeaders:c,value:new s({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:c,responseBody:o,isRetryable:n?.(r)})}}},Ks=e=>async({response:t})=>{let n=gs(t);if(t.body==null)throw new u({});return{responseHeaders:n,value:Bs({stream:t.body,schema:e})}},qs=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await zs({text:i,schema:e}),o=gs(t);if(!a.success)throw new s({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},{btoa:Js,atob:Ys}=globalThis;function Xs(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Js(t)}function Zs(e){return e instanceof Uint8Array?Xs(e):e}function Qs(e){return e?.replace(/\/$/,``)}function $s(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.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,${Zs(e.data)}`}}}else throw new S({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function ec({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 tc(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 nc=M.object({type:M.literal(`web`),country:M.string().length(2).optional(),excludedWebsites:M.array(M.string()).max(5).optional(),allowedWebsites:M.array(M.string()).max(5).optional(),safeSearch:M.boolean().optional()}),rc=M.object({type:M.literal(`x`),excludedXHandles:M.array(M.string()).optional(),includedXHandles:M.array(M.string()).optional(),postFavoriteCount:M.number().int().optional(),postViewCount:M.number().int().optional(),xHandles:M.array(M.string()).optional()}),ic=M.object({type:M.literal(`news`),country:M.string().length(2).optional(),excludedWebsites:M.array(M.string()).max(5).optional(),safeSearch:M.boolean().optional()}),ac=M.object({type:M.literal(`rss`),links:M.array(M.string().url()).max(1)}),oc=M.discriminatedUnion(`type`,[nc,rc,ic,ac]),sc=M.object({reasoningEffort:M.enum([`low`,`high`]).optional(),searchParameters:M.object({mode:M.enum([`off`,`auto`,`on`]),returnCitations:M.boolean().optional(),fromDate:M.string().optional(),toDate:M.string().optional(),maxSearchResults:M.number().min(1).max(50).optional(),sources:M.array(oc).optional()}).optional()}),cc=M.object({error:M.object({message:M.string(),type:M.string().nullish(),param:M.any().nullish(),code:M.union([M.string(),M.number()]).nullish()})}),lc=Gs({errorSchema:cc,errorToMessage:e=>e.error.message});function uc({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new S({functionality:`tool choice type: ${i}`})}}var dc=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 Vs({provider:`xai`,providerOptions:u,schema:sc})??{};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}=$s(e);p.push(...g);let{tools:_,toolChoice:v,toolWarnings:y}=uc({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 Us({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:hs(this.config.headers(),e.headers),body:t,failedResponseHandler:lc,successfulResponseHandler:qs(pc),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:tc(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:{...ec(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 Us({url:`${this.config.baseURL??`https://api.x.ai/v1`}/chat/completions`,headers:hs(this.config.headers(),e.headers),body:r,failedResponseHandler:lc,successfulResponseHandler:Ks(mc),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`,...ec(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=tc(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}}}},fc=M.object({prompt_tokens:M.number(),completion_tokens:M.number(),total_tokens:M.number(),completion_tokens_details:M.object({reasoning_tokens:M.number().nullish()}).nullish()}),pc=M.object({id:M.string().nullish(),created:M.number().nullish(),model:M.string().nullish(),choices:M.array(M.object({message:M.object({role:M.literal(`assistant`),content:M.string().nullish(),reasoning_content:M.string().nullish(),tool_calls:M.array(M.object({id:M.string(),type:M.literal(`function`),function:M.object({name:M.string(),arguments:M.string()})})).nullish()}),index:M.number(),finish_reason:M.string().nullish()})),object:M.literal(`chat.completion`),usage:fc,citations:M.array(M.string().url()).nullish()}),mc=M.object({id:M.string().nullish(),created:M.number().nullish(),model:M.string().nullish(),choices:M.array(M.object({delta:M.object({role:M.enum([`assistant`]).optional(),content:M.string().nullish(),reasoning_content:M.string().nullish(),tool_calls:M.array(M.object({id:M.string(),type:M.literal(`function`),function:M.object({name:M.string(),arguments:M.string()})})).nullish()}),finish_reason:M.string().nullish(),index:M.number()})),usage:fc.nullish(),citations:M.array(M.string().url()).nullish()}),hc=`2.0.23`,gc={errorSchema:cc,errorToMessage:e=>e.error.message};function _c(e={}){let t=Qs(e.baseURL??`https://api.x.ai/v1`),n=()=>ys({Authorization:`Bearer ${Ts({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers},`ai-sdk/xai/${hc}`),r=r=>new dc(r,{provider:`xai.chat`,baseURL:t,headers:n,generateId:bs,fetch:e.fetch}),i=r=>new ps(r,{provider:`xai.image`,url:({path:e})=>`${t}${e}`,headers:n,fetch:e.fetch,errorStructure:gc}),a=e=>r(e);return a.languageModel=r,a.chat=r,a.textEmbeddingModel=e=>{throw new v({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=i,a.image=i,a}_c();function vc(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(y);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new d).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 n=e=>be({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(jo({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(jo({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(_n({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(Br({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(_c({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}function yc(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var bc=class{_lockP=null;async lock(){let e=this._lockP,{promise:t,resolve:n}=yc();return this._lockP=t,await e,n}withLock(e){return Sc(this.lock(),e)}},xc=class{_lock=new bc;_writeP=null;_readP=[];read(){return this._lock.withLock(async()=>{await this._writeP;let{promise:e,resolve:t}=yc();return this._readP.push(e),t})}withRead(e){return Sc(this.read(),e)}async write(){return await this._lock.withLock(async()=>{await this._writeP,await Promise.all(this._readP);let{promise:e,resolve:t}=yc();return this._writeP=e,this._readP=[],t})}withWrite(e){return Sc(this.write(),e)}};async function Sc(e,t){let n=await e;try{return await t()}finally{n()}}var Cc=class{constructor(e){this.onRelease=e}[Symbol.dispose](){this.onRelease()}},wc=class{constructor(e){this.onRelease=e}[Symbol.dispose](){this.onRelease()}},Tc=class{_lock=new xc;async read(){let e=await this._lock.read();return new Cc(e)}async write(){let e=await this._lock.write();return new wc(e)}},Ec=class{baseUrl;client;constructor(e){this.client=ee(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),vc(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 Dc(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}function Oc(e){let[t,n]=W(void 0),[r,i]=W([]),[a,o]=W(void 0),[s,l]=W(e.buildResult),[u,d]=W(e.env),[f,p]=W(e.apiServerUrl),[m,h]=W(void 0);return H(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),H(()=>{if(!s||`error`in s){n(void 0),i([]),o(void 0),h(void 0);return}let e=new AbortController,t=!1;o(void 0),n(void 0),h(void 0);let r;return(async()=>{let t=await kc(),a=we(`node`,[`--no-deprecation`,s.entry],{stdio:`pipe`,env:{...process.env,...u,[c]:f,PORT:t.toString(),HOST:`127.0.0.1`},detached:!1}),o=()=>{try{a.kill()}catch{}};process.once(`exit`,o),process.once(`SIGINT`,o),process.once(`SIGTERM`,o),process.once(`uncaughtException`,o),e.signal.addEventListener(`abort`,()=>{process.off(`exit`,o),process.off(`SIGINT`,o),process.off(`SIGTERM`,o),process.off(`uncaughtException`,o),o()});let l=!1;a.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!l&&t.startsWith(`Agent server listening on`)||(l||console.log(`stdout: ${t}`),t.length&&i(e=>[...e,{level:`log`,message:t}]))}),a.stderr.on(`data`,e=>{l||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&i(e=>[...e,{level:`error`,message:t}])}),a.on(`error`,t=>{e.abort(t)}),a.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let d=new Ec({baseUrl:`http://127.0.0.1:${t}`}),p=new Tc;for(r=p;!e.signal.aborted;){try{await d.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;l=!0;let m=await d.capabilities();h(m),n({client:d,lock:p})})().catch(e=>{t||o(e instanceof Error?e:Error(String(e)))}),()=>{t=!0,(async()=>{try{var t=Dc();t.u(await r?.write()),e.abort()}catch(e){t.e=e}finally{t.d()}})()}},[s,u,f]),Ee(()=>({agent:t,logs:r,error:a,capabilities:m}),[t,r,a,m])}async function kc(){let e=ue();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}var Ac=Object.getOwnPropertyNames,jc=(e,t)=>function(){return t||(0,e[Ac(e)[0]])((t={exports:{}}).exports,t),t.exports},Y=A(import.meta.url);K.object({email:K.string().email(),password:K.string().min(8)}),K.object({email:K.string().email(),code:K.string()}),K.object({email:K.string().email(),password:K.string().min(8)});var Mc=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))}})}},Nc=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 Pc(e){}function Fc(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Pc,onError:n=Pc,onRetry:r=Pc,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Ic(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
16
16
  `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Nc(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Nc(`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
17
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Ic(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
18
18
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
19
19
  `&&r++}}return[t,n]}var Lc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Fc({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)}})}},Rc=`vercel.ai.error`,zc=Symbol.for(Rc),Bc,Vc=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Bc]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Rc)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};Bc=zc;var Hc=Vc;function Uc(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var Wc=`AI_InvalidArgumentError`,Gc=`vercel.ai.error.${Wc}`,Kc=Symbol.for(Gc),qc,Jc=class extends Hc{constructor({message:e,cause:t,argument:n}){super({name:Wc,message:e,cause:t}),this[qc]=!0,this.argument=n}static isInstance(e){return Hc.hasMarker(e,Gc)}};qc=Kc;var Yc=`AI_JSONParseError`,Xc=`vercel.ai.error.${Yc}`,Zc=Symbol.for(Xc),Qc,$c=class extends Hc{constructor({text:e,cause:t}){super({name:Yc,message:`JSON parsing failed: Text: ${e}.
20
20
  Error message: ${Uc(t)}`,cause:t}),this[Qc]=!0,this.text=e}static isInstance(e){return Hc.hasMarker(e,Xc)}};Qc=Zc;var el=`AI_TypeValidationError`,tl=`vercel.ai.error.${el}`,nl=Symbol.for(tl),rl,il=class e extends Hc{constructor({value:e,cause:t}){super({name:el,message:`Type validation failed: Value: ${JSON.stringify(e)}.
21
- Error message: ${Uc(t)}`,cause:t}),this[rl]=!0,this.value=e}static isInstance(e){return Hc.hasMarker(e,tl)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};rl=nl;var al=il;(({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 Jc({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();var ol=/"__proto__"\s*:/,sl=/"constructor"\s*:/;function cl(e){let t=JSON.parse(e);return typeof t!=`object`||!t||ol.test(e)===!1&&sl.test(e)===!1?t:ll(t)}function ll(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 ul(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return cl(e)}finally{Error.stackTraceLimit=t}}var dl=Symbol.for(`vercel.ai.validator`);function fl(e){return{[dl]:!0,validate:e}}function pl(e){return typeof e==`object`&&!!e&&dl in e&&e[dl]===!0&&`validate`in e}function ml(e){return pl(e)?e:hl(e)}function hl(e){return fl(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new al({value:t,cause:n.issues})}})}async function gl({value:e,schema:t}){let n=ml(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:al.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:al.wrap({value:e,cause:t}),rawValue:e}}}async function _l({text:e,schema:t}){try{let n=ul(e);return t==null?{success:!0,value:n,rawValue:n}:await gl({value:n,schema:t})}catch(t){return{success:!1,error:$c.isInstance(t)?t:new $c({text:e,cause:t}),rawValue:void 0}}}var{btoa:vl,atob:yl}=globalThis;function bl(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 X=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}`)}}},xl=q.object({per_page:q.number().int().positive().max(100).default(10).optional(),page:q.number().int().nonnegative().default(0).optional()}),Sl=e=>q.object({has_more:q.boolean(),items:q.array(e)}),Cl=q.object({limit:q.number().int().positive().max(100).default(10).optional(),cursor:q.string().optional()}),wl=e=>q.object({next_cursor:q.string().nullable(),items:q.array(e)}),Tl=q.any().nullable().refine(e=>e?Object.keys(e).length<=16:!0,{message:`Metadata must contain at most 16 keys`}),El=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,Dl=(e,t)=>{let n=new Lc;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(n.writable).catch(e=>{}),Ol(n.readable,t)},Ol=(e,t)=>{let n=e.pipeThrough(new TransformStream({async transform(e,n){let r=await _l({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 bl(n)};q.union([q.object({agent_id:q.uuid(),deployment_id:q.uuid()}),q.object({agent_id:q.uuid(),deployment_number:q.number().int().positive()})]),q.object({agent_id:q.uuid(),deployment_id:q.uuid()});const kl=q.object({path:q.string(),id:q.uuid()}),Al=kl.or(q.object({path:q.string(),data:q.string().max(1024*1024*5)})),jl=q.enum([`production`,`preview`]);q.object({agent_id:q.uuid(),output_files:q.array(Al).optional(),source_files:q.array(Al).optional(),files:q.array(Al).optional(),target:jl,entrypoint:q.string().optional(),message:q.string().max(128).optional()}).transform(e=>e.files&&!e.output_files?{...e,output_files:e.files,files:void 0}:e);const Ml=q.object({id:q.uuid(),number:q.number().int().positive(),created_at:q.iso.datetime(),updated_at:q.iso.datetime(),created_by:q.uuid().nullable(),created_from:q.enum([`cli`]),agent_id:q.uuid(),source_files:q.array(kl),output_files:q.array(kl),status:q.enum([`success`,`failed`,`deploying`,`pending`]),target:jl,error_message:q.string().nullable(),user_message:q.string().nullable(),platform:q.enum([`lambda`]),platform_memory_mb:q.number().int().positive(),platform_region:q.string().nullable()});q.object({id:q.uuid(),created_at:q.string().datetime(),updated_at:q.string().datetime(),agent_id:q.uuid(),deployment_id:q.uuid(),level:q.enum([`log`,`info`,`warning`,`error`]),message:q.string()}),xl.extend({agent_id:q.uuid(),order:q.enum([`asc`,`desc`]).default(`asc`).optional()}),Sl(Ml);var Nl=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 X(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 X(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 X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);await X(t,200)}};q.object({agent_id:q.uuid(),target:jl.array().optional()}),q.object({id:q.uuid(),created_at:q.date(),updated_at:q.date(),created_by:q.uuid(),updated_by:q.uuid(),key:q.string(),value:q.string().nullable(),secret:q.boolean(),target:jl.array()});const Pl=q.object({key:q.string(),value:q.string(),secret:q.boolean(),target:jl.array().optional(),upsert:q.boolean().optional()});Pl.extend({agent_id:q.uuid()}),q.object({agent_id:q.uuid(),id:q.uuid()}),q.object({agent_id:q.uuid(),id:q.uuid(),key:q.string().optional(),value:q.string().optional(),secret:q.boolean().optional(),target:jl.array().default([`preview`,`production`]).optional()});var Fl=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 X(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 X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/env/${e.id}`);await X(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 X(t,200),t.json()}};const Il=q.object({id:q.string(),agent_id:q.uuid(),agent_deployment_id:q.uuid(),received_at:q.date(),request_method:q.string(),request_handler_location:q.string().nullable(),duration_ms:q.number().nullable(),error:q.string().nullable(),response_status:q.number().nullable()});Il.extend({request_headers:q.record(q.string(),q.string()),request_headers_redacted:q.boolean(),request_body:q.string().nullable(),request_body_redacted:q.boolean(),response_headers:q.record(q.string(),q.string()).nullable(),response_headers_redacted:q.boolean(),response_body:q.string().nullable(),response_body_redacted:q.boolean()}),Cl.extend({agent_id:q.string(),agent_deployment_id:q.number().optional()}),wl(Il);var Ll=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 X(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 X(n,200),n.json()}};Cl.extend({agent_id:q.uuid(),agent_deployment_id:q.uuid().optional()}),q.object({agent_id:q.uuid(),run_id:q.uuid()});var Rl=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 X(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 X(t,200),t.json()}};const zl=q.enum([`streaming`,`stalled`,`completed`,`interrupted`,`error`]),Bl=q.enum([`tool_call`,`queued_message`]),Vl=q.object({id:q.uuid(),number:q.number().int().positive(),chat_id:q.uuid(),chat_run_id:q.uuid(),agent_id:q.uuid(),agent_deployment_id:q.uuid(),started_at:q.string().datetime(),status:zl,error:q.string().nullable(),continuation_reason:Bl.nullable(),response_status:q.number().nullable(),response_message_id:q.uuid().nullable(),time_to_first_token_micros:q.number().nullable()});Vl.extend({heartbeat_at:q.date(),completed_at:q.date().nullable(),interrupted_at:q.date().nullable(),first_message_id:q.uuid().nullable(),last_message_id:q.uuid().nullable(),response_headers:q.record(q.string(),q.string()).nullable(),response_headers_redacted:q.boolean(),response_body:q.string().nullable(),response_body_redacted:q.boolean(),usage_model:q.string().nullable(),usage_total_input_tokens:q.number().nullable(),usage_total_output_tokens:q.number().nullable(),usage_total_tokens:q.number().nullable(),usage_total_cached_input_tokens:q.number().nullable(),usage_cost_usd:q.number().nullable()}),Cl.extend({chat_id:q.uuid(),run_id:q.uuid().optional()}),wl(Vl);var Hl=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 X(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 X(t,200),t.json()}};Cl.extend({agent_id:q.uuid(),agent_deployment_id:q.uuid().optional(),chat_id:q.uuid().optional(),run_id:q.uuid().optional(),status:zl.optional()}),wl(Vl);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 X(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 X(t,200),t.json()}};const Wl=q.object({type:q.literal(`eq`),key:q.string(),value:q.string()}),Gl=q.object({type:q.literal(`and`),get filters(){return q.array(q.union([Wl,Gl]))}});q.object({start_time:q.iso.datetime().pipe(q.coerce.date()),end_time:q.iso.datetime().pipe(q.coerce.date()),filters:q.string().transform(e=>JSON.parse(e)).pipe(Gl),limit:q.string().pipe(q.coerce.number().min(1).max(1e4)).optional()});var Kl=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 X(n,200),await n.json()}};K.object({start_time:K.iso.datetime().pipe(K.coerce.date()),end_time:K.iso.datetime().pipe(K.coerce.date()),message_pattern:K.string().optional(),filters:K.string().transform(e=>JSON.parse(e)).pipe(Gl).optional(),limit:K.string().pipe(K.coerce.number().min(1).max(1e4)).optional()});const ql=K.object({timestamp:K.iso.datetime().pipe(K.coerce.date()),message:K.string(),level:K.enum([`info`,`error`,`warn`])}),Jl=K.object({logs:K.array(ql)});var Yl=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 X(n,200);let r=await n.json();return Jl.parse(r)}};const Xl=q.enum([`private`,`public`]);q.object({organization_id:q.uuid(),name:q.string().regex(El),description:q.string().optional(),visibility:Xl.default(`private`).optional(),source_files:q.array(Al).optional(),output_files:q.array(Al).optional(),entrypoint:q.string().optional(),env:q.array(Pl).optional(),request_id:q.uuid().optional()});const Zl=q.object({id:q.uuid(),organization_id:q.uuid(),created_at:q.iso.datetime(),updated_at:q.iso.datetime(),created_by:q.uuid(),name:q.string().regex(El),description:q.string().nullable(),avatar_url:q.string().nullable(),visibility:Xl,active_deployment_id:q.uuid().nullable(),pinned:q.boolean().default(!1),request_url:q.url().nullable().describe(`The URL for the agent requests. Only visible to owners.`)});q.object({id:q.uuid(),name:q.string().regex(El).optional(),description:q.string().optional(),visibility:Xl.optional(),active_deployment_id:q.uuid().optional(),avatar_file_id:q.uuid().nullable().optional()}),xl.extend({organization_id:q.uuid().optional(),pinned:q.boolean().optional()}),Sl(Zl),q.object({agent_id:q.uuid(),input:q.string(),caret:q.number().optional(),selection:q.tuple([q.number(),q.number()]).optional(),chat_id:q.uuid().optional(),agent_deployment_id:q.uuid().optional()});const Ql=q.object({text:q.string(),caret:q.number().optional(),selection:q.tuple([q.number(),q.number()]).optional()});q.object({agent_id:q.uuid(),agent_deployment_id:q.uuid().optional(),selected:q.record(q.string(),q.string()).optional()}),q.object({agent_id:q.uuid(),start_time:q.iso.datetime().pipe(q.coerce.date()),end_time:q.iso.datetime().pipe(q.coerce.date())}),q.object({seconds:q.string()});var $l=class{constructor(e){this.client=e,this.deployments=new Nl(e),this.env=new Fl(e),this.webhook=new Ll(e),this.runs=new Rl(e),this.steps=new Ul(e),this.logs=new Yl(e),this.traces=new Kl(e)}async create(e){let t=await this.client.request(`POST`,`/api/agents`,JSON.stringify(e));return await X(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/agents/${e.id}`,JSON.stringify(e));return await X(t,200),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e}`);return await X(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 X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}`);await X(t,204)}async completions(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/completions`,JSON.stringify(e));if(await X(t,200),t.headers.get(`content-type`)===`application/json`){let e=await t.json();return bl(new ReadableStream({start(t){t.enqueue(e),t.close()}}))}return Dl(t,Ql)}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 X(n,200),n.json()}async pin(e){let t=await this.client.request(`POST`,`/api/agents/${e}/pin`);await X(t,204)}async unpin(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}/pin`);await X(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 X(n,200),n.json()}},eu=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 X(n,201),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/files/${e}`);return await X(t,200),new File([await t.blob()],``)}};const tu=q.enum([`owner`,`admin`,`billing_admin`,`member`]),nu=q.object({user_id:q.uuid(),organization_id:q.uuid(),role:tu,created_at:q.date(),updated_at:q.date()}),ru=q.object({id:q.uuid(),created_at:q.date(),updated_at:q.date(),display_name:q.string().nullable(),email:q.email(),avatar_url:q.url().nullable(),username:q.string()}),iu=nu.extend({user:ru});xl.extend({organization_id:q.uuid()}),Sl(iu),q.object({organization_id:q.uuid(),user_id:q.uuid()}),q.object({role:q.enum([`owner`,`admin`,`member`,`billing_admin`]).optional()}).extend({organization_id:q.uuid(),user_id:q.uuid()});var au=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 X(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 X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);await X(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 X(t,200),t.json()}},ou=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 X(t,200),t.json()}};q.object({id:q.uuid(),name:q.string(),created_at:q.date(),updated_at:q.date(),membership:nu.nullable(),members_url:q.url(),invites_url:q.url(),avatar_url:q.url().nullable()}),q.object({name:q.string().regex(El)}),q.object({name:q.string().max(100).optional(),avatar_file_id:q.string().nullable().optional(),avatar_url:q.string().url().nullable().optional()});var su=class{constructor(e){this.client=e,this.members=new au(e),this.agents=new ou(e)}async list(){let e=await this.client.request(`GET`,`/api/organizations`);return await X(e,200),e.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e}`);return await X(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/organizations`,JSON.stringify(e));return await X(t,201),t.json()}async update(e,t){let n=await this.client.request(`PATCH`,`/api/organizations/${e}`,JSON.stringify(t));return await X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e}`);await X(t,204)}};K.object({id:K.uuid(),created_at:K.date(),updated_at:K.date(),email:K.string().email(),email_verified:K.boolean(),display_name:K.string(),username:K.string(),organization_id:K.uuid(),avatar_url:K.string().url().nullable()}),K.object({display_name:K.string().max(100).optional(),username:K.string().regex(El).optional(),avatar_file_id:K.string().nullable().optional()});const cu=K.object({provider:K.enum([`github`,`google`]),provider_account_id:K.string()});K.object({github:K.array(cu),google:K.array(cu)});var lu=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 X(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/users/me`,JSON.stringify(e));return await X(t,200),t.json()}async accounts(){let e=await this.client.request(`GET`,`/api/users/me/accounts`);return await X(e,200),e.json()}async unlinkProvider(e,t){let n=await this.client.request(`DELETE`,`/api/users/me/accounts/${e}/${t}`);await X(n,204)}async delete(){let e=await this.client.request(`DELETE`,`/api/users/me`);await X(e,204)}};const uu=q.enum([`ai-sdk`]),du=q.array(q.custom()),fu=q.enum([`user`,`assistant`,`system`]),pu=q.object({id:q.uuid(),created_at:q.string().datetime(),chat_id:q.uuid(),metadata:Tl}).extend({format:q.literal(`ai-sdk`),parts:du,role:fu}),mu=q.discriminatedUnion(`format`,[pu]);Cl.extend({chat_id:q.uuid(),format:uu.default(`ai-sdk`).optional()}),wl(mu),q.object({chat_id:q.uuid(),message_id:q.uuid()});const hu=q.object({id:q.uuid().optional(),role:fu,parts:du,metadata:Tl.optional(),format:q.literal(`ai-sdk`).optional()});q.object({message_id:q.uuid(),metadata:Tl.optional(),role:fu.optional(),parts:du.optional(),format:q.literal(`ai-sdk`).optional(),behavior:q.enum([`interrupt`,`enqueue`,`none`]).optional()});const gu=q.enum([`enqueue`,`interrupt`,`append`]);q.object({chat_id:q.uuid(),behavior:gu.optional(),messages:q.array(hu).min(1)}),q.object({messages:q.array(mu)});var _u=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 X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/messages/${e}`);await X(t,204)}async get(e){let t=await this.client.request(`GET`,`/api/messages/${e}`);return await X(t,200),t.json()}async update(e){let t=await this.client.request(`PUT`,`/api/messages/${e.message_id}`,JSON.stringify(e));await X(t,200)}async send(e){let t=await this.client.request(`POST`,`/api/messages`,JSON.stringify(e));return await X(t,201),t.json()}};Cl.extend({chat_id:q.uuid()});const vu=q.object({id:q.uuid(),started_at:q.date(),agent_id:q.uuid(),agent_deployment_id:q.uuid().nullable(),chat_id:q.uuid(),step_count:q.number().int().positive(),status:zl.nullable(),error:q.string().nullable()});wl(vu);var yu=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 X(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 X(t,200),t.json()}};const bu=q.enum([`streaming`,`idle`,`error`,`interrupted`]),xu=q.enum([`private`,`organization`,`public`]),Su=q.object({id:q.uuid(),created_at:q.iso.datetime(),updated_at:q.iso.datetime(),created_by:q.uuid().nullable(),organization_id:q.uuid(),title:q.string().nullable(),visibility:xu,metadata:Tl,archived:q.boolean(),status:bu,error:q.string().nullable(),agent_deployment_id:q.uuid().nullable(),agent:Zl});q.enum([`websocket`,`sse`]);const Cu=q.object({organization_id:q.uuid(),title:q.string().optional(),visibility:xu.default(`private`).optional(),metadata:Tl.optional(),agent_id:q.uuid(),agent_deployment_id:q.uuid().optional(),messages:q.array(hu).optional()}),wu=Cu.extend({stream:q.literal(!0)}),Tu=Cu.extend({stream:q.literal(!1).optional()});q.union([wu,Tu]),q.union([Cl.extend({organization_id:q.uuid()}),Cl.extend({agent_id:q.uuid()})]);const Eu=Su.extend({messages:q.array(mu)});wl(Su);const Du=q.discriminatedUnion(`event`,[q.strictObject({event:q.literal(`chat.updated`),data:Su}),q.strictObject({event:q.literal(`message.created`),data:mu}),q.strictObject({event:q.literal(`message.updated`),data:mu}),q.strictObject({event:q.literal(`message.deleted`),data:q.object({id:q.uuid()})}),q.strictObject({event:q.literal(`message.chunk.added`),data:q.object({id:q.uuid(),chunk:q.custom()})})]),Ou=q.strictObject({event:q.literal(`chat.created`),data:Eu});var ku=class{constructor(e){this.client=e,this.runs=new yu(e),this.steps=new Hl(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 X(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=Dl(n,q.discriminatedUnion(`event`,[Du,Ou])),r=t.getReader(),{done:i,value:a}=await r.read();if(i)throw Error(`The stream ended before the chat.created event was received!`);if(a.event!==`chat.created`)throw Error(`Expected chat.created, got ${a.event}`);return r.releaseLock(),{...a.data,messages:a.data.messages,stream:t}}return n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e}`);return await X(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 X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/chats/${e}`);await X(t,204)}async stop(e){let t=await this.client.request(`POST`,`/api/chats/${e}/stop`);await X(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 X(n,200),Dl(n,Du)}streamWS(e,t){let n=this.client.websocket(`/api/chats/${e}/stream`),r=new Lc,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(()=>{})}),Ol(r.readable,Du)}};q.object({id:q.uuid(),organization_id:q.uuid(),role:tu,invited_by:q.uuid(),expires_at:q.date(),created_at:q.date(),updated_at:q.date(),reusable:q.boolean(),accepted_at:q.date().nullable(),email:q.string().email().nullable()}),q.object({organization_id:q.uuid(),role:tu,email:q.string().email().optional(),reusable:q.boolean().optional()}),q.object({organization_id:q.uuid()}),q.object({organization_id:q.uuid(),invite_id:q.uuid()}),q.object({code:q.string()}).extend({invite_id:q.uuid()});var Au=class{constructor(e){this.client=e}async create(e){let t=await this.client.request(`POST`,`/api/invites`,JSON.stringify(e));return await X(t,201),t.json()}async list(e){let t=await this.client.request(`GET`,`/api/invites?organization_id=${e.organization_id}`);return await X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/invites/${e.invite_id}`);await X(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 X(t,201),t.json()}},ju=class{constructor(e){this.chats=new ku(this),this.runs=new yu(this),this.agents=new $l(this),this.files=new eu(this),this.organizations=new su(this),this.invites=new Au(this),this.users=new lu(this),this.messages=new _u(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 Mc(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())}},Mu=jc({"../../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=Y(`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}})})}),Nu=jc({"../../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:()=>{}}})}),Pu=jc({"../../node_modules/ws/lib/buffer-util.js":((e,t)=>{let{EMPTY_BUFFER:n}=Nu(),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=Y(`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{}})}),Fu=jc({"../../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])}}}})}),Iu=jc({"../../node_modules/ws/lib/permessage-deflate.js":((e,t)=>{let n=Y(`zlib`),r=Pu(),i=Fu(),{kStatusCode:a}=Nu(),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)}})}),Lu=jc({"../../node_modules/ws/lib/validation.js":((e,t)=>{let{isUtf8:n}=Y(`buffer`),{hasBlob:r}=Nu(),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=Y(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})}),Ru=jc({"../../node_modules/ws/lib/receiver.js":((e,t)=>{let{Writable:n}=Y(`stream`),r=Iu(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Nu(),{concat:c,toArrayBuffer:l,unmask:u}=Pu(),{isValidStatusCode:d,isValidUTF8:f}=Lu(),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}}})}),zu=jc({"../../node_modules/ws/lib/sender.js":((e,t)=>{let{Duplex:n}=Y(`stream`),{randomFillSync:r}=Y(`crypto`),i=Iu(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Nu(),{isBlob:c,isValidStatusCode:l}=Lu(),{mask:u,toBuffer:d}=Pu(),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)}})}),Bu=jc({"../../node_modules/ws/lib/event-target.js":((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Nu(),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)}})}),Vu=jc({"../../node_modules/ws/lib/extension.js":((e,t)=>{let{tokenChars:n}=Lu();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}})}),Hu=jc({"../../node_modules/ws/lib/websocket.js":((e,t)=>{let n=Y(`events`),r=Y(`https`),i=Y(`http`),a=Y(`net`),o=Y(`tls`),{randomBytes:s,createHash:c}=Y(`crypto`),{Duplex:l,Readable:u}=Y(`stream`),{URL:d}=Y(`url`),f=Iu(),p=Ru(),m=zu(),{isBlob:h}=Lu(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=Nu(),{EventTarget:{addEventListener:w,removeEventListener:T}}=Bu(),{format:E,parse:D}=Vu(),{toBuffer:O}=Pu(),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`,L),i.on(`drain`,re),i.on(`error`,R),i.on(`message`,z),i.on(`ping`,ae),i.on(`pong`,oe),a.onerror=ce,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,B),t.on(`data`,ue),t.on(`end`,de),t.on(`error`,fe),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())}),le(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ne(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||_,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ne(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||_,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ne(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[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;te(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?F:P),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,te(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}`);te(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 te(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function P(e){return e.path=e.socketPath,a.connect(e)}function F(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(te,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ne(e,t,n){if(t){let n=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 L(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,ue),process.nextTick(se,n._socket),e===1005?n.close():n.close(e,t))}function re(){let e=this[S];e.isPaused||e._socket.resume()}function R(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,ue),process.nextTick(se,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function ie(){this[S].emitClose()}function z(e,t){this[S].emit(`message`,e,t)}function ae(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function oe(e){this[S].emit(`pong`,e)}function se(e){e.resume()}function ce(e){let t=this[S];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,le(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function le(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function B(){let e=this[S];this.removeListener(`close`,B),this.removeListener(`data`,ue),this.removeListener(`end`,de),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`,ie),e._receiver.on(`finish`,ie))}function ue(e){this[S]._receiver.write(e)||this.pause()}function de(){let e=this[S];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function fe(){let e=this[S];this.removeListener(`error`,fe),this.on(`error`,C),e&&(e._readyState=N.CLOSING,this.destroy())}})}),Uu=jc({"../../node_modules/ws/lib/stream.js":((e,t)=>{Hu();let{Duplex:n}=Y(`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})}),Wu=jc({"../../node_modules/ws/lib/subprotocol.js":((e,t)=>{let{tokenChars:n}=Lu();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}})}),Gu=jc({"../../node_modules/ws/lib/websocket-server.js":((e,t)=>{let n=Y(`events`),r=Y(`http`),{Duplex:i}=Y(`stream`),{createHash:a}=Y(`crypto`),o=Vu(),s=Iu(),c=Wu(),l=Hu(),{GUID:u,kWebSocket:d}=Nu(),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
21
+ Error message: ${Uc(t)}`,cause:t}),this[rl]=!0,this.value=e}static isInstance(e){return Hc.hasMarker(e,tl)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};rl=nl;var al=il;(({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 Jc({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`})();var ol=/"__proto__"\s*:/,sl=/"constructor"\s*:/;function cl(e){let t=JSON.parse(e);return typeof t!=`object`||!t||ol.test(e)===!1&&sl.test(e)===!1?t:ll(t)}function ll(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 ul(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return cl(e)}finally{Error.stackTraceLimit=t}}var dl=Symbol.for(`vercel.ai.validator`);function fl(e){return{[dl]:!0,validate:e}}function pl(e){return typeof e==`object`&&!!e&&dl in e&&e[dl]===!0&&`validate`in e}function ml(e){return pl(e)?e:hl(e)}function hl(e){return fl(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new al({value:t,cause:n.issues})}})}async function gl({value:e,schema:t}){let n=ml(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:al.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:al.wrap({value:e,cause:t}),rawValue:e}}}async function _l({text:e,schema:t}){try{let n=ul(e);return t==null?{success:!0,value:n,rawValue:n}:await gl({value:n,schema:t})}catch(t){return{success:!1,error:$c.isInstance(t)?t:new $c({text:e,cause:t}),rawValue:void 0}}}var{btoa:vl,atob:yl}=globalThis;function bl(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 X=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}`)}}},xl=K.object({per_page:K.number().int().positive().max(100).default(10).optional(),page:K.number().int().nonnegative().default(0).optional()}),Sl=e=>K.object({has_more:K.boolean(),items:K.array(e)}),Cl=K.object({limit:K.number().int().positive().max(100).default(10).optional(),cursor:K.string().optional()}),wl=e=>K.object({next_cursor:K.string().nullable(),items:K.array(e)}),Tl=K.any().nullable().refine(e=>e?Object.keys(e).length<=16:!0,{message:`Metadata must contain at most 16 keys`}),El=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i,Dl=(e,t)=>{let n=new Lc;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(n.writable).catch(e=>{}),Ol(n.readable,t)},Ol=(e,t)=>{let n=e.pipeThrough(new TransformStream({async transform(e,n){let r=await _l({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 bl(n)};K.union([K.object({agent_id:K.uuid(),deployment_id:K.uuid()}),K.object({agent_id:K.uuid(),deployment_number:K.number().int().positive()})]),K.object({agent_id:K.uuid(),deployment_id:K.uuid()});const kl=K.object({path:K.string(),id:K.uuid()}),Al=kl.or(K.object({path:K.string(),data:K.string().max(1024*1024*5)})),jl=K.enum([`production`,`preview`]);K.object({agent_id:K.uuid(),output_files:K.array(Al).optional(),source_files:K.array(Al).optional(),files:K.array(Al).optional(),target:jl,entrypoint:K.string().optional(),message:K.string().max(128).optional()}).transform(e=>e.files&&!e.output_files?{...e,output_files:e.files,files:void 0}:e);const Ml=K.object({id:K.uuid(),number:K.number().int().positive(),created_at:K.iso.datetime(),updated_at:K.iso.datetime(),created_by:K.uuid().nullable(),created_from:K.enum([`cli`]),agent_id:K.uuid(),source_files:K.array(kl),output_files:K.array(kl),status:K.enum([`success`,`failed`,`deploying`,`pending`]),target:jl,error_message:K.string().nullable(),user_message:K.string().nullable(),platform:K.enum([`lambda`]),platform_memory_mb:K.number().int().positive(),platform_region:K.string().nullable()});K.object({id:K.uuid(),created_at:K.string().datetime(),updated_at:K.string().datetime(),agent_id:K.uuid(),deployment_id:K.uuid(),level:K.enum([`log`,`info`,`warning`,`error`]),message:K.string()}),xl.extend({agent_id:K.uuid(),order:K.enum([`asc`,`desc`]).default(`asc`).optional()}),Sl(Ml);var Nl=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 X(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 X(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 X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);await X(t,200)}};K.object({agent_id:K.uuid(),target:jl.array().optional()}),K.object({id:K.uuid(),created_at:K.date(),updated_at:K.date(),created_by:K.uuid(),updated_by:K.uuid(),key:K.string(),value:K.string().nullable(),secret:K.boolean(),target:jl.array()});const Pl=K.object({key:K.string(),value:K.string(),secret:K.boolean(),target:jl.array().optional(),upsert:K.boolean().optional()});Pl.extend({agent_id:K.uuid()}),K.object({agent_id:K.uuid(),id:K.uuid()}),K.object({agent_id:K.uuid(),id:K.uuid(),key:K.string().optional(),value:K.string().optional(),secret:K.boolean().optional(),target:jl.array().default([`preview`,`production`]).optional()});var Fl=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 X(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 X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/env/${e.id}`);await X(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 X(t,200),t.json()}};const Il=K.object({id:K.string(),agent_id:K.uuid(),agent_deployment_id:K.uuid(),received_at:K.date(),request_method:K.string(),request_handler_location:K.string().nullable(),duration_ms:K.number().nullable(),error:K.string().nullable(),response_status:K.number().nullable()});Il.extend({request_headers:K.record(K.string(),K.string()),request_headers_redacted:K.boolean(),request_body:K.string().nullable(),request_body_redacted:K.boolean(),response_headers:K.record(K.string(),K.string()).nullable(),response_headers_redacted:K.boolean(),response_body:K.string().nullable(),response_body_redacted:K.boolean()}),Cl.extend({agent_id:K.string(),agent_deployment_id:K.number().optional()}),wl(Il);var Ll=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 X(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 X(n,200),n.json()}};Cl.extend({agent_id:K.uuid(),agent_deployment_id:K.uuid().optional()}),K.object({agent_id:K.uuid(),run_id:K.uuid()});var Rl=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 X(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 X(t,200),t.json()}};const zl=K.enum([`streaming`,`stalled`,`completed`,`interrupted`,`error`]),Bl=K.enum([`tool_call`,`queued_message`]),Vl=K.object({id:K.uuid(),number:K.number().int().positive(),chat_id:K.uuid(),chat_run_id:K.uuid(),agent_id:K.uuid(),agent_deployment_id:K.uuid(),started_at:K.string().datetime(),status:zl,error:K.string().nullable(),continuation_reason:Bl.nullable(),response_status:K.number().nullable(),response_message_id:K.uuid().nullable(),time_to_first_token_micros:K.number().nullable()});Vl.extend({heartbeat_at:K.date(),completed_at:K.date().nullable(),interrupted_at:K.date().nullable(),first_message_id:K.uuid().nullable(),last_message_id:K.uuid().nullable(),response_headers:K.record(K.string(),K.string()).nullable(),response_headers_redacted:K.boolean(),response_body:K.string().nullable(),response_body_redacted:K.boolean(),usage_model:K.string().nullable(),usage_total_input_tokens:K.number().nullable(),usage_total_output_tokens:K.number().nullable(),usage_total_tokens:K.number().nullable(),usage_total_cached_input_tokens:K.number().nullable(),usage_cost_usd:K.number().nullable()}),Cl.extend({chat_id:K.uuid(),run_id:K.uuid().optional()}),wl(Vl);var Hl=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 X(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 X(t,200),t.json()}};Cl.extend({agent_id:K.uuid(),agent_deployment_id:K.uuid().optional(),chat_id:K.uuid().optional(),run_id:K.uuid().optional(),status:zl.optional()}),wl(Vl);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 X(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 X(t,200),t.json()}};const Wl=K.object({type:K.literal(`eq`),key:K.string(),value:K.string()}),Gl=K.object({type:K.literal(`and`),get filters(){return K.array(K.union([Wl,Gl]))}});K.object({start_time:K.iso.datetime().pipe(K.coerce.date()),end_time:K.iso.datetime().pipe(K.coerce.date()),filters:K.string().transform(e=>JSON.parse(e)).pipe(Gl),limit:K.string().pipe(K.coerce.number().min(1).max(1e4)).optional()});var Kl=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 X(n,200),await n.json()}};G.object({start_time:G.iso.datetime().pipe(G.coerce.date()),end_time:G.iso.datetime().pipe(G.coerce.date()),message_pattern:G.string().optional(),filters:G.string().transform(e=>JSON.parse(e)).pipe(Gl).optional(),limit:G.string().pipe(G.coerce.number().min(1).max(1e4)).optional()});const ql=G.object({timestamp:G.iso.datetime().pipe(G.coerce.date()),message:G.string(),level:G.enum([`info`,`error`,`warn`])}),Jl=G.object({logs:G.array(ql)});var Yl=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 X(n,200);let r=await n.json();return Jl.parse(r)}};const Xl=K.enum([`private`,`public`]);K.object({organization_id:K.uuid(),name:K.string().regex(El),description:K.string().optional(),visibility:Xl.default(`private`).optional(),source_files:K.array(Al).optional(),output_files:K.array(Al).optional(),entrypoint:K.string().optional(),env:K.array(Pl).optional(),request_id:K.uuid().optional()});const Zl=K.object({id:K.uuid(),organization_id:K.uuid(),created_at:K.iso.datetime(),updated_at:K.iso.datetime(),created_by:K.uuid(),name:K.string().regex(El),description:K.string().nullable(),avatar_url:K.string().nullable(),visibility:Xl,active_deployment_id:K.uuid().nullable(),pinned:K.boolean().default(!1),request_url:K.url().nullable().describe(`The URL for the agent requests. Only visible to owners.`)});K.object({id:K.uuid(),name:K.string().regex(El).optional(),description:K.string().optional(),visibility:Xl.optional(),active_deployment_id:K.uuid().optional(),avatar_file_id:K.uuid().nullable().optional()}),xl.extend({organization_id:K.uuid().optional(),pinned:K.boolean().optional()}),Sl(Zl),K.object({agent_id:K.uuid(),input:K.string(),caret:K.number().optional(),selection:K.tuple([K.number(),K.number()]).optional(),chat_id:K.uuid().optional(),agent_deployment_id:K.uuid().optional()});const Ql=K.object({text:K.string(),caret:K.number().optional(),selection:K.tuple([K.number(),K.number()]).optional()});K.object({agent_id:K.uuid(),agent_deployment_id:K.uuid().optional(),selected:K.record(K.string(),K.string()).optional()}),K.object({agent_id:K.uuid(),start_time:K.iso.datetime().pipe(K.coerce.date()),end_time:K.iso.datetime().pipe(K.coerce.date())}),K.object({seconds:K.string()});var $l=class{constructor(e){this.client=e,this.deployments=new Nl(e),this.env=new Fl(e),this.webhook=new Ll(e),this.runs=new Rl(e),this.steps=new Ul(e),this.logs=new Yl(e),this.traces=new Kl(e)}async create(e){let t=await this.client.request(`POST`,`/api/agents`,JSON.stringify(e));return await X(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/agents/${e.id}`,JSON.stringify(e));return await X(t,200),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e}`);return await X(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 X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}`);await X(t,204)}async completions(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/completions`,JSON.stringify(e));if(await X(t,200),t.headers.get(`content-type`)===`application/json`){let e=await t.json();return bl(new ReadableStream({start(t){t.enqueue(e),t.close()}}))}return Dl(t,Ql)}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 X(n,200),n.json()}async pin(e){let t=await this.client.request(`POST`,`/api/agents/${e}/pin`);await X(t,204)}async unpin(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}/pin`);await X(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 X(n,200),n.json()}},eu=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 X(n,201),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/files/${e}`);return await X(t,200),new File([await t.blob()],``)}};const tu=K.enum([`owner`,`admin`,`billing_admin`,`member`]),nu=K.object({user_id:K.uuid(),organization_id:K.uuid(),role:tu,created_at:K.date(),updated_at:K.date()}),ru=K.object({id:K.uuid(),created_at:K.date(),updated_at:K.date(),display_name:K.string().nullable(),email:K.email(),avatar_url:K.url().nullable(),username:K.string()}),iu=nu.extend({user:ru});xl.extend({organization_id:K.uuid()}),Sl(iu),K.object({organization_id:K.uuid(),user_id:K.uuid()}),K.object({role:K.enum([`owner`,`admin`,`member`,`billing_admin`]).optional()}).extend({organization_id:K.uuid(),user_id:K.uuid()});var au=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 X(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 X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);await X(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 X(t,200),t.json()}},ou=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 X(t,200),t.json()}};K.object({id:K.uuid(),name:K.string(),created_at:K.date(),updated_at:K.date(),membership:nu.nullable(),members_url:K.url(),invites_url:K.url(),avatar_url:K.url().nullable()}),K.object({name:K.string().regex(El)}),K.object({name:K.string().max(100).optional(),avatar_file_id:K.string().nullable().optional(),avatar_url:K.string().url().nullable().optional()});var su=class{constructor(e){this.client=e,this.members=new au(e),this.agents=new ou(e)}async list(){let e=await this.client.request(`GET`,`/api/organizations`);return await X(e,200),e.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e}`);return await X(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/organizations`,JSON.stringify(e));return await X(t,201),t.json()}async update(e,t){let n=await this.client.request(`PATCH`,`/api/organizations/${e}`,JSON.stringify(t));return await X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e}`);await X(t,204)}};G.object({id:G.uuid(),created_at:G.date(),updated_at:G.date(),email:G.string().email(),email_verified:G.boolean(),display_name:G.string(),username:G.string(),organization_id:G.uuid(),avatar_url:G.string().url().nullable()}),G.object({display_name:G.string().max(100).optional(),username:G.string().regex(El).optional(),avatar_file_id:G.string().nullable().optional()});const cu=G.object({provider:G.enum([`github`,`google`]),provider_account_id:G.string()});G.object({github:G.array(cu),google:G.array(cu)});var lu=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 X(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/users/me`,JSON.stringify(e));return await X(t,200),t.json()}async accounts(){let e=await this.client.request(`GET`,`/api/users/me/accounts`);return await X(e,200),e.json()}async unlinkProvider(e,t){let n=await this.client.request(`DELETE`,`/api/users/me/accounts/${e}/${t}`);await X(n,204)}async delete(){let e=await this.client.request(`DELETE`,`/api/users/me`);await X(e,204)}};const uu=K.enum([`ai-sdk`]),du=K.array(K.custom()),fu=K.enum([`user`,`assistant`,`system`]),pu=K.object({id:K.uuid(),created_at:K.string().datetime(),chat_id:K.uuid(),metadata:Tl}).extend({format:K.literal(`ai-sdk`),parts:du,role:fu}),mu=K.discriminatedUnion(`format`,[pu]);Cl.extend({chat_id:K.uuid(),format:uu.default(`ai-sdk`).optional()}),wl(mu),K.object({chat_id:K.uuid(),message_id:K.uuid()});const hu=K.object({id:K.uuid().optional(),role:fu,parts:du,metadata:Tl.optional(),format:K.literal(`ai-sdk`).optional()});K.object({message_id:K.uuid(),metadata:Tl.optional(),role:fu.optional(),parts:du.optional(),format:K.literal(`ai-sdk`).optional(),behavior:K.enum([`interrupt`,`enqueue`,`none`]).optional()});const gu=K.enum([`enqueue`,`interrupt`,`append`]);K.object({chat_id:K.uuid(),behavior:gu.optional(),messages:K.array(hu).min(1)}),K.object({messages:K.array(mu)});var _u=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 X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/messages/${e}`);await X(t,204)}async get(e){let t=await this.client.request(`GET`,`/api/messages/${e}`);return await X(t,200),t.json()}async update(e){let t=await this.client.request(`PUT`,`/api/messages/${e.message_id}`,JSON.stringify(e));await X(t,200)}async send(e){let t=await this.client.request(`POST`,`/api/messages`,JSON.stringify(e));return await X(t,201),t.json()}};Cl.extend({chat_id:K.uuid()});const vu=K.object({id:K.uuid(),started_at:K.date(),agent_id:K.uuid(),agent_deployment_id:K.uuid().nullable(),chat_id:K.uuid(),step_count:K.number().int().positive(),status:zl.nullable(),error:K.string().nullable()});wl(vu);var yu=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 X(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 X(t,200),t.json()}};const bu=K.enum([`streaming`,`idle`,`error`,`interrupted`]),xu=K.enum([`private`,`organization`,`public`]),Su=K.object({id:K.uuid(),created_at:K.iso.datetime(),updated_at:K.iso.datetime(),created_by:K.uuid().nullable(),organization_id:K.uuid(),title:K.string().nullable(),visibility:xu,metadata:Tl,archived:K.boolean(),status:bu,error:K.string().nullable(),agent_deployment_id:K.uuid().nullable(),agent:Zl});K.enum([`websocket`,`sse`]);const Cu=K.object({organization_id:K.uuid(),title:K.string().optional(),visibility:xu.default(`private`).optional(),metadata:Tl.optional(),agent_id:K.uuid(),agent_deployment_id:K.uuid().optional(),messages:K.array(hu).optional()}),wu=Cu.extend({stream:K.literal(!0)}),Tu=Cu.extend({stream:K.literal(!1).optional()});K.union([wu,Tu]),K.union([Cl.extend({organization_id:K.uuid()}),Cl.extend({agent_id:K.uuid()})]);const Eu=Su.extend({messages:K.array(mu)});wl(Su);const Du=K.discriminatedUnion(`event`,[K.strictObject({event:K.literal(`chat.updated`),data:Su}),K.strictObject({event:K.literal(`message.created`),data:mu}),K.strictObject({event:K.literal(`message.updated`),data:mu}),K.strictObject({event:K.literal(`message.deleted`),data:K.object({id:K.uuid()})}),K.strictObject({event:K.literal(`message.chunk.added`),data:K.object({id:K.uuid(),chunk:K.custom()})})]),Ou=K.strictObject({event:K.literal(`chat.created`),data:Eu});var ku=class{constructor(e){this.client=e,this.runs=new yu(e),this.steps=new Hl(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 X(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=Dl(n,K.discriminatedUnion(`event`,[Du,Ou])),r=t.getReader(),{done:i,value:a}=await r.read();if(i)throw Error(`The stream ended before the chat.created event was received!`);if(a.event!==`chat.created`)throw Error(`Expected chat.created, got ${a.event}`);return r.releaseLock(),{...a.data,messages:a.data.messages,stream:t}}return n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e}`);return await X(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 X(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/chats/${e}`);await X(t,204)}async stop(e){let t=await this.client.request(`POST`,`/api/chats/${e}/stop`);await X(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 X(n,200),Dl(n,Du)}streamWS(e,t){let n=this.client.websocket(`/api/chats/${e}/stream`),r=new Lc,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(()=>{})}),Ol(r.readable,Du)}};K.object({id:K.uuid(),organization_id:K.uuid(),role:tu,invited_by:K.uuid(),expires_at:K.date(),created_at:K.date(),updated_at:K.date(),reusable:K.boolean(),accepted_at:K.date().nullable(),email:K.string().email().nullable()}),K.object({organization_id:K.uuid(),role:tu,email:K.string().email().optional(),reusable:K.boolean().optional()}),K.object({organization_id:K.uuid()}),K.object({organization_id:K.uuid(),invite_id:K.uuid()}),K.object({code:K.string()}).extend({invite_id:K.uuid()});var Au=class{constructor(e){this.client=e}async create(e){let t=await this.client.request(`POST`,`/api/invites`,JSON.stringify(e));return await X(t,201),t.json()}async list(e){let t=await this.client.request(`GET`,`/api/invites?organization_id=${e.organization_id}`);return await X(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/invites/${e.invite_id}`);await X(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 X(t,201),t.json()}},ju=class{constructor(e){this.chats=new ku(this),this.runs=new yu(this),this.agents=new $l(this),this.files=new eu(this),this.organizations=new su(this),this.invites=new Au(this),this.users=new lu(this),this.messages=new _u(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 Mc(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())}},Mu=jc({"../../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=Y(`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()}),ee=u.z.object({oldStart:u.z.number(),oldLines:u.z.number(),newStart:u.z.number(),newLines:u.z.number(),lines:u.z.array(w)}),T=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(ee)}),E=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(T)}),D=u.z.object({path:u.z.string(),status:u.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:u.z.boolean()}),O=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(T).optional()}),k=u.z.object({files:u.z.array(D),branch:u.z.string(),ahead:u.z.number(),behind:u.z.number(),timestamp:u.z.date(),sessionDiff:E.optional(),workingDirectoryDiff:E.optional(),newCommits:u.z.array(O),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()}),A=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()}),j={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:k};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 ee}}),Object.defineProperty(e,`DiffLineSchema`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`DiffSummarySchema`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`FileChangeEventSchema`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`FileDiffSchema`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(e,`GitCommitEventSchema`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,`GitFileStatusSchema`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`GitStatusEventSchema`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`NotificationSchema`,{enumerable:!0,get:function(){return j}}),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 A}}),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}})})}),Nu=jc({"../../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:()=>{}}})}),Pu=jc({"../../node_modules/ws/lib/buffer-util.js":((e,t)=>{let{EMPTY_BUFFER:n}=Nu(),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=Y(`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{}})}),Fu=jc({"../../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])}}}})}),Iu=jc({"../../node_modules/ws/lib/permessage-deflate.js":((e,t)=>{let n=Y(`zlib`),r=Pu(),i=Fu(),{kStatusCode:a}=Nu(),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)}})}),Lu=jc({"../../node_modules/ws/lib/validation.js":((e,t)=>{let{isUtf8:n}=Y(`buffer`),{hasBlob:r}=Nu(),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=Y(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})}),Ru=jc({"../../node_modules/ws/lib/receiver.js":((e,t)=>{let{Writable:n}=Y(`stream`),r=Iu(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=Nu(),{concat:c,toArrayBuffer:l,unmask:u}=Pu(),{isValidStatusCode:d,isValidUTF8:f}=Lu(),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}}})}),zu=jc({"../../node_modules/ws/lib/sender.js":((e,t)=>{let{Duplex:n}=Y(`stream`),{randomFillSync:r}=Y(`crypto`),i=Iu(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=Nu(),{isBlob:c,isValidStatusCode:l}=Lu(),{mask:u,toBuffer:d}=Pu(),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)}})}),Bu=jc({"../../node_modules/ws/lib/event-target.js":((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=Nu(),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)}})}),Vu=jc({"../../node_modules/ws/lib/extension.js":((e,t)=>{let{tokenChars:n}=Lu();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}})}),Hu=jc({"../../node_modules/ws/lib/websocket.js":((e,t)=>{let n=Y(`events`),r=Y(`https`),i=Y(`http`),a=Y(`net`),o=Y(`tls`),{randomBytes:s,createHash:c}=Y(`crypto`),{Duplex:l,Readable:u}=Y(`stream`),{URL:d}=Y(`url`),f=Iu(),p=Ru(),m=zu(),{isBlob:h}=Lu(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=Nu(),{EventTarget:{addEventListener:w,removeEventListener:ee}}=Bu(),{format:T,parse:E}=Vu(),{toBuffer:D}=Pu(),O=Symbol(`kAborted`),k=[8,13],A=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],j=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var M=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]),te(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`,I),i.on(`drain`,ie),i.on(`error`,L),i.on(`message`,R),i.on(`ping`,oe),i.on(`pong`,se),a.onerror=le,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,z),t.on(`data`,de),t.on(`end`,fe),t.on(`error`,pe),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){F(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())}),ue(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){re(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){re(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){re(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){F(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(M,`CONNECTING`,{enumerable:!0,value:A.indexOf(`CONNECTING`)}),Object.defineProperty(M.prototype,`CONNECTING`,{enumerable:!0,value:A.indexOf(`CONNECTING`)}),Object.defineProperty(M,`OPEN`,{enumerable:!0,value:A.indexOf(`OPEN`)}),Object.defineProperty(M.prototype,`OPEN`,{enumerable:!0,value:A.indexOf(`OPEN`)}),Object.defineProperty(M,`CLOSING`,{enumerable:!0,value:A.indexOf(`CLOSING`)}),Object.defineProperty(M.prototype,`CLOSING`,{enumerable:!0,value:A.indexOf(`CLOSING`)}),Object.defineProperty(M,`CLOSED`,{enumerable:!0,value:A.indexOf(`CLOSED`)}),Object.defineProperty(M.prototype,`CLOSED`,{enumerable:!0,value:A.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(M.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(M.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})}})}),M.prototype.addEventListener=w,M.prototype.removeEventListener=ee,t.exports=M;function te(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:k[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,!k.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${k.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;ne(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?P:N),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`]=T({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!j.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`,()=>{F(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[O]||(x=e._req=null,ne(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){F(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{let t=SyntaxError(`Invalid URL: ${i}`);ne(e,t);return}te(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||F(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==M.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){F(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+v).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){F(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){F(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){F(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=E(u)}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){F(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{F(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 ne(e,t){e._readyState=M.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function N(e){return e.path=e.socketPath,a.connect(e)}function P(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function F(e,t,n){e._readyState=M.CLOSING;let r=Error(n);Error.captureStackTrace(r,F),t.setHeader?(t[O]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ne,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function re(e,t,n){if(t){let n=h(t)?t.size:D(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${A[e.readyState]})`);process.nextTick(n,t)}}function I(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,de),process.nextTick(ce,n._socket),e===1005?n.close():n.close(e,t))}function ie(){let e=this[S];e.isPaused||e._socket.resume()}function L(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,de),process.nextTick(ce,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function ae(){this[S].emitClose()}function R(e,t){this[S].emit(`message`,e,t)}function oe(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function se(e){this[S].emit(`pong`,e)}function ce(e){e.resume()}function le(e){let t=this[S];t.readyState!==M.CLOSED&&(t.readyState===M.OPEN&&(t._readyState=M.CLOSING,ue(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ue(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function z(){let e=this[S];this.removeListener(`close`,z),this.removeListener(`data`,de),this.removeListener(`end`,fe),e._readyState=M.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`,ae),e._receiver.on(`finish`,ae))}function de(e){this[S]._receiver.write(e)||this.pause()}function fe(){let e=this[S];e._readyState=M.CLOSING,e._receiver.end(),this.end()}function pe(){let e=this[S];this.removeListener(`error`,pe),this.on(`error`,C),e&&(e._readyState=M.CLOSING,this.destroy())}})}),Uu=jc({"../../node_modules/ws/lib/stream.js":((e,t)=>{Hu();let{Duplex:n}=Y(`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})}),Wu=jc({"../../node_modules/ws/lib/subprotocol.js":((e,t)=>{let{tokenChars:n}=Lu();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}})}),Gu=jc({"../../node_modules/ws/lib/websocket-server.js":((e,t)=>{let n=Y(`events`),r=Y(`http`),{Duplex:i}=Y(`stream`),{createHash:a}=Y(`crypto`),o=Vu(),s=Iu(),c=Wu(),l=Hu(),{GUID:u,kWebSocket:d}=Nu(),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)}})}),Ku=jc({"../../node_modules/ws/index.js":((e,t)=>{let n=Hu();n.createWebSocketStream=Uu(),n.Server=Gu(),n.Receiver=Ru(),n.Sender=zu(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})}),qu=jc({"../../node_modules/@blink-sdk/compute-protocol/dist/server-BAzD0QDI.cjs":(e=>{var t,n,r,i;let a=Mu(),o=Y(`node:fs/promises`);o=a.__toESM(o);let s=Y(`module`);s=a.__toESM(s);let c=Y(`fs/promises`);c=a.__toESM(c);let l=Y(`child_process`);l=a.__toESM(l);let u=Ku();u=a.__toESM(u);let d=Y(`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?te(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return P(e);case`ascii`:return F(e);case`latin1`:case`iso-8859-1`:return I(e);case`windows-1252`:return ne(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function te(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 P(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function F(e){return String.fromCharCode(...e.map(e=>e&127))}function I(e){return String.fromCharCode(...e)}function ne(e){let t=``;for(let n of e)n>=128&&n<=159&&M[n]?t+=M[n]:t+=String.fromCharCode(n);return t}function L(e){return new DataView(e.buffer,e.byteOffset)}let re={len:1,get(e,t){return L(e).getUint8(t)},put(e,t,n){return L(e).setUint8(t,n),t+1}},R={len:2,get(e,t){return L(e).getUint16(t,!0)},put(e,t,n){return L(e).setUint16(t,n,!0),t+2}},ie={len:2,get(e,t){return L(e).getUint16(t)},put(e,t,n){return L(e).setUint16(t,n),t+2}},z={len:4,get(e,t){return L(e).getUint32(t,!0)},put(e,t,n){return L(e).setUint32(t,n,!0),t+4}},ae={len:4,get(e,t){return L(e).getUint32(t)},put(e,t,n){return L(e).setUint32(t,n),t+4}},oe={len:4,get(e,t){return L(e).getInt32(t)},put(e,t,n){return L(e).setInt32(t,n),t+4}},se={len:8,get(e,t){return L(e).getBigUint64(t,!0)},put(e,t,n){return L(e).setBigUint64(t,n,!0),t+8}};var ce=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)}},le=(0,s.createRequire)(`/`);try{le(`worker_threads`).Worker}catch{}var B=Uint8Array,ue=Uint16Array,de=Int32Array,fe=new B([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]),pe=new B([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]),me=new B([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),he=function(e,t){for(var n=new ue(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new de(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}},ge=he(fe,2),_e=ge.b,ve=ge.r;_e[28]=258,ve[258]=28;var ye=he(pe,0),be=ye.b;ye.r;for(var xe=new ue(32768),V=0;V<32768;++V){var Se=(V&43690)>>1|(V&21845)<<1;Se=(Se&52428)>>2|(Se&13107)<<2,Se=(Se&61680)>>4|(Se&3855)<<4,xe[V]=((Se&65280)>>8|(Se&255)<<8)>>1}for(var Ce=(function(e,t,n){for(var r=e.length,i=0,a=new ue(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new ue(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new ue(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[xe[d]>>c]=l}else for(s=new ue(r),i=0;i<r;++i)e[i]&&(s[i]=xe[o[e[i]-1]++]>>15-e[i]);return s}),we=new B(288),V=0;V<144;++V)we[V]=8;for(var V=144;V<256;++V)we[V]=9;for(var V=256;V<280;++V)we[V]=7;for(var V=280;V<288;++V)we[V]=8;for(var H=new B(32),V=0;V<32;++V)H[V]=5;var U=Ce(we,9,1),Te=Ce(H,5,1),W=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},G=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},K=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},q=function(e){return(e+7)/8|0},Ee=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new B(e.subarray(t,n))},De=[`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`],Oe=function(e,t,n){var r=Error(t||De[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Oe),!n)throw r;return r},ke=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new B(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new B(i*3));var l=function(e){var t=n.length;if(e>t){var r=new B(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=G(e,d,1);var v=G(e,d+1,3);if(d+=3,v)if(v==1)p=U,m=Te,h=9,g=5;else if(v==2){var y=G(e,d,31)+257,b=G(e,d+10,15)+4,x=y+G(e,d+5,31)+1;d+=14;for(var S=new B(x),C=new B(19),w=0;w<b;++w)C[me[w]]=G(e,d+w*3,7);d+=b*3;for(var T=W(C),E=(1<<T)-1,D=Ce(C,T,1),w=0;w<x;){var O=D[G(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+G(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+G(e,d,7),d+=3):k==18&&(j=11+G(e,d,127),d+=7);j--;)S[w++]=A}}var M=S.subarray(0,y),N=S.subarray(y);h=W(M),g=W(N),p=Ce(M,h,1),m=Ce(N,g,1)}else Oe(1);else{var k=q(d)+4,ee=e[k-4]|e[k-3]<<8,te=k+ee;if(te>i){c&&Oe(0);break}s&&l(f+ee),n.set(e.subarray(k,te),f),t.b=f+=ee,t.p=d=te*8,t.f=u;continue}if(d>_){c&&Oe(0);break}}s&&l(f+131072);for(var P=(1<<h)-1,F=(1<<g)-1,I=d;;I=d){var A=p[K(e,d)&P],ne=A>>4;if(d+=A&15,d>_){c&&Oe(0);break}if(A||Oe(2),ne<256)n[f++]=ne;else if(ne==256){I=d,p=null;break}else{var L=ne-254;if(ne>264){var w=ne-257,re=fe[w];L=G(e,d,(1<<re)-1)+_e[w],d+=re}var R=m[K(e,d)&F],ie=R>>4;R||Oe(3),d+=R&15;var N=be[ie];if(ie>3){var re=pe[ie];N+=K(e,d)&(1<<re)-1,d+=re}if(d>_){c&&Oe(0);break}s&&l(f+131072);var z=f+L;if(f<N){var ae=a-N,oe=Math.min(N,z);for(ae+f<0&&Oe(3);f<oe;++f)n[f]=r[ae+f]}for(;f<z;++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?Ee(n,0,f):n.subarray(0,f)},J=new B(0),Ae=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&Oe(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)},je=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},Me=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&Oe(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&Oe(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function Ne(e,t){return ke(e,{i:2},t&&t.out,t&&t.dictionary)}function Pe(e,t){var n=Ae(e);return n+8>e.length&&Oe(6,`invalid gzip data`),ke(e.subarray(n,-8),{i:2},t&&t.out||new B(je(e)),t&&t.dictionary)}function Fe(e,t){return ke(e.subarray(Me(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function Ie(e,t){return e[0]==31&&e[1]==139&&e[2]==8?Pe(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?Ne(e,t):Fe(e,t)}var Le=typeof TextDecoder<`u`&&new TextDecoder;try{Le.decode(J,{stream:!0})}catch{}var Re=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`:``)}})}),ze=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=Re(),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})}),Be=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=ze()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),Ve=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)}})}),He=a.__commonJS({"../../node_modules/supports-color/index.js":((e,t)=>{let n=Y(`os`),r=Y(`tty`),i=Ve(),{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)))}})}),Ue=a.__commonJS({"../../node_modules/debug/src/node.js":((e,t)=>{let n=Y(`tty`),r=Y(`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=He();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)}})}),Ku=jc({"../../node_modules/ws/index.js":((e,t)=>{let n=Hu();n.createWebSocketStream=Uu(),n.Server=Gu(),n.Receiver=Ru(),n.Sender=zu(),n.WebSocket=n,n.WebSocketServer=n.Server,t.exports=n})}),qu=jc({"../../node_modules/@blink-sdk/compute-protocol/dist/server-BAzD0QDI.cjs":(e=>{var t,n,r,i;let a=Mu(),o=Y(`node:fs/promises`);o=a.__toESM(o);let s=Y(`module`);s=a.__toESM(s);let c=Y(`fs/promises`);c=a.__toESM(c);let l=Y(`child_process`);l=a.__toESM(l);let u=Ku();u=a.__toESM(u);let d=Y(`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}},ee=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 T(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new ee(t):new w(t)}catch(t){if(t instanceof TypeError)return new ee(e.getReader());throw t}}var E=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()}},D=class extends E{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}},O=class extends E{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 k(e,t){let n=T(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new D(n,r)}function A(e,t){return new O(e,t)}let j={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:`Ÿ`},M={};for(let[e,t]of Object.entries(j))M[t]=Number.parseInt(e);function te(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?ne(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return N(e);case`ascii`:return P(e);case`latin1`:case`iso-8859-1`:return F(e);case`windows-1252`:return re(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function ne(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 N(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function P(e){return String.fromCharCode(...e.map(e=>e&127))}function F(e){return String.fromCharCode(...e)}function re(e){let t=``;for(let n of e)n>=128&&n<=159&&j[n]?t+=j[n]:t+=String.fromCharCode(n);return t}function I(e){return new DataView(e.buffer,e.byteOffset)}let ie={len:1,get(e,t){return I(e).getUint8(t)},put(e,t,n){return I(e).setUint8(t,n),t+1}},L={len:2,get(e,t){return I(e).getUint16(t,!0)},put(e,t,n){return I(e).setUint16(t,n,!0),t+2}},ae={len:2,get(e,t){return I(e).getUint16(t)},put(e,t,n){return I(e).setUint16(t,n),t+2}},R={len:4,get(e,t){return I(e).getUint32(t,!0)},put(e,t,n){return I(e).setUint32(t,n,!0),t+4}},oe={len:4,get(e,t){return I(e).getUint32(t)},put(e,t,n){return I(e).setUint32(t,n),t+4}},se={len:4,get(e,t){return I(e).getInt32(t)},put(e,t,n){return I(e).setInt32(t,n),t+4}},ce={len:8,get(e,t){return I(e).getBigUint64(t,!0)},put(e,t,n){return I(e).setBigUint64(t,n,!0),t+8}};var le=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return te(n,this.encoding)}},ue=(0,s.createRequire)(`/`);try{ue(`worker_threads`).Worker}catch{}var z=Uint8Array,de=Uint16Array,fe=Int32Array,pe=new z([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]),me=new z([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]),he=new z([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ge=function(e,t){for(var n=new de(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new fe(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}},_e=ge(pe,2),ve=_e.b,ye=_e.r;ve[28]=258,ye[258]=28;var be=ge(me,0),xe=be.b;be.r;for(var Se=new de(32768),B=0;B<32768;++B){var Ce=(B&43690)>>1|(B&21845)<<1;Ce=(Ce&52428)>>2|(Ce&13107)<<2,Ce=(Ce&61680)>>4|(Ce&3855)<<4,Se[B]=((Ce&65280)>>8|(Ce&255)<<8)>>1}for(var we=(function(e,t,n){for(var r=e.length,i=0,a=new de(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new de(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new de(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[Se[d]>>c]=l}else for(s=new de(r),i=0;i<r;++i)e[i]&&(s[i]=Se[o[e[i]-1]++]>>15-e[i]);return s}),Te=new z(288),B=0;B<144;++B)Te[B]=8;for(var B=144;B<256;++B)Te[B]=9;for(var B=256;B<280;++B)Te[B]=7;for(var B=280;B<288;++B)Te[B]=8;for(var V=new z(32),B=0;B<32;++B)V[B]=5;var H=we(Te,9,1),Ee=we(V,5,1),U=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},G=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},K=function(e){return(e+7)/8|0},q=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new z(e.subarray(t,n))},De=[`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`],Oe=function(e,t,n){var r=Error(t||De[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Oe),!n)throw r;return r},ke=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new z(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new z(i*3));var l=function(e){var t=n.length;if(e>t){var r=new z(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=H,m=Ee,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 z(x),C=new z(19),w=0;w<b;++w)C[he[w]]=W(e,d+w*3,7);d+=b*3;for(var ee=U(C),T=(1<<ee)-1,E=we(C,ee,1),w=0;w<x;){var D=E[W(e,d,T)];d+=D&15;var O=D>>4;if(O<16)S[w++]=O;else{var k=0,A=0;for(O==16?(A=3+W(e,d,3),d+=2,k=S[w-1]):O==17?(A=3+W(e,d,7),d+=3):O==18&&(A=11+W(e,d,127),d+=7);A--;)S[w++]=k}}var j=S.subarray(0,y),M=S.subarray(y);h=U(j),g=U(M),p=we(j,h,1),m=we(M,g,1)}else Oe(1);else{var O=K(d)+4,te=e[O-4]|e[O-3]<<8,ne=O+te;if(ne>i){c&&Oe(0);break}s&&l(f+te),n.set(e.subarray(O,ne),f),t.b=f+=te,t.p=d=ne*8,t.f=u;continue}if(d>_){c&&Oe(0);break}}s&&l(f+131072);for(var N=(1<<h)-1,P=(1<<g)-1,F=d;;F=d){var k=p[G(e,d)&N],re=k>>4;if(d+=k&15,d>_){c&&Oe(0);break}if(k||Oe(2),re<256)n[f++]=re;else if(re==256){F=d,p=null;break}else{var I=re-254;if(re>264){var w=re-257,ie=pe[w];I=W(e,d,(1<<ie)-1)+ve[w],d+=ie}var L=m[G(e,d)&P],ae=L>>4;L||Oe(3),d+=L&15;var M=xe[ae];if(ae>3){var ie=me[ae];M+=G(e,d)&(1<<ie)-1,d+=ie}if(d>_){c&&Oe(0);break}s&&l(f+131072);var R=f+I;if(f<M){var oe=a-M,se=Math.min(M,R);for(oe+f<0&&Oe(3);f<se;++f)n[f]=r[oe+f]}for(;f<R;++f)n[f]=n[f-M]}}t.l=p,t.p=F,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?q(n,0,f):n.subarray(0,f)},J=new z(0),Ae=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&Oe(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)},je=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},Me=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&Oe(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&Oe(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function Ne(e,t){return ke(e,{i:2},t&&t.out,t&&t.dictionary)}function Pe(e,t){var n=Ae(e);return n+8>e.length&&Oe(6,`invalid gzip data`),ke(e.subarray(n,-8),{i:2},t&&t.out||new z(je(e)),t&&t.dictionary)}function Fe(e,t){return ke(e.subarray(Me(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function Ie(e,t){return e[0]==31&&e[1]==139&&e[2]==8?Pe(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?Ne(e,t):Fe(e,t)}var Le=typeof TextDecoder<`u`&&new TextDecoder;try{Le.decode(J,{stream:!0})}catch{}var Re=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`:``)}})}),ze=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=Re(),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})}),Be=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=ze()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),Ve=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)}})}),He=a.__commonJS({"../../node_modules/supports-color/index.js":((e,t)=>{let n=Y(`os`),r=Y(`tty`),i=Ve(),{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)))}})}),Ue=a.__commonJS({"../../node_modules/debug/src/node.js":((e,t)=>{let n=Y(`tty`),r=Y(`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=He();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
27
27
  `).join(`
28
28
  `+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=o()+n+` `+e[0]}function o(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function s(...t){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...t)+`
29
29
  `)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=ze()(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)}})}),We=a.__commonJS({"../../node_modules/debug/src/index.js":((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=Be():t.exports=Ue()})});let Ge={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Ke={get(e){return R.get(e,6),{signature:z.get(e,0),compressedSize:z.get(e,8),uncompressedSize:z.get(e,12)}},len:16},qe={get(e){let t=R.get(e,6);return{signature:z.get(e,0),minVersion:R.get(e,4),dataDescriptor:!!(t&8),compressedMethod:R.get(e,8),compressedSize:z.get(e,18),uncompressedSize:z.get(e,22),filenameLength:R.get(e,26),extraFieldLength:R.get(e,28),filename:null}},len:30},Je={get(e){return{signature:z.get(e,0),nrOfThisDisk:R.get(e,4),nrOfThisDiskWithTheStart:R.get(e,6),nrOfEntriesOnThisDisk:R.get(e,8),nrOfEntriesOfSize:R.get(e,10),sizeOfCd:z.get(e,12),offsetOfStartOfCd:z.get(e,16),zipFileCommentLength:R.get(e,20)}},len:22},Ye={get(e){let t=R.get(e,8);return{signature:z.get(e,0),minVersion:R.get(e,6),dataDescriptor:!!(t&8),compressedMethod:R.get(e,10),compressedSize:z.get(e,20),uncompressedSize:z.get(e,24),filenameLength:R.get(e,28),extraFieldLength:R.get(e,30),fileCommentLength:R.get(e,32),relativeOffsetOfLocalHeader:z.get(e,42),filename:null}},len:46};var Xe=a.__toESM(We(),1);function Ze(e){let t=new Uint8Array(z.len);return z.put(t,0,e),t}let Qe=(0,Xe.default)(`tokenizer:inflate`),$e=256*1024,et=Ze(Ge.DataDescriptor),tt=Ze(Ge.EndOfCentralDirectory);var nt=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array($e)}async isZip(){return await this.peekSignature()===Ge.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(z)}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]===tt[0]&&n[r+1]===tt[1]&&n[r+2]===tt[2]&&n[r+3]===tt[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){Qe(`Cannot reading central-directory without random-read support`);return}Qe(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Qe(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(Je,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(Ye);if(t.signature!==Ge.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new ce(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),Qe(`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=$e;Qe(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===$e;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=rt(this.syncBuffer.subarray(0,n),et);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)}Qe(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,it(e),r.handler)}else r.handler?(Qe(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(Qe(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(Qe(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(Ke)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Ke.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);Qe(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let r=Ie(t);return n(r)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(z);if(e===Ge.LocalFileHeader){let e=await this.tokenizer.readToken(qe);return e.filename=await this.tokenizer.readToken(new ce(e.filenameLength,`utf-8`)),e}if(e===Ge.CentralFileHeader)return!1;throw e===3759263696?Error(`Encrypted ZIP`):Error(`Unexpected signature`)}};function rt(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 it(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 at(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 ot(e){return[...e].map(e=>e.charCodeAt(0))}function st(e,t=0){let n=Number.parseInt(new ce(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 ct={get:(e,t)=>e[t+3]&127|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},lt=4100;async function ut(e,t){return new pt(t).fromBuffer(e)}function dt(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 ft(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 pt=class{constructor(e){this.detectConfident=async e=>{if(this.buffer=new Uint8Array(lt),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(ct);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 nt(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=dt(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=dt(e))}else{n=n.slice(0,Math.max(0,r));let e=n.lastIndexOf(`"`),i=n.slice(Math.max(0,e+1));t=dt(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),ft(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:ft(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:ft(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:ft(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:ft(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:ft(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(re),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:at(i),len:at(a)}}async function r(t){for(;t>0;){let r=await n();if(r.id===17026)return(await e.readToken(new ce(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 ce(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 ce(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(oe),type:await e.readToken(new ce(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 ce(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(se))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),r=n.size-24;if(ft(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),ft(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(ft(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 ce(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})&&st(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(lt),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=lt}=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 ft(this.buffer,e,t)}checkString(e,t){return this.check(ot(e),t)}async readTiffTag(e){let t=await this.tokenizer.readToken(e?ie:R);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?ie:R);for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t=(e?ie:R).get(this.buffer,2),n=(e?ae:z).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?ie:R).get(this.buffer,8),n=(e?ie:R).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`}}}},mt=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${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})()))})}),ht=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=`
30
+ `).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})}),We=a.__commonJS({"../../node_modules/debug/src/index.js":((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=Be():t.exports=Ue()})});let Ge={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Ke={get(e){return L.get(e,6),{signature:R.get(e,0),compressedSize:R.get(e,8),uncompressedSize:R.get(e,12)}},len:16},qe={get(e){let t=L.get(e,6);return{signature:R.get(e,0),minVersion:L.get(e,4),dataDescriptor:!!(t&8),compressedMethod:L.get(e,8),compressedSize:R.get(e,18),uncompressedSize:R.get(e,22),filenameLength:L.get(e,26),extraFieldLength:L.get(e,28),filename:null}},len:30},Je={get(e){return{signature:R.get(e,0),nrOfThisDisk:L.get(e,4),nrOfThisDiskWithTheStart:L.get(e,6),nrOfEntriesOnThisDisk:L.get(e,8),nrOfEntriesOfSize:L.get(e,10),sizeOfCd:R.get(e,12),offsetOfStartOfCd:R.get(e,16),zipFileCommentLength:L.get(e,20)}},len:22},Ye={get(e){let t=L.get(e,8);return{signature:R.get(e,0),minVersion:L.get(e,6),dataDescriptor:!!(t&8),compressedMethod:L.get(e,10),compressedSize:R.get(e,20),uncompressedSize:R.get(e,24),filenameLength:L.get(e,28),extraFieldLength:L.get(e,30),fileCommentLength:L.get(e,32),relativeOffsetOfLocalHeader:R.get(e,42),filename:null}},len:46};var Xe=a.__toESM(We(),1);function Ze(e){let t=new Uint8Array(R.len);return R.put(t,0,e),t}let Qe=(0,Xe.default)(`tokenizer:inflate`),$e=256*1024,et=Ze(Ge.DataDescriptor),tt=Ze(Ge.EndOfCentralDirectory);var nt=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array($e)}async isZip(){return await this.peekSignature()===Ge.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(R)}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]===tt[0]&&n[r+1]===tt[1]&&n[r+2]===tt[2]&&n[r+3]===tt[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){Qe(`Cannot reading central-directory without random-read support`);return}Qe(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Qe(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(Je,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(Ye);if(t.signature!==Ge.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new le(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),Qe(`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=$e;Qe(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===$e;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=rt(this.syncBuffer.subarray(0,n),et);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)}Qe(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,it(e),r.handler)}else r.handler?(Qe(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(Qe(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(Qe(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(Ke)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Ke.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);Qe(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let r=Ie(t);return n(r)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(R);if(e===Ge.LocalFileHeader){let e=await this.tokenizer.readToken(qe);return e.filename=await this.tokenizer.readToken(new le(e.filenameLength,`utf-8`)),e}if(e===Ge.CentralFileHeader)return!1;throw e===3759263696?Error(`Encrypted ZIP`):Error(`Unexpected signature`)}};function rt(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 it(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 at(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 ot(e){return[...e].map(e=>e.charCodeAt(0))}function st(e,t=0){let n=Number.parseInt(new le(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 ct={get:(e,t)=>e[t+3]&127|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},lt=4100;async function ut(e,t){return new pt(t).fromBuffer(e)}function dt(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 ft(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 pt=class{constructor(e){this.detectConfident=async e=>{if(this.buffer=new Uint8Array(lt),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(ct);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 nt(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=dt(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=dt(e))}else{n=n.slice(0,Math.max(0,r));let e=n.lastIndexOf(`"`),i=n.slice(Math.max(0,e+1));t=dt(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),ft(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:ft(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:ft(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:ft(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:ft(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:ft(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(ie),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:at(i),len:at(a)}}async function r(t){for(;t>0;){let r=await n();if(r.id===17026)return(await e.readToken(new le(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 le(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 le(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(se),type:await e.readToken(new le(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 le(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(ce))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),r=n.size-24;if(ft(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),ft(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(ft(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 le(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})&&st(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(lt),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(A(t,this.tokenizerOptions))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){let t=await k(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=lt}=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 ft(this.buffer,e,t)}checkString(e,t){return this.check(ot(e),t)}async readTiffTag(e){let t=await this.tokenizer.readToken(e?ae:L);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?ae:L);for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t=(e?ae:L).get(this.buffer,2),n=(e?oe:R).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?ae:L).get(this.buffer,8),n=(e?ae:L).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`}}}},mt=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${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})()))})}),ht=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 ee 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 T(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(E(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]);E(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=ee;let T=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 E(e){return 0<=e&&e<256}T=r([i(0,h.IBufferService)],T)},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?``:`${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})})()})}),gt=a.__toESM(mt(),1),_t=a.__toESM(ht(),1),vt=(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=yt(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 _t.default.Terminal({allowProposedApi:!0,convertEol:!0,scrollback:e.SCROLLBACK,cols:e.COLUMNS,rows:e.ROWS}),o=new gt.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 yt=(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 bt=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}}})}),xt=a.__commonJS({"../../node_modules/fast-fifo/index.js":((e,t)=>{let n=bt();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}}})}),St=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 te(e,t){return b(e).readDoubleBE(t)}function P(e,t){return b(e).readFloatBE(t)}function F(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:te,readFloatBE:P,readUInt32BE:F,readInt32BE:I}})}),Ct=a.__commonJS({"../../node_modules/text-decoder/lib/pass-through-decoder.js":((e,t)=>{let n=St();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})}),wt=a.__commonJS({"../../node_modules/text-decoder/lib/utf8-decoder.js":((e,t)=>{let n=St();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}}})}),Tt=a.__commonJS({"../../node_modules/text-decoder/index.js":((e,t)=>{let n=Ct(),r=wt();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)}}})}),Et=a.__commonJS({"../../node_modules/streamx/index.js":((e,t)=>{let{EventEmitter:n}=Y(`events`),r=Error(`Stream was destroyed`),i=Error(`Premature close`),a=xt(),o=Tt(),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 te=c^A;c^w;let P=c^N,F=16|C,I=c^F,ne=m|O,L=14|ne;ee&536870847;let re=A|h;re&I;let R=33587215;u|16399;let ie=m|143;u|143,u|16398,h|1,M|8388623,E|D,E|C;let z=270794767;T|C,C|j,O|134217742;let ae=Symbol.asyncIterator||Symbol(`asyncIterator`);var oe=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:r,byteLength:i,byteLengthWritable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||i||Ae,this.map=r||n,this.afterWrite=fe.bind(this),this.afterUpdateNextTick=he.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&z)===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&z)===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(ue.bind(this));return}if((e._duplexState&14)==4){(e._duplexState&re)===0&&(e._duplexState|=F,e._destroy(de.bind(this)));return}(e._duplexState&R)===1&&(e._duplexState=(e._duplexState|F)&l,e._open(_e.bind(this)))}continueUpdate(){return(this.stream._duplexState&A)===0?!1:(this.stream._duplexState&=te,!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))}},se=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:r,byteLength:i,byteLengthReadable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||i||Ae,this.map=r||n,this.pipeTo=null,this.afterRead=pe.bind(this),this.afterUpdateNextTick=me.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 le(this.stream,e,t),t&&this.stream.on(`error`,je),K(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,je),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,B.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&ie)===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&ie)===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&L)===ne&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){(e._duplexState&re)===0&&(e._duplexState|=F,e._destroy(de.bind(this)));return}(e._duplexState&R)===1&&(e._duplexState=(e._duplexState|F)&l,e._open(_e.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))}},ce=class{constructor(e){this.data=null,this.afterTransform=ve.bind(e),this.afterFinal=null}},le=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 B(){this.stream._duplexState|=512,this.updateCallback()}function ue(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=O,t.emit(`finish`)),(t._duplexState&L)===ne&&(t._duplexState|=4),t._duplexState&=402391039,(t._duplexState&w)===0?this.update():this.updateNextTick()}function de(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 fe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&ge(this.drains),(t._duplexState&6553615)===D&&(t._duplexState&=532676607,(t._duplexState&k)===k&&t.emit(`drain`)),this.updateCallback()}function pe(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=S),this.updateCallback()}function me(){this.stream._duplexState&32||(this.stream._duplexState&=x,this.update())}function he(){(this.stream._duplexState&w)===0&&(this.stream._duplexState&=te,this.update())}function ge(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function _e(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 ve(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function ye(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 be=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,Me.bind(this))),this.on(`newListener`,ye)}_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())}},xe=class e extends be{constructor(e){super(e),this._duplexState|=O|131073,this._readableState=new se(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||W;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(Oe(t))return t;if(t[ae])return this._fromAsyncIterator(t[ae](),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}[ae](){let e=this,t=null,n=null,i=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,a),this.on(`close`,o),{[ae](){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})})})}}},V=class extends be{constructor(e){super(e),this._duplexState|=1|m,this._writableState=new oe(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&=P,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return(e._duplexState&146800654)!=0}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(Ne(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&j?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},Se=class extends xe{constructor(e){super(e),this._duplexState=1|this._duplexState&_,this._writableState=new oe(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&=P,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}},Ce=class extends Se{constructor(e){super(e),this._transformState=new ce(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(H.bind(this))}},we=class extends Ce{};function H(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function U(...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],K(a)?a.pipe(o,l):(c(a,!0,e>1,l),a.pipe(o)),a=o;if(r){let e=!1,t=K(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 W(e){return e}function G(e){return!!e._readableState||!!e._writableState}function K(e){return typeof e._duplexState==`number`&&G(e)}function q(e){return!!e._readableState&&e._readableState.ended}function Ee(e){return!!e._writableState&&e._writableState.ended}function De(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===r?null:n}function Oe(e){return K(e)&&e.readable}function ke(e){return(e._duplexState&1)!=1||(e._duplexState&re)!==0}function J(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Ae(e){return J(e)?e.byteLength:1024}function je(){}function Me(){this.destroy(Error(`Stream aborted.`))}function Ne(e){return e._writev!==V.prototype._writev&&e._writev!==Se.prototype._writev}t.exports={pipeline:Te,pipelinePromise:U,isStream:G,isStreamx:K,isEnded:q,isFinished:Ee,isDisturbed:ke,getStreamError:De,Stream:be,Writable:V,Readable:xe,Duplex:Se,Transform:Ce,PassThrough:we}})}),Dt=a.__commonJS({"../../node_modules/tar-stream/headers.js":(e=>{let t=St(),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})})()})}),gt=a.__toESM(mt(),1),_t=a.__toESM(ht(),1),vt=(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=yt(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 _t.default.Terminal({allowProposedApi:!0,convertEol:!0,scrollback:e.SCROLLBACK,cols:e.COLUMNS,rows:e.ROWS}),o=new gt.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 yt=(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 bt=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}}})}),xt=a.__commonJS({"../../node_modules/fast-fifo/index.js":((e,t)=>{let n=bt();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}}})}),St=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 ee(e,t,n){return b(e).writeUInt32LE(t,n)}function T(e,t,n){return b(e).writeInt32LE(t,n)}function E(e,t){return b(e).readDoubleLE(t)}function D(e,t){return b(e).readFloatLE(t)}function O(e,t){return b(e).readUInt32LE(t)}function k(e,t){return b(e).readInt32LE(t)}function A(e,t,n){return b(e).writeDoubleBE(t,n)}function j(e,t,n){return b(e).writeFloatBE(t,n)}function M(e,t,n){return b(e).writeUInt32BE(t,n)}function te(e,t,n){return b(e).writeInt32BE(t,n)}function ne(e,t){return b(e).readDoubleBE(t)}function N(e,t){return b(e).readFloatBE(t)}function P(e,t){return b(e).readUInt32BE(t)}function F(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:ee,writeInt32LE:T,readDoubleLE:E,readFloatLE:D,readUInt32LE:O,readInt32LE:k,writeDoubleBE:A,writeFloatBE:j,writeUInt32BE:M,writeInt32BE:te,readDoubleBE:ne,readFloatBE:N,readUInt32BE:P,readInt32BE:F}})}),Ct=a.__commonJS({"../../node_modules/text-decoder/lib/pass-through-decoder.js":((e,t)=>{let n=St();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})}),wt=a.__commonJS({"../../node_modules/text-decoder/lib/utf8-decoder.js":((e,t)=>{let n=St();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}}})}),Tt=a.__commonJS({"../../node_modules/text-decoder/index.js":((e,t)=>{let n=Ct(),r=wt();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)}}})}),Et=a.__commonJS({"../../node_modules/streamx/index.js":((e,t)=>{let{EventEmitter:n}=Y(`events`),r=Error(`Stream was destroyed`),i=Error(`Premature close`),a=xt(),o=Tt(),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,ee=4<<18,T=8<<18,E=16<<18,D=32<<18,O=64<<18,k=128<<18,A=256<<18,j=512<<18,M=1024<<18;c^(C|A);let te=c^ee;c^(C|j),c^E,c^T;let ne=c^k;c^w;let N=c^M,P=16|C,F=c^P,re=m|D,I=14|re;te&536870847;let ie=k|h;ie&F;let L=33587215;u|16399;let ae=m|143;u|143,u|16398,h|1,j|8388623,T|E,T|C;let R=270794767;ee|C,C|A,D|134217742;let oe=Symbol.asyncIterator||Symbol(`asyncIterator`);var se=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:r,byteLength:i,byteLengthWritable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||i||Ae,this.map=r||n,this.afterWrite=pe.bind(this),this.afterUpdateNextTick=ge.bind(this)}get ended(){return(this.stream._duplexState&D)!==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|=T,!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|j)&te}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&R)===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&R)===T;){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)===j){e._duplexState|=C,e._final(de.bind(this));return}if((e._duplexState&14)==4){(e._duplexState&ie)===0&&(e._duplexState|=P,e._destroy(fe.bind(this)));return}(e._duplexState&L)===1&&(e._duplexState=(e._duplexState|P)&l,e._open(ve.bind(this)))}continueUpdate(){return(this.stream._duplexState&k)===0?!1:(this.stream._duplexState&=ne,!0)}updateCallback(){(this.stream._duplexState&35127311)===ee?this.update():this.updateNextTick()}updateNextTick(){(this.stream._duplexState&k)===0&&(this.stream._duplexState|=k,(this.stream._duplexState&w)===0&&s(this.afterUpdateNextTick))}},ce=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:r,byteLength:i,byteLengthReadable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||i||Ae,this.map=r||n,this.pipeTo=null,this.afterRead=me.bind(this),this.afterUpdateNextTick=he.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 ue(this.stream,e,t),t&&this.stream.on(`error`,je),G(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,je),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,z.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&ae)===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&ae)===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&I)===re&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){(e._duplexState&ie)===0&&(e._duplexState|=P,e._destroy(fe.bind(this)));return}(e._duplexState&L)===1&&(e._duplexState=(e._duplexState|P)&l,e._open(ve.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))}},le=class{constructor(e){this.data=null,this.afterTransform=ye.bind(e),this.afterFinal=null}},ue=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 z(){this.stream._duplexState|=512,this.updateCallback()}function de(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=D,t.emit(`finish`)),(t._duplexState&I)===re&&(t._duplexState|=4),t._duplexState&=402391039,(t._duplexState&w)===0?this.update():this.updateNextTick()}function fe(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 pe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&_e(this.drains),(t._duplexState&6553615)===E&&(t._duplexState&=532676607,(t._duplexState&O)===O&&t.emit(`drain`)),this.updateCallback()}function me(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=S),this.updateCallback()}function he(){this.stream._duplexState&32||(this.stream._duplexState&=x,this.update())}function ge(){(this.stream._duplexState&w)===0&&(this.stream._duplexState&=ne,this.update())}function _e(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function ve(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=ee),t.emit(`open`)),t._duplexState&=F,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function ye(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function be(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|=O,this._writableState.updateNextTick())}var xe=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,Me.bind(this))),this.on(`newListener`,be)}_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())}},Se=class e extends xe{constructor(e){super(e),this._duplexState|=D|131073,this._readableState=new ce(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||U;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(Oe(t))return t;if(t[oe])return this._fromAsyncIterator(t[oe](),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}[oe](){let e=this,t=null,n=null,i=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,a),this.on(`close`,o),{[oe](){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})})})}}},B=class extends xe{constructor(e){super(e),this._duplexState|=1|m,this._writableState=new se(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|=M}uncork(){this._duplexState&=N,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return(e._duplexState&146800654)!=0}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(Ne(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&A?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}},Ce=class extends Se{constructor(e){super(e),this._duplexState=1|this._duplexState&_,this._writableState=new se(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=M}uncork(){this._duplexState&=N,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}},we=class extends Ce{constructor(e){super(e),this._transformState=new le(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(V.bind(this))}},Te=class extends we{};function V(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function H(...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],G(a)?a.pipe(o,l):(c(a,!0,e>1,l),a.pipe(o)),a=o;if(r){let e=!1,t=G(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 U(e){return e}function W(e){return!!e._readableState||!!e._writableState}function G(e){return typeof e._duplexState==`number`&&W(e)}function K(e){return!!e._readableState&&e._readableState.ended}function q(e){return!!e._writableState&&e._writableState.ended}function De(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===r?null:n}function Oe(e){return G(e)&&e.readable}function ke(e){return(e._duplexState&1)!=1||(e._duplexState&ie)!==0}function J(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Ae(e){return J(e)?e.byteLength:1024}function je(){}function Me(){this.destroy(Error(`Stream aborted.`))}function Ne(e){return e._writev!==B.prototype._writev&&e._writev!==Ce.prototype._writev}t.exports={pipeline:Ee,pipelinePromise:H,isStream:W,isStreamx:G,isEnded:K,isFinished:q,isDisturbed:ke,getStreamError:De,Stream:xe,Writable:B,Readable:Se,Duplex:Ce,Transform:we,PassThrough:Te}})}),Dt=a.__commonJS({"../../node_modules/tar-stream/headers.js":(e=>{let t=St(),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
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}})}),Ot=a.__commonJS({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=Et(),a=xt(),o=St(),s=Dt(),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}})}),kt=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=Y(`fs`).constants||n}catch{t.exports=n}})}),At=a.__commonJS({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=Et(),a=St(),o=kt(),s=Dt(),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)}})}),jt=a.__commonJS({"../../node_modules/tar-stream/index.js":(e=>{e.extract=Ot(),e.pack=At()})}),Mt=a.__toESM(jt(),1);let Nt=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=Mt.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{}}})},Pt=(e,t)=>e.length<=t?e:e.slice(e.length-t),Ft=(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 It=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 vt({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=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=Ft(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 Nt(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await c.readFile(t.payload.path),r=await ut(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
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=Pt(this.processManager.readANSIOutput(i.pid),64e3),f=Ft(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 It}})})}),Ju=jc({"../../node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{Mu(),e.Server=qu().Server})}),Yu=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}=Ju(),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 Xu=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}({}),Zu=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}({});Xu.REQUEST,q.string(),Xu.PROXY_INIT,q.object({method:q.string(),headers:q.record(q.string(),q.string()),url:q.string()}),Xu.PROXY_BODY,q.instanceof(Uint8Array),Xu.PROXY_WEBSOCKET_MESSAGE,q.object({type:q.enum([`text`,`binary`]),data:q.instanceof(Uint8Array)}),Xu.PROXY_WEBSOCKET_CLOSE,q.object({code:q.number().optional(),reason:q.string().optional()}),Zu.RESPONSE,q.string(),Zu.NOTIFICATION,q.string(),Zu.PROXY_INIT,q.object({status_code:q.number(),status_message:q.string(),headers:q.record(q.string(),q.string())}),Zu.PROXY_DATA,q.instanceof(Uint8Array),Zu.PROXY_WEBSOCKET_MESSAGE,q.instanceof(Uint8Array),Zu.PROXY_WEBSOCKET_CLOSE,q.object({code:q.number(),reason:q.string()}),Xu.PROXY_INIT,q.string(),q.record(q.string(),q.string()),q.string(),q.object({command:q.string(),args:q.array(q.string()),env:q.record(q.string(),q.string()).optional(),cwd:q.string().optional()}),q.object({pid:q.number(),data:q.string()}),q.object({pid:q.number(),output_idle_timeout_ms:q.number().optional(),timeout_ms:q.number().optional()}),q.object({include_dead:q.boolean().optional()}),q.object({pid:q.number(),start_line:q.number().optional(),end_line:q.number().optional()}),q.object({pid:q.number(),signal:q.string().optional()}),q.object({env:q.record(q.string(),q.string())}),q.object({path:q.string(),line_start:q.number().optional(),line_end:q.number().optional()}),q.object({path:q.string(),content:q.string(),base64:q.boolean().optional(),mode:q.number().optional()}),q.object({path:q.string()}),q.object({path:q.string()}),q.object({path:q.string()});const Qu=q.object({pid:q.number(),command:q.string(),args:q.array(q.string()),title:q.string().optional(),cwd:q.string(),env:q.record(q.string(),q.string()),exit_code:q.number().optional(),exit_signal:q.number().optional(),duration_ms:q.number().optional(),output_total_lines:q.number()});Qu.extend({ansi_output:q.string(),plain_output:q.object({lines:q.array(q.string()),total_lines:q.number()})}),q.object({pid:q.number()}),q.object({}),q.object({processes:q.array(Qu)}),q.object({lines:q.array(q.string()),total_lines:q.number(),duration_ms:q.number(),exit_code:q.number().optional(),exit_signal:q.number().optional()}),q.object({}),q.object({}),q.object({total_lines:q.number(),lines_read:q.number(),start_line:q.number(),content:q.string(),mime_type:q.string()}),q.object({}),q.object({entries:q.array(q.object({name:q.string(),type:q.enum([`file`,`directory`,`symlink`])}))}),q.object({}),q.object({deployment_id:q.string()});const $u=q.object({type:q.enum([`create`,`update`,`delete`]),path:q.string()}),ed=q.object({type:q.enum([`context`,`added`,`deleted`]),content:q.string(),oldLineNumber:q.number().optional(),newLineNumber:q.number().optional()}),td=q.object({oldStart:q.number(),oldLines:q.number(),newStart:q.number(),newLines:q.number(),lines:q.array(ed)}),nd=q.object({path:q.string(),status:q.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:q.string().optional(),insertions:q.number(),deletions:q.number(),chunks:q.array(td)}),rd=q.object({totalFiles:q.number(),totalInsertions:q.number(),totalDeletions:q.number(),netChange:q.number(),startHash:q.string().optional(),currentHash:q.string().optional(),timespan:q.number(),files:q.array(nd)}),id=q.object({path:q.string(),status:q.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:q.boolean()}),ad=q.object({hash:q.string(),shortHash:q.string(),message:q.string(),author:q.string(),email:q.string(),date:q.date(),timestamp:q.date(),filesChanged:q.number(),insertions:q.number(),deletions:q.number(),commitDiff:q.array(nd).optional()});q.object({files:q.array(id),branch:q.string(),ahead:q.number(),behind:q.number(),timestamp:q.date(),sessionDiff:rd.optional(),workingDirectoryDiff:rd.optional(),newCommits:q.array(ad),currentCommit:q.object({hash:q.string(),shortHash:q.string(),message:q.string(),author:q.string(),date:q.date()}).optional(),diffSkipped:q.boolean().optional(),payloadTruncated:q.boolean().optional(),estimatedSizeKB:q.number().optional()}),q.object({debounceDelay:q.number().optional(),gitStatusInterval:q.number().optional(),ignoreDotfiles:q.boolean().optional(),ignored:q.array(q.string()).optional(),watchGit:q.boolean().optional(),includeDiffs:q.boolean().optional(),maxDiffFiles:q.number().optional(),maxPayloadSizeKB:q.number().optional(),truncateLargeDiffs:q.boolean().optional()}),q.object({status:Qu}),q.object({pid:q.number(),output:q.string()}),q.object({changes:q.array($u)});var od=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)}}}};q.object({}),q.object({id:q.string(),token:q.string()});var sd=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await X(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new od({send:e=>t.send(e)})}},cd=class{constructor(e){this.client=e,this.compute=new sd(this.client)}},ld=class extends ju{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new Yu(this),this.tools=new cd(this)}},ud=e((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})),dd=e((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})),fd=e((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})),pd=e((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 a=r(i(`os`)),o=r(i(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:a,path:o,process}})),md=e(((e,t)=>{var n=fd(),r=pd();t.exports=n.Adapt(r.adapter).OSPaths})),hd=n({default:()=>vd}),gd,_d,vd,yd=t((()=>{gd=o(md()),_d=gd.default,vd=_d})),bd=e((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},o=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var s=r(i(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:o((yd(),a(hd))).default,path:s,process}})),xd=e(((e,t)=>{var n=dd(),r=bd();t.exports=n.Adapt(r.adapter).XDG})),Sd=n({default:()=>wd}),Cd,wd,Td=t((()=>{Cd=o(xd()),r(Sd,o(xd())),wd=Cd.default})),Ed=e((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},o=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var s=r(i(`path`)),c=o((Td(),a(Sd)));e.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=(i!=null&&i.main?i.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:s,process,xdg:c.default}})),Dd=o(e(((e,t)=>{var n=ud(),r=Ed();t.exports=n.Adapt(r.adapter).XDGAppPaths}))()).default;const Od=(e=0)=>t=>`\u001B[${t+e}m`,kd=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,Ad=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,Z={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(Z.modifier);const jd=Object.keys(Z.color),Md=Object.keys(Z.bgColor);[...jd,...Md];function Nd(){let e=new Map;for(let[t,n]of Object.entries(Z)){for(let[t,r]of Object.entries(n))Z[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=Z[t],e.set(r[0],r[1]);Object.defineProperty(Z,t,{value:n,enumerable:!1})}return Object.defineProperty(Z,`codes`,{value:e,enumerable:!1}),Z.color.close=`\x1B[39m`,Z.bgColor.close=`\x1B[49m`,Z.color.ansi=Od(),Z.color.ansi256=kd(),Z.color.ansi16m=Ad(),Z.bgColor.ansi=Od(10),Z.bgColor.ansi256=kd(10),Z.bgColor.ansi16m=Ad(10),Object.defineProperties(Z,{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=>Z.rgbToAnsi256(...Z.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)=>Z.ansi256ToAnsi(Z.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>Z.ansi256ToAnsi(Z.hexToAnsi256(e)),enumerable:!1}}),Z}var Pd=Nd();function Fd(e,t=globalThis.Deno?globalThis.Deno.args:J.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:Q}=J;let Id;Fd(`no-color`)||Fd(`no-colors`)||Fd(`color=false`)||Fd(`color=never`)?Id=0:(Fd(`color`)||Fd(`colors`)||Fd(`color=true`)||Fd(`color=always`))&&(Id=1);function Ld(){if(`FORCE_COLOR`in Q)return Q.FORCE_COLOR===`true`?1:Q.FORCE_COLOR===`false`?0:Q.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(Q.FORCE_COLOR,10),3)}function Rd(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function zd(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=Ld();r!==void 0&&(Id=r);let i=n?Id:r;if(i===0)return 0;if(n){if(Fd(`color=16m`)||Fd(`color=full`)||Fd(`color=truecolor`))return 3;if(Fd(`color=256`))return 2}if(`TF_BUILD`in Q&&`AGENT_NAME`in Q)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(Q.TERM===`dumb`)return a;if(J.platform===`win32`){let e=Me.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in Q)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in Q)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in Q)||Q.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in Q)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Q.TEAMCITY_VERSION)?1:0;if(Q.COLORTERM===`truecolor`||Q.TERM===`xterm-kitty`||Q.TERM===`xterm-ghostty`||Q.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in Q){let e=Number.parseInt((Q.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(Q.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(Q.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Q.TERM)||`COLORTERM`in Q?1:a}function Bd(e,t={}){let n=zd(e,{streamIsTTY:e&&e.isTTY,...t});return Rd(n)}var Vd={stdout:Bd({isTTY:Ne.isatty(1)}),stderr:Bd({isTTY:Ne.isatty(2)})};function Hd(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 Ud(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
- `:`
41
- `)+n,i=r+1,r=e.indexOf(`
42
- `,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:Wd,stderr:Gd}=Vd,Kd=Symbol(`GENERATOR`),qd=Symbol(`STYLER`),Jd=Symbol(`IS_EMPTY`),Yd=[`ansi`,`ansi`,`ansi256`,`ansi16m`],Xd=Object.create(null),Zd=(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=Wd?Wd.level:0;e.level=t.level===void 0?n:t.level},Qd=e=>{let t=(...e)=>e.join(` `);return Zd(t,e),Object.setPrototypeOf(t,$d.prototype),t};function $d(e){return Qd(e)}Object.setPrototypeOf($d.prototype,Function.prototype);for(let[e,t]of Object.entries(Pd))Xd[e]={get(){let n=rf(this,nf(t.open,t.close,this[qd]),this[Jd]);return Object.defineProperty(this,e,{value:n}),n}};Xd.visible={get(){let e=rf(this,this[qd],!0);return Object.defineProperty(this,`visible`,{value:e}),e}};const ef=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?Pd[n].ansi16m(...r):t===`ansi256`?Pd[n].ansi256(Pd.rgbToAnsi256(...r)):Pd[n].ansi(Pd.rgbToAnsi(...r)):e===`hex`?ef(`rgb`,t,n,...Pd.hexToRgb(...r)):Pd[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){Xd[e]={get(){let{level:t}=this;return function(...n){let r=nf(ef(e,Yd[t],`color`,...n),Pd.color.close,this[qd]);return rf(this,r,this[Jd])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);Xd[t]={get(){let{level:t}=this;return function(...n){let r=nf(ef(e,Yd[t],`bgColor`,...n),Pd.bgColor.close,this[qd]);return rf(this,r,this[Jd])}}}}const tf=Object.defineProperties(()=>{},{...Xd,level:{enumerable:!0,get(){return this[Kd].level},set(e){this[Kd].level=e}}}),nf=(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}},rf=(e,t,n)=>{let r=(...e)=>af(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,tf),r[Kd]=e,r[qd]=t,r[Jd]=n,r},af=(e,t)=>{if(e.level<=0||!t)return e[Jd]?``: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=Hd(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
43
- `);return a!==-1&&(t=Ud(t,i,r,a)),r+t+i};Object.defineProperties($d.prototype,Xd);const sf=$d();$d({level:Gd?Gd.level:0});var cf=sf,lf=e(((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`}})),uf=e(((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}));lf(),uf();function df({onlyFirst:e=!1}={}){let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}df();function ff(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var pf={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}})(pf);var mf=pf.exports;ff(mf),ff(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 hf=(e=0)=>t=>`\x1B[${t+e}m`,gf=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,_f=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,$={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($.modifier);const vf=Object.keys($.color),yf=Object.keys($.bgColor);[...vf,...yf];function bf(){let e=new Map;for(let[t,n]of Object.entries($)){for(let[t,r]of Object.entries(n))$[t]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[t]=$[t],e.set(r[0],r[1]);Object.defineProperty($,t,{value:n,enumerable:!1})}return Object.defineProperty($,`codes`,{value:e,enumerable:!1}),$.color.close=`\x1B[39m`,$.bgColor.close=`\x1B[49m`,$.color.ansi=hf(),$.color.ansi256=gf(),$.color.ansi16m=_f(),$.bgColor.ansi=hf(10),$.bgColor.ansi256=gf(10),$.bgColor.ansi16m=_f(10),Object.defineProperties($,{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=>$.rgbToAnsi256(...$.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)=>$.ansi256ToAnsi($.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>$.ansi256ToAnsi($.hexToAnsi256(e)),enumerable:!1}}),$}bf();const xf={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 Sf(e,t){if(typeof e==`string`)return xf.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Sf(n,t))return!0;return!1}globalThis.process.platform.startsWith(`win`),Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty;var Cf=o(uf(),1);lf();function wf(){return J.platform===`win32`?!!J.env.CI||!!J.env.WT_SESSION||!!J.env.TERMINUS_SUBLIME||J.env.ConEmuTask===`{cmd::Cmder}`||J.env.TERM_PROGRAM===`Terminus-Sublime`||J.env.TERM_PROGRAM===`vscode`||J.env.TERM===`xterm-256color`||J.env.TERM===`alacritty`||J.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:J.env.TERM!==`linux`}const Tf=wf(),Ef=(e,t)=>Tf?e:t,Df=Ef(`◇`,`o`),Of=Ef(`│`,`|`),kf=Ef(`●`,`•`),Af=Ef(`◆`,`*`),jf=Ef(`▲`,`!`),Mf=Ef(`■`,`x`),Nf={message:(e=``,{symbol:t=Cf.default.gray(Of)}={})=>{let n=[`${Cf.default.gray(Of)}`];if(e){let[r,...i]=e.split(`
44
- `);n.push(`${t} ${r}`,...i.map(e=>`${Cf.default.gray(Of)} ${e}`))}process.stdout.write(`${n.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=Pt(this.processManager.readANSIOutput(i.pid),64e3),f=Ft(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 It}})})}),Ju=jc({"../../node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{Mu(),e.Server=qu().Server})}),Yu=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}=Ju(),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 Xu=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}({}),Zu=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}({});Xu.REQUEST,K.string(),Xu.PROXY_INIT,K.object({method:K.string(),headers:K.record(K.string(),K.string()),url:K.string()}),Xu.PROXY_BODY,K.instanceof(Uint8Array),Xu.PROXY_WEBSOCKET_MESSAGE,K.object({type:K.enum([`text`,`binary`]),data:K.instanceof(Uint8Array)}),Xu.PROXY_WEBSOCKET_CLOSE,K.object({code:K.number().optional(),reason:K.string().optional()}),Zu.RESPONSE,K.string(),Zu.NOTIFICATION,K.string(),Zu.PROXY_INIT,K.object({status_code:K.number(),status_message:K.string(),headers:K.record(K.string(),K.string())}),Zu.PROXY_DATA,K.instanceof(Uint8Array),Zu.PROXY_WEBSOCKET_MESSAGE,K.instanceof(Uint8Array),Zu.PROXY_WEBSOCKET_CLOSE,K.object({code:K.number(),reason:K.string()}),Xu.PROXY_INIT,K.string(),K.record(K.string(),K.string()),K.string(),K.object({command:K.string(),args:K.array(K.string()),env:K.record(K.string(),K.string()).optional(),cwd:K.string().optional()}),K.object({pid:K.number(),data:K.string()}),K.object({pid:K.number(),output_idle_timeout_ms:K.number().optional(),timeout_ms:K.number().optional()}),K.object({include_dead:K.boolean().optional()}),K.object({pid:K.number(),start_line:K.number().optional(),end_line:K.number().optional()}),K.object({pid:K.number(),signal:K.string().optional()}),K.object({env:K.record(K.string(),K.string())}),K.object({path:K.string(),line_start:K.number().optional(),line_end:K.number().optional()}),K.object({path:K.string(),content:K.string(),base64:K.boolean().optional(),mode:K.number().optional()}),K.object({path:K.string()}),K.object({path:K.string()}),K.object({path:K.string()});const Qu=K.object({pid:K.number(),command:K.string(),args:K.array(K.string()),title:K.string().optional(),cwd:K.string(),env:K.record(K.string(),K.string()),exit_code:K.number().optional(),exit_signal:K.number().optional(),duration_ms:K.number().optional(),output_total_lines:K.number()});Qu.extend({ansi_output:K.string(),plain_output:K.object({lines:K.array(K.string()),total_lines:K.number()})}),K.object({pid:K.number()}),K.object({}),K.object({processes:K.array(Qu)}),K.object({lines:K.array(K.string()),total_lines:K.number(),duration_ms:K.number(),exit_code:K.number().optional(),exit_signal:K.number().optional()}),K.object({}),K.object({}),K.object({total_lines:K.number(),lines_read:K.number(),start_line:K.number(),content:K.string(),mime_type:K.string()}),K.object({}),K.object({entries:K.array(K.object({name:K.string(),type:K.enum([`file`,`directory`,`symlink`])}))}),K.object({}),K.object({deployment_id:K.string()});const $u=K.object({type:K.enum([`create`,`update`,`delete`]),path:K.string()}),ed=K.object({type:K.enum([`context`,`added`,`deleted`]),content:K.string(),oldLineNumber:K.number().optional(),newLineNumber:K.number().optional()}),td=K.object({oldStart:K.number(),oldLines:K.number(),newStart:K.number(),newLines:K.number(),lines:K.array(ed)}),nd=K.object({path:K.string(),status:K.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:K.string().optional(),insertions:K.number(),deletions:K.number(),chunks:K.array(td)}),rd=K.object({totalFiles:K.number(),totalInsertions:K.number(),totalDeletions:K.number(),netChange:K.number(),startHash:K.string().optional(),currentHash:K.string().optional(),timespan:K.number(),files:K.array(nd)}),id=K.object({path:K.string(),status:K.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:K.boolean()}),ad=K.object({hash:K.string(),shortHash:K.string(),message:K.string(),author:K.string(),email:K.string(),date:K.date(),timestamp:K.date(),filesChanged:K.number(),insertions:K.number(),deletions:K.number(),commitDiff:K.array(nd).optional()});K.object({files:K.array(id),branch:K.string(),ahead:K.number(),behind:K.number(),timestamp:K.date(),sessionDiff:rd.optional(),workingDirectoryDiff:rd.optional(),newCommits:K.array(ad),currentCommit:K.object({hash:K.string(),shortHash:K.string(),message:K.string(),author:K.string(),date:K.date()}).optional(),diffSkipped:K.boolean().optional(),payloadTruncated:K.boolean().optional(),estimatedSizeKB:K.number().optional()}),K.object({debounceDelay:K.number().optional(),gitStatusInterval:K.number().optional(),ignoreDotfiles:K.boolean().optional(),ignored:K.array(K.string()).optional(),watchGit:K.boolean().optional(),includeDiffs:K.boolean().optional(),maxDiffFiles:K.number().optional(),maxPayloadSizeKB:K.number().optional(),truncateLargeDiffs:K.boolean().optional()}),K.object({status:Qu}),K.object({pid:K.number(),output:K.string()}),K.object({changes:K.array($u)});var od=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)}}}};K.object({}),K.object({id:K.string(),token:K.string()});var sd=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await X(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new od({send:e=>t.send(e)})}},cd=class{constructor(e){this.client=e,this.compute=new sd(this.client)}},ld=class extends ju{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new Yu(this),this.tools=new cd(this)}},ud=e(((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`}})),dd=e(((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}));ud(),dd();function fd({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`)}fd();function pd(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var md={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}})(md);var hd=md.exports;pd(hd),pd(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 gd=(e=0)=>t=>`\x1B[${t+e}m`,_d=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,vd=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,Z={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(Z.modifier);const yd=Object.keys(Z.color),bd=Object.keys(Z.bgColor);[...yd,...bd];function xd(){let e=new Map;for(let[t,n]of Object.entries(Z)){for(let[t,r]of Object.entries(n))Z[t]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[t]=Z[t],e.set(r[0],r[1]);Object.defineProperty(Z,t,{value:n,enumerable:!1})}return Object.defineProperty(Z,`codes`,{value:e,enumerable:!1}),Z.color.close=`\x1B[39m`,Z.bgColor.close=`\x1B[49m`,Z.color.ansi=gd(),Z.color.ansi256=_d(),Z.color.ansi16m=vd(),Z.bgColor.ansi=gd(10),Z.bgColor.ansi256=_d(10),Z.bgColor.ansi16m=vd(10),Object.defineProperties(Z,{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=>Z.rgbToAnsi256(...Z.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)=>Z.ansi256ToAnsi(Z.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>Z.ansi256ToAnsi(Z.hexToAnsi256(e)),enumerable:!1}}),Z}xd();const Sd={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 Cd(e,t){if(typeof e==`string`)return Sd.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Cd(n,t))return!0;return!1}globalThis.process.platform.startsWith(`win`),Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty,Object.defineProperty;var wd=o(dd(),1);ud();function Td(){return J.platform===`win32`?!!J.env.CI||!!J.env.WT_SESSION||!!J.env.TERMINUS_SUBLIME||J.env.ConEmuTask===`{cmd::Cmder}`||J.env.TERM_PROGRAM===`Terminus-Sublime`||J.env.TERM_PROGRAM===`vscode`||J.env.TERM===`xterm-256color`||J.env.TERM===`alacritty`||J.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:J.env.TERM!==`linux`}const Ed=Td(),Dd=(e,t)=>Ed?e:t,Od=Dd(`◇`,`o`),kd=Dd(`│`,`|`),Ad=Dd(`●`,`•`),jd=Dd(`◆`,`*`),Md=Dd(`▲`,`!`),Nd=Dd(`■`,`x`),Pd={message:(e=``,{symbol:t=wd.default.gray(kd)}={})=>{let n=[`${wd.default.gray(kd)}`];if(e){let[r,...i]=e.split(`
40
+ `);n.push(`${t} ${r}`,...i.map(e=>`${wd.default.gray(kd)} ${e}`))}process.stdout.write(`${n.join(`
45
41
  `)}
46
- `)},info:e=>{Nf.message(e,{symbol:Cf.default.blue(kf)})},success:e=>{Nf.message(e,{symbol:Cf.default.green(Af)})},step:e=>{Nf.message(e,{symbol:Cf.default.green(Df)})},warn:e=>{Nf.message(e,{symbol:Cf.default.yellow(jf)})},warning:e=>{Nf.warn(e)},error:e=>{Nf.message(e,{symbol:Cf.default.red(Mf)})}},Pf=`${Cf.default.gray(Of)} `,Ff={message:async(e,{symbol:t=Cf.default.gray(Of)}={})=>{process.stdout.write(`${Cf.default.gray(Of)}
42
+ `)},info:e=>{Pd.message(e,{symbol:wd.default.blue(Ad)})},success:e=>{Pd.message(e,{symbol:wd.default.green(jd)})},step:e=>{Pd.message(e,{symbol:wd.default.green(Od)})},warn:e=>{Pd.message(e,{symbol:wd.default.yellow(Md)})},warning:e=>{Pd.warn(e)},error:e=>{Pd.message(e,{symbol:wd.default.red(Nd)})}},Fd=`${wd.default.gray(kd)} `,Id={message:async(e,{symbol:t=wd.default.gray(kd)}={})=>{process.stdout.write(`${wd.default.gray(kd)}
47
43
  ${t} `);let n=3;for await(let t of e){t=t.replace(/\n/g,`
48
- ${Pf}`),t.includes(`
49
- `)&&(n=3+oe(t.slice(t.lastIndexOf(`
50
- `))).length);let e=oe(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
51
- ${Pf}${t.trimStart()}`),n=3+oe(t.trimStart()).length)}process.stdout.write(`
52
- `)},info:e=>Ff.message(e,{symbol:Cf.default.blue(kf)}),success:e=>Ff.message(e,{symbol:Cf.default.green(Af)}),step:e=>Ff.message(e,{symbol:Cf.default.green(Df)}),warn:e=>Ff.message(e,{symbol:Cf.default.yellow(jf)}),warning:e=>Ff.warn(e),error:e=>Ff.message(e,{symbol:Cf.default.red(Mf)})};let If;function Lf(){try{return F.statSync(`/.dockerenv`),!0}catch{return!1}}function Rf(){try{return F.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function zf(){return If===void 0&&(If=Lf()||Rf()),If}let Bf;const Vf=()=>{try{return F.statSync(`/run/.containerenv`),!0}catch{return!1}};function Hf(){return Bf===void 0&&(Bf=Vf()||zf()),Bf}const Uf=()=>{if(J.platform!==`linux`)return!1;if(Me.release().toLowerCase().includes(`microsoft`))return!Hf();try{return F.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Hf():!1}catch{return!1}};var Wf=J.env.__IS_WSL_TEST__?Uf:Uf();const Gf=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Re.access(n,ze.F_OK),r=!0}catch{}if(!r)return e;let i=await Re.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}})(),Kf=async()=>`${await Gf()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,qf=async()=>Wf?Kf():`${J.env.SYSTEMROOT||J.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Jf(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 Yf=ae(Le);async function Xf(){if(J.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Yf(`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 Zf=ae(Le);async function Qf(e,{humanReadableOutput:t=!0,signal:n}={}){if(J.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Zf(`osascript`,[`-e`,e,r],i);return a.trim()}async function $f(e){return Qf(`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 ep=ae(Le),tp={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 np=class extends Error{};async function rp(e=ep){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 np(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=tp[r];if(!i)throw new np(`Unknown browser ID: ${r}`);return i}const ip=ae(Le),ap=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function op(){if(J.platform===`darwin`){let e=await Xf();return{name:await $f(e),id:e}}if(J.platform===`linux`){let{stdout:e}=await ip(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:ap(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(J.platform===`win32`)return rp();throw Error(`Only macOS, Linux, and Windows are supported`)}const sp=ae(Ie.execFile),cp=De.dirname(ie(import.meta.url)),lp=De.join(cp,`xdg-open`),{platform:up,arch:dp}=J;async function fp(){let e=await qf(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=te.from(t,`utf16le`).toString(`base64`),{stdout:r}=await sp(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const pp=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},mp=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return pp(e.app,t=>mp({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return pp(t,t=>mp({...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=Wf?await fp():await op();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),mp({...e,app:{name:vp[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(up===`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(up===`win32`||Wf&&!Hf()&&!t){r=await qf(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Wf||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=te.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!cp||cp===`/`,t=!1;try{await Re.access(lp,ze.X_OK),t=!0}catch{}r=J.versions.electron??(up===`android`||e||!t)?`xdg-open`:lp}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}up===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Ie.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},hp=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return mp({...t,target:e})};function gp(e){if(typeof e==`string`||Array.isArray(e))return e;let{[dp]:t}=e;if(!t)throw Error(`${dp} is not supported`);return t}function _p({[up]:e},{wsl:t}){if(t&&Wf)return gp(t);if(!e)throw Error(`${up} is not supported`);return gp(e)}const vp={};Jf(vp,`chrome`,()=>_p({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`]}})),Jf(vp,`brave`,()=>_p({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`]}})),Jf(vp,`firefox`,()=>_p({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Jf(vp,`edge`,()=>_p({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Jf(vp,`browser`,()=>`browser`),Jf(vp,`browserPrivate`,()=>`browserPrivate`);var yp=hp;async function bp(e,t=void 0){try{(await yp(e)).once(`error`,n=>{console.log(cf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(cf.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function xp(e){let t=e||wp();if(I(t)){let e=L(t,`utf8`);return JSON.parse(e).token}}function Sp(e,t){let n=t||wp();I(Oe(n))||ne(Oe(n),{recursive:!0}),R(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function Cp(e){let t=e||wp();I(t)&&re(t)}function wp(){let e=Dd(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return ke(e[0],`auth.json`)}function Tp(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=G(),[s,c]=G(()=>xp(i)),[l,u]=G(),d=W(n),f=W(r);U(()=>{d.current=n,f.current=r},[n,r]);let p=H(async()=>{u(void 0);try{let e=xp(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ld({baseURL:`https://blink.coder.com`});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=H(async()=>{u(void 0);try{let e=new ld,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();Sp(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=H(()=>{Cp(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return U(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}let Ep=Promise.resolve();var Dp=class{constructor(e){this.printLog=e}setPrintLog(e){this.printLog=e}error(e,...t){Ep=Ep.then(()=>this.printLog(`error`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}log(e,...t){Ep=Ep.then(()=>this.printLog(`log`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}flush(){return Ep}};const Op=we(void 0);function kp(e){let{directory:t,logger:n,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e,logger:new Dp(async()=>{})}:e,o=Te(()=>A(t),[t]),[s,c]=G(void 0),[l,u]=G(void 0),[d,f]=G(`building`),p=W(r),m=W(i),h=W(a);return U(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),U(()=>{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=>{n.error(`system`,`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),Te(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Ap(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function jp(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Mp=/^\.+(\\|\/)|^\.+$/,Np=/[. ]+$/,Pp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Fp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Ip=e=>e===`‍`,Lp=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Rp=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let zp;function Bp(){return zp??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),zp}function Vp(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Ap().test(n)||[...n].some(e=>Fp.test(e)&&!Ip(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Rp,` `),n.length>0&&(e=e.replaceAll(Lp,`$1`)),e=e.replace(Np,``),e=e.replace(Mp,n),e=e.replace(Ap(),n),e=e.replaceAll(Pp,e=>Ip(e)?e:n),e.length===0&&(e=n),e=jp().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=Hp(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Hp(n,a)+i}}return e}function Hp(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Bp().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Up(e){return`${e}.lock`}function Wp(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Gp(e,t={}){let n=Up(e),r=process.pid.toString();try{return P.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(P.readFileSync(n,`utf8`),10)}catch{return P.unlinkSync(n),Gp(e,{...t,stale:0})}if(!Wp(i))try{return P.unlinkSync(n),Gp(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return Gp(e,{...t,stale:0});throw n}return!1}}async function Kp(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=Ee.resolve(e),i=0;for(;i<=n.retries;){if(Gp(r,n))return()=>qp(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 qp(e){let t=Ee.resolve(e),n=Up(t);try{if(parseInt(P.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}P.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Jp(e){let t=Ee.resolve(e),n=Up(t);try{if(!P.existsSync(n))return{locked:!1};let e=P.readFileSync(n,`utf8`),t=parseInt(e,10);return Wp(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Yp=e=>{P.mkdirSync(e,{recursive:!0})},Xp=e=>{try{P.fdatasyncSync(e)}catch{}try{P.closeSync(e)}catch{}},Zp=e=>{try{let t=P.openSync(e,`r`);try{P.fsyncSync(t)}finally{P.closeSync(t)}}catch{}},Qp=(e,t)=>{let n=Ee.dirname(e);Yp(n);let r=Ee.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=P.openSync(r,`w`),P.writeFileSync(i,t,`utf-8`),Xp(i),i=void 0,P.renameSync(r,e),Zp(e),Zp(n)}catch(e){if(i!==void 0)try{P.closeSync(i)}catch{}try{P.rmSync(r,{force:!0})}catch{}throw e}},$p=(e,t)=>{let n=new Map,r,i=e=>{if(P.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(e,`utf-8`))},a=(e,t)=>{Qp(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=Ee.join(e,`index.json`);Yp(e),P.existsSync(t)||P.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Kp(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=Ee.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=Ee.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return Ee.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=Ee.join(e,n);if(P.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(P.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Vp(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=Ee.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!P.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=Ee.join(e,i),a=P.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Jp(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Vp(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=Ee.join(e,t);Yp(e),P.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Jp(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Kp(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=Ee.join(e,n);try{P.rmSync(i,{force:!0}),Zp(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},em=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=Ee.join(e,`index.json`),u=()=>{try{if(!P.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=P.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=Ee.join(e,n);try{let e=P.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=Jp(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(P.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{P.mkdirSync(e,{recursive:!0})}catch{}a=P.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function tm({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=nm}){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=ve({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 nm=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(_e);return n.length===0||n.some(e=>E(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},rm=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function im(e){return typeof e==`object`&&e?.__blink_internal!==void 0}function am(e){return typeof e.metadata==`object`&&e.metadata!==null&&`__blink_log`in e.metadata&&e.metadata.__blink_log===!0&&`level`in e.metadata&&`source`in e.metadata&&`message`in e.metadata}var om=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];logQueue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=$p(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=em(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=>!im(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue,queuedLogs:this.logQueue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async queueLogMessage({message:e,level:t,source:n}){let r=`(EDIT MODE NOTE) ${n===`agent`?`The agent`:"The `blink dev` CLI"} printed the following ${t}:\n\`\`\`\n${oe(e)}\n\`\`\`\n`,i={id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`user`,parts:[{type:`text`,text:r}],metadata:{__blink_log:!0,level:t,source:n,message:e},mode:`edit`};this.logQueue.push(i),this.notifyListeners()}async flushLogQueue(e){if(this.logQueue.length===0)return;let t=[...this.logQueue];this.logQueue=[],await this.upsertMessages(t,e)}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId),await this.flushLogQueue(e);let n=!0;for(;this.queue.length>0||n;)try{var t=Dc();n=!1;let r=new AbortController;this.abortController=r;let i=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),i.length>0&&await this.upsertMessages(i,e);let a=this.chat.messages;this.filterMessages&&(a=a.filter(this.filterMessages)),a=a.map(e=>({...e,parts:e.parts.map(e=>!_e(e)||e.input!==``?e:{...e,input:{}})})),t.u(await this.agent.lock.read());let o=performance.now(),s=await tm({agent:this.agent.client,id:this.chatId,signal:r.signal,messages:a}),c=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},l=s.getReader();r.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||r.signal.aborted)break;u||=performance.now()-o,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let n={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(n):n,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}catch(e){t.e=e}finally{t.d()}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.status=`idle`,e&&(await this.flushLogQueue(e),this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.stopStreaming()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[],this.logQueue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function sm(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=W(null),[c,l]=G({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[],queuedLogs:[]});U(()=>{s.current&&s.current.dispose();let e=new om({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]),U(()=>{s.current&&s.current.setAgent(n)},[n]);let u=H(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=H(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=H(async e=>{s.current&&await s.current.queueLogMessage(e)},[]),p=H(()=>{s.current&&s.current.stopStreaming()},[]),m=H(async()=>{s.current&&await s.current.resetChat()},[]),h=H(()=>{s.current&&s.current.clearQueue()},[]),g=H(async e=>{s.current&&await s.current.deleteMessages([e])},[]),_=H(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,queueLogMessage:f,stopStreaming:p,resetChat:m,clearQueue:h,deleteMessage:g,start:_}}function cm(e){return ue(e,`.blink`,`devhook.txt`)}function lm(e){return de(cm(e))}function um(e){let t=cm(e);if(de(t))return pe(t,`utf-8`).trim()}function dm(e){let t=cm(e);if(fe(B(t),{recursive:!0}),de(t))return pe(t,`utf-8`);let n=crypto.randomUUID();return he(t,n),n}const fm=(e,t)=>e.json({error:t},400),pm=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}},mm=()=>new f,hm=mm().get(`/:key`,async e=>{let{key:t,err:n}=pm(e);if(n)return fm(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,k(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?fm(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:fm(t,`Value must be a string`):fm(t,`Value is required`)}),async e=>{let{key:t,err:n}=pm(e);if(n)return fm(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}=pm(e);return n?fm(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})}),gm=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`}},_m=k(`param`,e=>({id:e.id})),vm=mm().post(`/:key`,async e=>{let{key:t,err:n}=gm(e);return n?fm(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,_m,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,_m,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,k(`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)):fm(e,`ID is required`)}).delete(`/:id/messages`,_m,k(`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`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,_m,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),ym=mm().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),bm=new f().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,hm).route(`/chat`,vm).route(`/otlp`,ym);var xm=/^(?:[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 Sm(e){return typeof e==`string`&&xm.test(e)}var Cm=Sm;function wm(e){if(!Cm(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 Tm=wm;const Em=[];for(let e=0;e<256;++e)Em.push((e+256).toString(16).slice(1));function Dm(e,t=0){return(Em[e[t+0]]+Em[e[t+1]]+Em[e[t+2]]+Em[e[t+3]]+`-`+Em[e[t+4]]+Em[e[t+5]]+`-`+Em[e[t+6]]+Em[e[t+7]]+`-`+Em[e[t+8]]+Em[e[t+9]]+`-`+Em[e[t+10]]+Em[e[t+11]]+Em[e[t+12]]+Em[e[t+13]]+Em[e[t+14]]+Em[e[t+15]]).toLowerCase()}function Om(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}function km(e,t,n,r,i,a){let o=typeof n==`string`?Om(n):n,s=typeof r==`string`?Tm(r):r;if(typeof r==`string`&&(r=Tm(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 Dm(c)}function Am(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),se(`sha1`).update(e).digest()}var jm=Am;function Mm(e,t,n,r){return km(80,jm,e,t,n,r)}Mm.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Mm.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Nm=Mm;function Pm(e){let t=ke(e.dataDirectory,`chats`),n={},r=ke(e.dataDirectory,`storage.json`);P.existsSync(r)&&(n=JSON.parse(P.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new om({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=Nm(JSON.stringify(e),Nm.URL),n=a(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=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>rm(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 a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,P.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],P.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=le(w(e=>bm.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=$p(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function Fm({agent:e,capabilities:t,messages:n}){let[r,i]=G(void 0),[a,o]=G(!0),[s,c]=G(void 0),l=W(s);U(()=>{l.current=s},[s]);let[u,d]=G(()=>D(n));U(()=>{d(e=>{let t=D(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=G(void 0),m=H((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=H(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);U(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=W(void 0),_=W(void 0);U(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),U(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=H((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}function Im(e){let t=W(e.onRequest);U(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=G(`disconnected`);return U(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=ke(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Kp(c,{stale:!0,retries:0})}catch(t){if(t&&typeof t==`object`&&`code`in t&&t.code===`ELOCKED`){let e=``;try{let t=Jp(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(cf.red(`\nError: Another ${cf.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(cf.red(`Please stop the other process and try again.
53
- `)),process.exit(1)}let n=t&&typeof t==`object`&&`message`in t?String(t.message):String(t);e.logger.error(`system`,cf.yellow(`\nWarning: Failed to acquire devhook lock: ${n}`)),e.logger.error(`system`,cf.yellow(`Continuing without lock. Multiple ${cf.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 ld({baseURL:`https://blink.coder.com`}).devhook.listen({id:e.id,onRequest:async e=>t.current(e),onConnect:()=>{o=!1,r(`connected`)},onDisconnect:()=>{o=!1,r(`disconnected`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))},onError:e=>{o=!1,r(`error`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))}})}};l()})(),()=>{if(n=!0,a&&=(clearTimeout(a),void 0),i){try{i.dispose()}catch{}i=void 0}if(s)try{s()}catch(t){e.logger.error(`system`,`Failed to release devhook lock:`,t)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var Lm=e(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),Rm=o(e(((e,t)=>{let n=i(`fs`),r=i(`path`),a=i(`os`),o=i(`crypto`),s=Lm().version,c=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function l(){return c[Math.floor(Math.random()*c.length)]}function u(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function d(){return process.stdout.isTTY}function f(e){return d()?`\x1b[2m${e}\x1b[0m`:e}let p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function m(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
44
+ ${Fd}`),t.includes(`
45
+ `)&&(n=3+se(t.slice(t.lastIndexOf(`
46
+ `))).length);let e=se(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
47
+ ${Fd}${t.trimStart()}`),n=3+se(t.trimStart()).length)}process.stdout.write(`
48
+ `)},info:e=>Id.message(e,{symbol:wd.default.blue(Ad)}),success:e=>Id.message(e,{symbol:wd.default.green(jd)}),step:e=>Id.message(e,{symbol:wd.default.green(Od)}),warn:e=>Id.message(e,{symbol:wd.default.yellow(Md)}),warning:e=>Id.warn(e),error:e=>Id.message(e,{symbol:wd.default.red(Nd)})},Ld=(e=0)=>t=>`\u001B[${t+e}m`,Rd=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,zd=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,Q={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(Q.modifier);const Bd=Object.keys(Q.color),Vd=Object.keys(Q.bgColor);[...Bd,...Vd];function Hd(){let e=new Map;for(let[t,n]of Object.entries(Q)){for(let[t,r]of Object.entries(n))Q[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=Q[t],e.set(r[0],r[1]);Object.defineProperty(Q,t,{value:n,enumerable:!1})}return Object.defineProperty(Q,`codes`,{value:e,enumerable:!1}),Q.color.close=`\x1B[39m`,Q.bgColor.close=`\x1B[49m`,Q.color.ansi=Ld(),Q.color.ansi256=Rd(),Q.color.ansi16m=zd(),Q.bgColor.ansi=Ld(10),Q.bgColor.ansi256=Rd(10),Q.bgColor.ansi16m=zd(10),Object.defineProperties(Q,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>Q.rgbToAnsi256(...Q.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>Q.ansi256ToAnsi(Q.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>Q.ansi256ToAnsi(Q.hexToAnsi256(e)),enumerable:!1}}),Q}var Ud=Hd();function Wd(e,t=globalThis.Deno?globalThis.Deno.args:J.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;let Gd;Wd(`no-color`)||Wd(`no-colors`)||Wd(`color=false`)||Wd(`color=never`)?Gd=0:(Wd(`color`)||Wd(`colors`)||Wd(`color=true`)||Wd(`color=always`))&&(Gd=1);function Kd(){if(`FORCE_COLOR`in $)return $.FORCE_COLOR===`true`?1:$.FORCE_COLOR===`false`?0:$.FORCE_COLOR.length===0?1:Math.min(Number.parseInt($.FORCE_COLOR,10),3)}function qd(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Jd(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=Kd();r!==void 0&&(Gd=r);let i=n?Gd:r;if(i===0)return 0;if(n){if(Wd(`color=16m`)||Wd(`color=full`)||Wd(`color=truecolor`))return 3;if(Wd(`color=256`))return 2}if(`TF_BUILD`in $&&`AGENT_NAME`in $)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if($.TERM===`dumb`)return a;if(J.platform===`win32`){let e=Pe.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in $)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in $)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in $)||$.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in $)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test($.TEAMCITY_VERSION)?1:0;if($.COLORTERM===`truecolor`||$.TERM===`xterm-kitty`||$.TERM===`xterm-ghostty`||$.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in $){let e=Number.parseInt(($.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch($.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test($.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test($.TERM)||`COLORTERM`in $?1:a}function Yd(e,t={}){let n=Jd(e,{streamIsTTY:e&&e.isTTY,...t});return qd(n)}var Xd={stdout:Yd({isTTY:Fe.isatty(1)}),stderr:Yd({isTTY:Fe.isatty(2)})};function Zd(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 Qd(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
49
+ `:`
50
+ `)+n,i=r+1,r=e.indexOf(`
51
+ `,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:$d,stderr:ef}=Xd,tf=Symbol(`GENERATOR`),nf=Symbol(`STYLER`),rf=Symbol(`IS_EMPTY`),af=[`ansi`,`ansi`,`ansi256`,`ansi16m`],sf=Object.create(null),cf=(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=$d?$d.level:0;e.level=t.level===void 0?n:t.level},lf=e=>{let t=(...e)=>e.join(` `);return cf(t,e),Object.setPrototypeOf(t,uf.prototype),t};function uf(e){return lf(e)}Object.setPrototypeOf(uf.prototype,Function.prototype);for(let[e,t]of Object.entries(Ud))sf[e]={get(){let n=mf(this,pf(t.open,t.close,this[nf]),this[rf]);return Object.defineProperty(this,e,{value:n}),n}};sf.visible={get(){let e=mf(this,this[nf],!0);return Object.defineProperty(this,`visible`,{value:e}),e}};const df=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?Ud[n].ansi16m(...r):t===`ansi256`?Ud[n].ansi256(Ud.rgbToAnsi256(...r)):Ud[n].ansi(Ud.rgbToAnsi(...r)):e===`hex`?df(`rgb`,t,n,...Ud.hexToRgb(...r)):Ud[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){sf[e]={get(){let{level:t}=this;return function(...n){let r=pf(df(e,af[t],`color`,...n),Ud.color.close,this[nf]);return mf(this,r,this[rf])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);sf[t]={get(){let{level:t}=this;return function(...n){let r=pf(df(e,af[t],`bgColor`,...n),Ud.bgColor.close,this[nf]);return mf(this,r,this[rf])}}}}const ff=Object.defineProperties(()=>{},{...sf,level:{enumerable:!0,get(){return this[tf].level},set(e){this[tf].level=e}}}),pf=(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}},mf=(e,t,n)=>{let r=(...e)=>hf(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,ff),r[tf]=e,r[nf]=t,r[rf]=n,r},hf=(e,t)=>{if(e.level<=0||!t)return e[rf]?``:t;let n=e[nf];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=Zd(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
52
+ `);return a!==-1&&(t=Qd(t,i,r,a)),r+t+i};Object.defineProperties(uf.prototype,sf);const gf=uf();uf({level:ef?ef.level:0});var _f=gf,vf=e((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})),yf=e((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})),bf=e((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})),xf=e((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 a=r(i(`os`)),o=r(i(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:a,path:o,process}})),Sf=e(((e,t)=>{var n=bf(),r=xf();t.exports=n.Adapt(r.adapter).OSPaths})),Cf=n({default:()=>Ef}),wf,Tf,Ef,Df=t((()=>{wf=o(Sf()),Tf=wf.default,Ef=Tf})),Of=e((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},o=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var s=r(i(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:o((Df(),a(Cf))).default,path:s,process}})),kf=e(((e,t)=>{var n=yf(),r=Of();t.exports=n.Adapt(r.adapter).XDG})),Af=n({default:()=>Mf}),jf,Mf,Nf=t((()=>{jf=o(kf()),r(Af,o(kf())),Mf=jf.default})),Pf=e((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},o=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var s=r(i(`path`)),c=o((Nf(),a(Af)));e.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=(i!=null&&i.main?i.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:s,process,xdg:c.default}})),Ff=o(e(((e,t)=>{var n=vf(),r=Pf();t.exports=n.Adapt(r.adapter).XDGAppPaths}))()).default;let If;function Lf(){try{return P.statSync(`/.dockerenv`),!0}catch{return!1}}function Rf(){try{return P.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function zf(){return If===void 0&&(If=Lf()||Rf()),If}let Bf;const Vf=()=>{try{return P.statSync(`/run/.containerenv`),!0}catch{return!1}};function Hf(){return Bf===void 0&&(Bf=Vf()||zf()),Bf}const Uf=()=>{if(J.platform!==`linux`)return!1;if(Pe.release().toLowerCase().includes(`microsoft`))return!Hf();try{return P.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Hf():!1}catch{return!1}};var Wf=J.env.__IS_WSL_TEST__?Uf:Uf();const Gf=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await Re.access(n,ze.F_OK),r=!0}catch{}if(!r)return e;let i=await Re.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}})(),Kf=async()=>`${await Gf()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,qf=async()=>Wf?Kf():`${J.env.SYSTEMROOT||J.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Jf(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 Yf=oe(Le);async function Xf(){if(J.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Yf(`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 Zf=oe(Le);async function Qf(e,{humanReadableOutput:t=!0,signal:n}={}){if(J.platform!==`darwin`)throw Error(`macOS only`);let r=t?[]:[`-ss`],i={};n&&(i.signal=n);let{stdout:a}=await Zf(`osascript`,[`-e`,e,r],i);return a.trim()}async function $f(e){return Qf(`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 ep=oe(Le),tp={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 np=class extends Error{};async function rp(e=ep){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 np(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=tp[r];if(!i)throw new np(`Unknown browser ID: ${r}`);return i}const ip=oe(Le),ap=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function op(){if(J.platform===`darwin`){let e=await Xf();return{name:await $f(e),id:e}}if(J.platform===`linux`){let{stdout:e}=await ip(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:ap(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(J.platform===`win32`)return rp();throw Error(`Only macOS, Linux, and Windows are supported`)}const sp=oe(Ie.execFile),cp=De.dirname(ae(import.meta.url)),lp=De.join(cp,`xdg-open`),{platform:up,arch:dp}=J;async function fp(){let e=await qf(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=ne.from(t,`utf16le`).toString(`base64`),{stdout:r}=await sp(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const pp=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},mp=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return pp(e.app,t=>mp({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return pp(t,t=>mp({...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=Wf?await fp():await op();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),mp({...e,app:{name:vp[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(up===`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(up===`win32`||Wf&&!Hf()&&!t){r=await qf(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Wf||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=ne.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!cp||cp===`/`,t=!1;try{await Re.access(lp,ze.X_OK),t=!0}catch{}r=J.versions.electron??(up===`android`||e||!t)?`xdg-open`:lp}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}up===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=Ie.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},hp=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return mp({...t,target:e})};function gp(e){if(typeof e==`string`||Array.isArray(e))return e;let{[dp]:t}=e;if(!t)throw Error(`${dp} is not supported`);return t}function _p({[up]:e},{wsl:t}){if(t&&Wf)return gp(t);if(!e)throw Error(`${up} is not supported`);return gp(e)}const vp={};Jf(vp,`chrome`,()=>_p({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`]}})),Jf(vp,`brave`,()=>_p({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`]}})),Jf(vp,`firefox`,()=>_p({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Jf(vp,`edge`,()=>_p({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Jf(vp,`browser`,()=>`browser`),Jf(vp,`browserPrivate`,()=>`browserPrivate`);var yp=hp;async function bp(e,t=void 0){try{(await yp(e)).once(`error`,n=>{console.log(_f.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))})}catch{console.log(_f.yellow(t??`Could not open the browser. Please visit the URL manually: ${e}`))}}function xp(e){let t=e||Ep();if(F(t)){let e=I(t,`utf8`),n=JSON.parse(e);return n.host||=`https://blink.coder.com`,n}}function Sp(e,t){let n=t||Ep();F(Oe(n))||re(Oe(n),{recursive:!0}),L(n,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,...e}))}function Cp(e){return xp(e)?.token}function wp(e,t){let n=xp(t)??{};Sp({...n,token:e},t)}function Tp(e){let t=e||Ep();F(t)&&ie(t)}function Ep(){let e=Ff(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return ke(e[0],`auth.json`)}function Dp(e={}){let{autoCheck:t=!0,onAuthChange:n,onLoginUrl:r,testAuthPath:i}=e,[a,o]=W(),[s,c]=W(()=>Cp(i)),[l,u]=W(),d=U(n),f=U(r);H(()=>{d.current=n,f.current=r},[n,r]);let p=V(async()=>{u(void 0);try{let e=Cp(i);if(c(e),!e){o(void 0),d.current?.(void 0);return}let t=new ld({baseURL:`https://blink.coder.com`});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=V(async()=>{u(void 0);try{let e=new ld,t=await e.auth.token((e,t)=>{f.current?.(e,t)});e.authToken=t;let n=await e.users.me();wp(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=V(()=>{Tp(i),c(void 0),o(void 0),u(void 0),d.current?.(void 0)},[i]);return H(()=>{t&&p()},[t,p]),{user:a,token:s,error:l,login:m,logout:h}}let Op=Promise.resolve();var kp=class{constructor(e){this.printLog=e}setPrintLog(e){this.printLog=e}error(e,...t){Op=Op.then(()=>this.printLog(`error`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}log(e,...t){Op=Op.then(()=>this.printLog(`log`,e,...t).catch(e=>{console.error(`Error printing log:`,e)}))}flush(){return Op}};const Ap=Te(void 0);function jp(e){let{directory:t,logger:n,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e,logger:new kp(async()=>{})}:e,o=Ee(()=>k(t),[t]),[s,c]=W(void 0),[l,u]=W(void 0),[d,f]=W(`building`),p=U(r),m=U(i),h=U(a);return H(()=>{p.current=r,m.current=i,h.current=a},[r,i,a]),H(()=>{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=>{n.error(`system`,`error`,e),f(`error`),c(e),h.current?.(e)}),()=>{e.abort()}},[t]),Ee(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function Mp(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function Np(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Pp=/^\.+(\\|\/)|^\.+$/,Fp=/[. ]+$/,Ip=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Lp=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Rp=e=>e===`‍`,zp=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Bp=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let Vp;function Hp(){return Vp??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Vp}function Up(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Mp().test(n)||[...n].some(e=>Lp.test(e)&&!Rp(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Bp,` `),n.length>0&&(e=e.replaceAll(zp,`$1`)),e=e.replace(Fp,``),e=e.replace(Pp,n),e=e.replace(Mp(),n),e=e.replaceAll(Ip,e=>Rp(e)?e:n),e.length===0&&(e=n),e=Np().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=Wp(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Wp(n,a)+i}}return e}function Wp(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Hp().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function Gp(e){return`${e}.lock`}function Kp(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function qp(e,t={}){let n=Gp(e),r=process.pid.toString();try{return N.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(N.readFileSync(n,`utf8`),10)}catch{return N.unlinkSync(n),qp(e,{...t,stale:0})}if(!Kp(i))try{return N.unlinkSync(n),qp(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return qp(e,{...t,stale:0});throw n}return!1}}async function Jp(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=q.resolve(e),i=0;for(;i<=n.retries;){if(qp(r,n))return()=>Yp(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 Yp(e){let t=q.resolve(e),n=Gp(t);try{if(parseInt(N.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}N.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function Xp(e){let t=q.resolve(e),n=Gp(t);try{if(!N.existsSync(n))return{locked:!1};let e=N.readFileSync(n,`utf8`),t=parseInt(e,10);return Kp(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const Zp=e=>{N.mkdirSync(e,{recursive:!0})},Qp=e=>{try{N.fdatasyncSync(e)}catch{}try{N.closeSync(e)}catch{}},$p=e=>{try{let t=N.openSync(e,`r`);try{N.fsyncSync(t)}finally{N.closeSync(t)}}catch{}},em=(e,t)=>{let n=q.dirname(e);Zp(n);let r=q.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=N.openSync(r,`w`),N.writeFileSync(i,t,`utf-8`),Qp(i),i=void 0,N.renameSync(r,e),$p(e),$p(n)}catch(e){if(i!==void 0)try{N.closeSync(i)}catch{}try{N.rmSync(r,{force:!0})}catch{}throw e}},tm=(e,t)=>{let n=new Map,r,i=e=>{if(N.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(N.readFileSync(e,`utf-8`))},a=(e,t)=>{em(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=q.join(e,`index.json`);Zp(e),N.existsSync(t)||N.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await Jp(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=q.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},c=async t=>{let n=q.join(e,`index.json`);a(n,t)},l=async t=>{let n=(await s()).ids[t];if(n)return q.join(e,n)},u=async t=>{let n=(await s()).ids[t];if(!n)return;let r=q.join(e,n);if(N.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(N.readFileSync(r,`utf-8`))},d=async n=>{let r=n[t],i=String(r),l=Up(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=l,t.current=i;let r=q.join(e,l);a(r,n),await c(t)}finally{await u()}};return{async get(e){return await u(e)},async list(){if(!N.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=q.join(e,i),a=N.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=Xp(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await l(r);if(!a){let t=Up(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=q.join(e,t);Zp(e),N.writeFileSync(i,JSON.stringify({}),`utf-8`),await c(n),a=i}finally{await n()}}if(i?.force){let e=Xp(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let f=await Jp(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(f())),{async get(){let e=await u(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await d(e)},async update(e){let n=await u(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await d({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await c(t);let i=q.join(e,n);try{N.rmSync(i,{force:!0}),$p(e)}catch{}}}finally{await t()}},async release(){try{f()}finally{n.delete(r)}}}},dispose(){n.clear()}}},nm=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,c=new Map,l=q.join(e,`index.json`),u=()=>{try{if(!N.statSync(l,{throwIfNoEntry:!1}))return{ids:{}};let e=N.readFileSync(l,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},d=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},f=(t,n,r=!1)=>{let i=q.join(e,n);try{let e=N.statSync(i,{throwIfNoEntry:!1}),a=c.get(n);if(!e){a&&(c.delete(n),d(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=Xp(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(N.readFileSync(i,`utf-8`)):a.cachedValue,c.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),d(t,e,s.locked,s.pid)}}catch{}},p=()=>{try{let e=u(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))f(t,n,!0);for(let[e,n]of c.entries())t.has(n.key)||(c.delete(e),d(n.key,void 0,!1))}catch{}},m=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),f(e,t,n)},r))},h=()=>{if(a)return;try{N.mkdirSync(e,{recursive:!0})}catch{}a=N.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){p();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=u(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&f(r,e,!0);return}let n=u(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&m(r,t,!1)});let t=()=>{p(),o=setTimeout(t,n)};p(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&h(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),c.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),c.clear()}}};async function rm({id:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=im}){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=ye({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 im=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),n=e.parts.slice(t+1).filter(ve);return n.length===0||n.some(e=>T(e.output)&&e.output.outcome===`pending`)?!1:n.every(e=>e.state.startsWith(`output-`))},am=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function om(e){return typeof e==`object`&&e?.__blink_internal!==void 0}function sm(e){return typeof e.metadata==`object`&&e.metadata!==null&&`__blink_log`in e.metadata&&e.metadata.__blink_log===!0&&`level`in e.metadata&&`source`in e.metadata&&`message`in e.metadata}var cm=class{chatId;agent;chatStore;serializeMessage;filterMessages;onError;chat;loading=!1;streamingMessage;status=`idle`;queue=[];logQueue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId??`00000000-0000-0000-0000-000000000000`,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=tm(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.onError=e.onError,this.watcher=nm(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=>!om(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,loading:this.loading,queuedMessages:this.queue,queuedLogs:this.logQueue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessages(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=[...t.messages];for(let t of e){let e;if(this.serializeMessage){let n=this.serializeMessage(t);if(n===void 0)return;e=n}else e={...t,created_at:new Date().toISOString(),mode:`run`,metadata:t.metadata,id:t.id??crypto.randomUUID()};let r=n.findIndex(t=>t.id===e.id);r===-1?n.push(e):n.splice(r,1,e)}this.chat={...t,updated_at:new Date().toISOString(),messages:n},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessages(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>!e.includes(t.id)),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async queueLogMessage({message:e,level:t,source:n}){let r=`(EDIT MODE NOTE) ${n===`agent`?`The agent`:"The `blink dev` CLI"} printed the following ${t}:\n\`\`\`\n${se(e)}\n\`\`\`\n`,i={id:crypto.randomUUID(),created_at:new Date().toISOString(),role:`user`,parts:[{type:`text`,text:r}],metadata:{__blink_log:!0,level:t,source:n,message:e},mode:`edit`};this.logQueue.push(i),this.notifyListeners()}async flushLogQueue(e){if(this.logQueue.length===0)return;let t=[...this.logQueue];this.logQueue=[],await this.upsertMessages(t,e)}async sendMessages(e){if(this.status=`idle`,this.notifyListeners(),this.isProcessingQueue){this.queue.push(...e),this.notifyListeners();return}this.queue=e,this.processQueueOrRun()}async start(){this.status=`idle`,this.notifyListeners(),this.processQueueOrRun()}async stop(){this.status=`idle`,this.abortController?.abort(),this.notifyListeners()}async processQueueOrRun(){if(!this.agent){this.onError?.(`The agent is not available. Please wait for the build to succeed.`),this.queue=[];return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e;try{e=await this.chatStore.lock(this.chatId),await this.flushLogQueue(e);let n=!0;for(;this.queue.length>0||n;)try{var t=Dc();n=!1;let r=new AbortController;this.abortController=r;let i=[...this.queue];this.queue=[],this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),i.length>0&&await this.upsertMessages(i,e);let a=this.chat.messages;this.filterMessages&&(a=a.filter(this.filterMessages)),a=a.map(e=>({...e,parts:e.parts.map(e=>!ve(e)||e.input!==``?e:{...e,input:{}})})),t.u(await this.agent.lock.read());let o=performance.now(),s=await rm({agent:this.agent.client,id:this.chatId,signal:r.signal,messages:a}),c=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},l=s.getReader();r.signal.addEventListener(`abort`,()=>{l.cancel().catch(()=>{})},{once:!0});let u;try{for(;;){let{done:e,value:t}=await l.read();if(e||r.signal.aborted)break;u||=performance.now()-o,this.streamingMessage&&t.id!==this.streamingMessage.id&&await c(this.streamingMessage);let n={...t,metadata:{...typeof t.metadata==`object`&&t.metadata!==null?t.metadata:{},ttft:u}};this.streamingMessage=this.serializeMessage?this.serializeMessage(n):n,this.notifyListeners()}}finally{l.releaseLock()}this.streamingMessage&&await c(this.streamingMessage)}catch(e){t.e=e}finally{t.d()}}catch(e){let t=e instanceof Error?e.message:String(e);this.onError?.(t)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.status=`idle`,e&&(await this.flushLogQueue(e),this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.stopStreaming()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[],this.logQueue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function lm(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a,onError:o}=e,s=U(null),[c,l]=W({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[],queuedLogs:[]});H(()=>{s.current&&s.current.dispose();let e=new cm({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]),H(()=>{s.current&&s.current.setAgent(n)},[n]);let u=V(async e=>{s.current&&await s.current.sendMessages([e])},[]),d=V(async e=>{s.current&&await s.current.upsertMessages([e])},[]),f=V(async e=>{s.current&&await s.current.queueLogMessage(e)},[]),p=V(()=>{s.current&&s.current.stopStreaming()},[]),m=V(async()=>{s.current&&await s.current.resetChat()},[]),h=V(()=>{s.current&&s.current.clearQueue()},[]),g=V(async e=>{s.current&&await s.current.deleteMessages([e])},[]),_=V(async()=>{s.current&&await s.current.start()},[]);return{...c,sendMessage:u,upsertMessage:d,queueLogMessage:f,stopStreaming:p,resetChat:m,clearQueue:h,deleteMessage:g,start:_}}function um(e){return de(e,`.blink`,`devhook.txt`)}function dm(e){return fe(um(e))}function fm(e){let t=um(e);if(fe(t))return me(t,`utf-8`).trim()}function pm(e){let t=um(e);if(pe(z(t),{recursive:!0}),fe(t))return me(t,`utf-8`);let n=crypto.randomUUID();return ge(t,n),n}const mm=(e,t)=>e.json({error:t},400),hm=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}},gm=()=>new f,_m=gm().get(`/:key`,async e=>{let{key:t,err:n}=hm(e);if(n)return mm(e,n);let r=await e.env.store.get(t);return e.json({value:r},200)}).post(`/:key`,O(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?mm(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:mm(t,`Value must be a string`):mm(t,`Value is required`)}),async e=>{let{key:t,err:n}=hm(e);if(n)return mm(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}=hm(e);return n?mm(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})}),vm=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`}},ym=O(`param`,e=>({id:e.id})),bm=gm().post(`/:key`,async e=>{let{key:t,err:n}=vm(e);return n?mm(e,n):e.json(await e.env.chat.upsert(t),200)}).get(`/:id`,ym,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.get(t),200)}).get(`/:id/messages`,ym,async e=>{let{id:t}=e.req.valid(`param`);return e.json(await e.env.chat.getMessages(t),200)}).post(`/:id/sendMessages`,O(`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)):mm(e,`ID is required`)}).delete(`/:id/messages`,ym,O(`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`,ym,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.start(t),e.body(null,204)}).post(`/:id/stop`,ym,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.stop(t),e.body(null,204)}).delete(`/:id`,ym,async e=>{let{id:t}=e.req.valid(`param`);return await e.env.chat.delete(t),e.body(null,204)}),xm=gm().post(`/v1/traces`,async e=>e.env.otlp?e.env.otlp.traces(e.req.raw):e.body(null,204)),Sm=new f().onError((e,t)=>t.json({error:e instanceof Error?e.message:`Unknown error`},500)).route(`/kv`,_m).route(`/chat`,bm).route(`/otlp`,xm);var Cm=/^(?:[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 wm(e){return typeof e==`string`&&Cm.test(e)}var Tm=wm;function Em(e){if(!Tm(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 Dm=Em;const Om=[];for(let e=0;e<256;++e)Om.push((e+256).toString(16).slice(1));function km(e,t=0){return(Om[e[t+0]]+Om[e[t+1]]+Om[e[t+2]]+Om[e[t+3]]+`-`+Om[e[t+4]]+Om[e[t+5]]+`-`+Om[e[t+6]]+Om[e[t+7]]+`-`+Om[e[t+8]]+Om[e[t+9]]+`-`+Om[e[t+10]]+Om[e[t+11]]+Om[e[t+12]]+Om[e[t+13]]+Om[e[t+14]]+Om[e[t+15]]).toLowerCase()}function Am(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}function jm(e,t,n,r,i,a){let o=typeof n==`string`?Am(n):n,s=typeof r==`string`?Dm(r):r;if(typeof r==`string`&&(r=Dm(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 km(c)}function Mm(e){return Array.isArray(e)?e=Buffer.from(e):typeof e==`string`&&(e=Buffer.from(e,`utf8`)),ce(`sha1`).update(e).digest()}var Nm=Mm;function Pm(e,t,n,r){return jm(80,Nm,e,t,n,r)}Pm.DNS=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`,Pm.URL=`6ba7b811-9dad-11d1-80b4-00c04fd430c8`;var Fm=Pm;function Im(e){let t=ke(e.dataDirectory,`chats`),n={},r=ke(e.dataDirectory,`storage.json`);N.existsSync(r)&&(n=JSON.parse(N.readFileSync(r,`utf-8`)));let i=new Map,a=n=>{let r=i.get(n);return r||(r=new cm({chatId:n,chatsDirectory:t}),i.set(n,r)),r.setAgent(e.getAgent()),r},o={async upsert(e){let t=Fm(JSON.stringify(e),Fm.URL),n=a(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=a(e).getState();return{id:t.id,createdAt:t.created_at??new Date().toISOString()}},async getMessages(e){return a(e).getState().messages},async sendMessages(e,t,n){let r=a(e),i=t.map(e=>am(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 a(e).deleteMessages(t)},async start(e){await a(e).start()},async stop(e){await a(e).stop()},async delete(e){await a(e).resetChat()}},s={get(e){return Promise.resolve(n[e])},set(e,t){return n[e]=t,N.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},delete(e){return delete n[e],N.writeFileSync(r,JSON.stringify(n),`utf-8`),Promise.resolve()},list(e,t){let r=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(n).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+r),c=o+r<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}},c=ue(w(e=>Sm.fetch(e,{chat:o,store:s})));c.listen(e.port??0);let l=tm(t,`id`);return{url:`http://127.0.0.1:${c.address().port}`,chatsDirectory:t,getChatManager:a,listChats:()=>l.list(),dispose:()=>{for(let e of i.values())e.dispose();i.clear(),l.dispose(),c.close()}}}function Lm({agent:e,capabilities:t,messages:n}){let[r,i]=W(void 0),[a,o]=W(!0),[s,c]=W(void 0),l=U(s);H(()=>{l.current=s},[s]);let[u,d]=W(()=>E(n));H(()=>{d(e=>{let t=E(n);return JSON.stringify(t)===JSON.stringify(e)?e:t})},[n]);let[f,p]=W(void 0),m=V((e,t)=>{if(!l.current)return!1;let n=l.current[e];return n?n.values.some(e=>e.id===t):!1},[]),h=V(e=>{p(t=>{let n={...u,...t,...e};for(let[e,t]of Object.entries(n))m(e,t)||delete n[e];for(let[e,t]of Object.entries(l.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[u,m]);H(()=>{if(!u&&!s){p(void 0);return}h()},[u,s,h]);let g=U(void 0),_=U(void 0);H(()=>{e!==_.current&&(_.current=e,c(void 0),p(void 0),i(void 0),o(!0),g.current=void 0)},[e]),H(()=>{if(t&&!t.ui||!e){c(void 0),p(void 0),i(void 0),g.current=void 0;return}let n=f?JSON.stringify(f):``;if(g.current===n){o(!1),i(void 0);return}let r=new AbortController;return o(!0),i(void 0),e.ui(f?{selectedOptions:f}:{},{signal:r.signal}).then(e=>{if(!e){c(void 0);return}r.signal.aborted||(c(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),g.current=n)}).catch(e=>{r.signal.aborted||i(e instanceof Error?e:Error(String(e)))}).finally(()=>{o(!1)}),()=>{r.abort()}},[e,t,f]);let v=V((e,t)=>{h({[e]:t})},[h]);return{schema:s,options:f,setOption:v,loading:a,error:r}}function Rm(e){let t=U(e.onRequest);H(()=>{t.current=e.onRequest},[e.onRequest]);let[n,r]=W(`disconnected`);return H(()=>{if(e.disabled||!e.id){r(`disconnected`);return}let n=!1,i,a,o=!1,s,c=ke(e.directory,`.blink`,`devhook`);return(async()=>{try{s=await Jp(c,{stale:!0,retries:0})}catch(t){if(t&&typeof t==`object`&&`code`in t&&t.code===`ELOCKED`){let e=``;try{let t=Xp(c);t.locked&&t.pid&&(e=` (PID: ${t.pid})`)}catch{}console.error(_f.red(`\nError: Another ${_f.bold(`blink dev`)} process is already running in this directory${e}.`)),console.error(_f.red(`Please stop the other process and try again.
53
+ `)),process.exit(1)}let n=t&&typeof t==`object`&&`message`in t?String(t.message):String(t);e.logger.error(`system`,_f.yellow(`\nWarning: Failed to acquire devhook lock: ${n}`)),e.logger.error(`system`,_f.yellow(`Continuing without lock. Multiple ${_f.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 ld({baseURL:`https://blink.coder.com`}).devhook.listen({id:e.id,onRequest:async e=>t.current(e),onConnect:()=>{o=!1,r(`connected`)},onDisconnect:()=>{o=!1,r(`disconnected`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))},onError:e=>{o=!1,r(`error`),!n&&!a&&(a=setTimeout(()=>{a=void 0,l()},2e3))}})}};l()})(),()=>{if(n=!0,a&&=(clearTimeout(a),void 0),i){try{i.dispose()}catch{}i=void 0}if(s)try{s()}catch(t){e.logger.error(`system`,`Failed to release devhook lock:`,t)}}},[e.disabled,e.directory]),{id:e.id,url:e.id?`https://${e.id}.blink.host`:void 0,status:n}}var zm=e(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),Bm=o(e(((e,t)=>{let n=i(`fs`),r=i(`path`),a=i(`os`),o=i(`crypto`),s=zm().version,c=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function l(){return c[Math.floor(Math.random()*c.length)]}function u(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function d(){return process.stdout.isTTY}function f(e){return d()?`\x1b[2m${e}\x1b[0m`:e}let p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function m(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
54
54
  `);let r;for(;(r=p.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
55
- `),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function h(e){e||={};let t=x(e);e.path=t;let n=O.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=y(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=b(n,t);a=O.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return O.parse(a)}function g(e){console.error(`[dotenv@${s}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function v(e){console.log(`[dotenv@${s}] ${e}`)}function y(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function b(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function x(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let 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 S(e){return e[0]===`~`?r.join(a.homedir(),e.slice(1)):e}function C(e){let t=u(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=u(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&v(`Loading env from encrypted .env.vault`);let r=O._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),O.populate(i,r,e),{parsed:r}}function w(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=u(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=u(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&_(`No encoding is specified. UTF-8 is used by default`);let c=[t];if(e&&e.path)if(!Array.isArray(e.path))c=[S(e.path)];else{c=[];for(let t of e.path)c.push(S(t))}let d,p={};for(let t of c)try{let r=O.parse(n.readFileSync(t,{encoding:i}));O.populate(p,r,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=O.populate(a,p,e);if(o=u(a.DOTENV_CONFIG_DEBUG||o),s=u(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of c)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&_(`Failed to load ${e} ${t.message}`),d=t}v(`injecting env (${e}) from ${t.join(`,`)} ${f(`-- tip: ${l()}`)}`)}return d?{parsed:p,error:d}:{parsed:p}}function T(e){if(y(e).length===0)return O.configDotenv(e);let t=x(e);return t?O._configVault(e):(g(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),O.configDotenv(e))}function E(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function D(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n],a[n]=t[n]),r&&_(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let O={configDotenv:w,_configVault:C,_parseVault:h,config:T,decrypt:E,parse:m,populate:D};t.exports.configDotenv=O.configDotenv,t.exports._configVault=O._configVault,t.exports._parseVault=O._parseVault,t.exports.config=O.config,t.exports.decrypt=O.decrypt,t.exports.parse=O.parse,t.exports.populate=O.populate,t.exports=O}))());async function zm(e,t){let n=e;for(;n!==B(n);){let e=ue(n,t);try{return await V(e),e}catch{}n=B(n)}}function Bm(e,t,n=`.env.local`){let[r,i]=G({});return U(()=>{let r,a=e=>{try{let t=pe(e,`utf-8`),n=(0,Rm.parse)(t);i(n)}catch(e){t.error(`system`,`Error reading ${n}:`,e),i({})}};return zm(e,n).then(e=>{if(!e){i({});return}a(e),r=me(e,{persistent:!1},()=>{a(e)})}),()=>{r&&r.close()}},[e,n]),r}var Vm=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}};new class extends Vm{};function Hm(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 Um(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 Wm(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 Gm(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 Km(e,t){return Wm(e,t,``)}function qm(e,t){return Gm(e,t,``)}function Jm(e,t){return t.slice(0,Ym(e,t))}function Ym(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 Xm(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function Zm(e){let t=e.match(/^\s*/);return t?t[0]:``}const Qm=`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}`,$m=RegExp(`[${Qm}]+|\\s+|[^${Qm}]`,`ug`);new class extends Vm{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($m)||[];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)&&eh(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&eh(n,i,r,null),e}};function eh(e,t,n,r){if(t&&n){let i=Zm(t.value),a=Xm(t.value),o=Zm(n.value),s=Xm(n.value);if(e){let r=Hm(i,o);e.value=Gm(e.value,o,r),t.value=Km(t.value,r),n.value=Km(n.value,r)}if(r){let e=Um(a,s);r.value=Wm(r.value,s,e),t.value=qm(t.value,e),n.value=qm(n.value,e)}}else if(n){if(e){let e=Zm(n.value);n.value=n.value.substring(e.length)}if(r){let e=Zm(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Zm(r.value),i=Zm(t.value),a=Xm(t.value),o=Hm(n,i);t.value=Km(t.value,o);let s=Um(Km(n,o),a);t.value=qm(t.value,s),r.value=Wm(r.value,n,s),e.value=Gm(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=Zm(r.value),n=Jm(Xm(t.value),e);t.value=qm(t.value,n)}else if(e){let n=Jm(Xm(e.value),Zm(t.value));t.value=Km(t.value,n)}}new class extends Vm{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Qm}]+|[^\\S\\n\\r]+|[^${Qm}]`,`ug`);return e.match(t)||[]}};const th=new class extends Vm{constructor(){super(...arguments),this.tokenize=rh}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
55
+ `),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function h(e){e||={};let t=x(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=y(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=b(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function g(e){console.error(`[dotenv@${s}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${s}][DEBUG] ${e}`)}function v(e){console.log(`[dotenv@${s}] ${e}`)}function y(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function b(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function x(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let 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 S(e){return e[0]===`~`?r.join(a.homedir(),e.slice(1)):e}function C(e){let t=u(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=u(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&v(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function w(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=u(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=u(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&_(`No encoding is specified. UTF-8 is used by default`);let c=[t];if(e&&e.path)if(!Array.isArray(e.path))c=[S(e.path)];else{c=[];for(let t of e.path)c.push(S(t))}let d,p={};for(let t of c)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&_(`Failed to load ${t} ${e.message}`),d=e}let m=D.populate(a,p,e);if(o=u(a.DOTENV_CONFIG_DEBUG||o),s=u(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of c)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&_(`Failed to load ${e} ${t.message}`),d=t}v(`injecting env (${e}) from ${t.join(`,`)} ${f(`-- tip: ${l()}`)}`)}return d?{parsed:p,error:d}:{parsed:p}}function ee(e){if(y(e).length===0)return D.configDotenv(e);let t=x(e);return t?D._configVault(e):(g(`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),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function 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&&_(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:w,_configVault:C,_parseVault:h,config:ee,decrypt:T,parse:m,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}))());async function Vm(e,t){let n=e;for(;n!==z(n);){let e=de(n,t);try{return await B(e),e}catch{}n=z(n)}}function Hm(e,t,n=`.env.local`){let[r,i]=W({});return H(()=>{let r,a=e=>{try{let t=me(e,`utf-8`),n=(0,Bm.parse)(t);i(n)}catch(e){t.error(`system`,`Error reading ${n}:`,e),i({})}};return Vm(e,n).then(e=>{if(!e){i({});return}a(e),r=he(e,{persistent:!1},()=>{a(e)})}),()=>{r&&r.close()}},[e,n]),r}var Um=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}};new class extends Um{};function Wm(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 Gm(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 Km(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 qm(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 Jm(e,t){return Km(e,t,``)}function Ym(e,t){return qm(e,t,``)}function Xm(e,t){return t.slice(0,Zm(e,t))}function Zm(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 Qm(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function $m(e){let t=e.match(/^\s*/);return t?t[0]:``}const eh=`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}`,th=RegExp(`[${eh}]+|\\s+|[^${eh}]`,`ug`);new class extends Um{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(th)||[];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)&&nh(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&nh(n,i,r,null),e}};function nh(e,t,n,r){if(t&&n){let i=$m(t.value),a=Qm(t.value),o=$m(n.value),s=Qm(n.value);if(e){let r=Wm(i,o);e.value=qm(e.value,o,r),t.value=Jm(t.value,r),n.value=Jm(n.value,r)}if(r){let e=Gm(a,s);r.value=Km(r.value,s,e),t.value=Ym(t.value,e),n.value=Ym(n.value,e)}}else if(n){if(e){let e=$m(n.value);n.value=n.value.substring(e.length)}if(r){let e=$m(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=$m(r.value),i=$m(t.value),a=Qm(t.value),o=Wm(n,i);t.value=Jm(t.value,o);let s=Gm(Jm(n,o),a);t.value=Ym(t.value,s),r.value=Km(r.value,n,s),e.value=qm(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=$m(r.value),n=Qm(t.value),i=Xm(n,e);t.value=Ym(t.value,i)}else if(e){let n=Qm(e.value),r=$m(t.value),i=Xm(n,r);t.value=Jm(t.value,i)}}new class extends Um{tokenize(e){let t=RegExp(`(\\r?\\n)|[${eh}]+|[^\\S\\n\\r]+|[^${eh}]`,`ug`);return e.match(t)||[]}};const rh=new class extends Um{constructor(){super(...arguments),this.tokenize=ah}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
56
56
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
57
57
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
58
58
  `)&&(e=e.slice(0,-1)),t.endsWith(`
59
- `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function nh(e,t,n){return th.diff(e,t,n)}function rh(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
60
- `));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 ih(e){return e==`.`||e==`!`||e==`?`}new class extends Vm{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(ih(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 class extends Vm{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends Vm{constructor(){super(...arguments),this.tokenize=rh}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(ah(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)}};function ah(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]=ah(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]=ah(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends Vm{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function oh(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;nh(n,r,Object.assign(Object.assign({},s),{callback:t=>{e(l(t))}}))}else return l(nh(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||sh(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(`
61
- `)?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 sh(e){let t=e.endsWith(`
59
+ `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function ih(e,t,n){return rh.diff(e,t,n)}function ah(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
60
+ `));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 oh(e){return e==`.`||e==`!`||e==`?`}new class extends Um{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(oh(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 class extends Um{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends Um{constructor(){super(...arguments),this.tokenize=ah}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(sh(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)}};function sh(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]=sh(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]=sh(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends Um{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};function ch(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;ih(n,r,Object.assign(Object.assign({},s),{callback:t=>{let n=l(t);e(n)}}))}else return l(ih(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||lh(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(`
61
+ `)?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 lh(e){let t=e.endsWith(`
62
62
  `),n=e.split(`
63
63
  `).map(e=>e+`
64
- `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const ch={readLineLimit:2e3,readLineLengthLimit:2e3,plainOutputCharacterLimit:8192};let lh;const uh=e=>{let t=()=>lh||(lh=Promise.resolve(Be().client),lh);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)})}}},dh=e=>{let{ansiOutput:t,...n}=e;return{type:`json`,value:n}},fh={execute_bash:uh(({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:q.object({command:q.string(),working_directory:q.string().describe(`The working directory to execute the command in. Use '.' for the current directory.`),env:q.record(q.string(),q.string()),env_file:q.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:uh(({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.
64
+ `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const uh={readLineLimit:2e3,readLineLengthLimit:2e3,plainOutputCharacterLimit:8192};let dh;const fh=e=>{let t=()=>dh||(dh=Promise.resolve(Be().client),dh);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)})}}},ph=e=>{let{ansiOutput:t,...n}=e;return{type:`json`,value:n}},mh={execute_bash:fh(({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:K.object({command:K.string(),working_directory:K.string().describe(`The working directory to execute the command in. Use '.' for the current directory.`),env:K.record(K.string(),K.string()),env_file:K.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:fh(({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.
65
65
 
66
- Use the same rules as \`execute_bash\`, but the output is returned synchronously.`,inputSchema:q.object({command:q.string(),working_directory:q.string().describe(`The working directory to execute the command in. Use '.' for the current directory.`),env:q.record(q.string(),q.string()),env_file:q.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 ph({client:await e(),pid:r.pid,abortSignal:n.abortSignal}))yield t},toModelOutput:dh})),process_send_input:uh(({client:e})=>({description:`Send input to a process by PID that was started by the execute_bash tool.
66
+ Use the same rules as \`execute_bash\`, but the output is returned synchronously.`,inputSchema:K.object({command:K.string(),working_directory:K.string().describe(`The working directory to execute the command in. Use '.' for the current directory.`),env:K.record(K.string(),K.string()),env_file:K.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 hh({client:await e(),pid:r.pid,abortSignal:n.abortSignal}))yield t},toModelOutput:ph})),process_send_input:fh(({client:e})=>({description:`Send input to a process by PID that was started by the execute_bash tool.
67
67
 
68
68
  Use "\r
69
- " to send a newline (e.g. for an interactive prompt).`,inputSchema:q.object({pid:q.number(),data:q.string()}),execute:async(t,n)=>(await e()).request(`process_send_input`,{pid:t.pid,data:t.data},{signal:n.abortSignal})})),process_kill:uh(({client:e})=>({description:`Kill a process by PID that was started by the execute_bash tool.`,inputSchema:q.object({pid:q.number(),signal:q.string()}),execute:async(t,n)=>(await e()).request(`process_kill`,{pid:t.pid,signal:t.signal},{signal:n.abortSignal})})),process_wait:uh(({client:e})=>({description:`This tool waits for a process to exit, or returns instantly if the process already has exited.
69
+ " to send a newline (e.g. for an interactive prompt).`,inputSchema:K.object({pid:K.number(),data:K.string()}),execute:async(t,n)=>(await e()).request(`process_send_input`,{pid:t.pid,data:t.data},{signal:n.abortSignal})})),process_kill:fh(({client:e})=>({description:`Kill a process by PID that was started by the execute_bash tool.`,inputSchema:K.object({pid:K.number(),signal:K.string()}),execute:async(t,n)=>(await e()).request(`process_kill`,{pid:t.pid,signal:t.signal},{signal:n.abortSignal})})),process_wait:fh(({client:e})=>({description:`This tool waits for a process to exit, or returns instantly if the process already has exited.
70
70
 
71
71
  Output from the process will be returned along with it's exit code, duration, and whether the process is still running.
72
72
 
73
73
  IMPORTANT: ALWAYS use this tool to determine the status of a process. NEVER use "ps".
74
- `,inputSchema:q.object({pid:q.number(),timeout_ms:q.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 ph({client:await e(),pid:t.pid,abortSignal:n.abortSignal,timeoutMs:t.timeout_ms}))yield r},toModelOutput:dh})),read_file:uh(({client:e})=>be({description:`Reads a file from the workspace filesystem. You can access any file directly by using this tool.
74
+ `,inputSchema:K.object({pid:K.number(),timeout_ms:K.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 hh({client:await e(),pid:t.pid,abortSignal:n.abortSignal,timeoutMs:t.timeout_ms}))yield r},toModelOutput:ph})),read_file:fh(({client:e})=>xe({description:`Reads a file from the workspace filesystem. You can access any file directly by using this tool.
75
75
  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.
76
76
 
77
77
  Usage:
78
78
  - The path parameter can be a relative path or an absolute path
79
- - By default, it reads up to ${ch.readLineLimit} lines starting from the beginning of the file
79
+ - By default, it reads up to ${uh.readLineLimit} lines starting from the beginning of the file
80
80
  - 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
81
- - Any lines longer than ${ch.readLineLengthLimit} characters will be truncated
81
+ - Any lines longer than ${uh.readLineLengthLimit} characters will be truncated
82
82
  - Results are returned using cat -n format, with line numbers starting at 1
83
83
  - 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
84
84
  - 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.
85
85
  - 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
86
- - If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:q.object({file_path:q.string(),line_offset:q.number(),line_limit:q.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:uh(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:q.object({file_path:q.string(),content:q.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:uh(({client:e})=>be({description:`Reads a directory from the workspace filesystem.`,inputSchema:q.object({directory_path:q.string()}),execute:async(t,n)=>(await e()).request(`read_directory`,{path:t.directory_path})})),edit_file:uh(({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.
86
+ - If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:K.object({file_path:K.string(),line_offset:K.number(),line_limit:K.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:fh(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:K.object({file_path:K.string(),content:K.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:fh(({client:e})=>xe({description:`Reads a directory from the workspace filesystem.`,inputSchema:K.object({directory_path:K.string()}),execute:async(t,n)=>(await e()).request(`read_directory`,{path:t.directory_path})})),edit_file:fh(({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.
87
87
 
88
88
  Before using this tool:
89
89
 
@@ -121,7 +121,7 @@ When making edits:
121
121
  If you want to create a new file, use:
122
122
  - A new file path, including dir name if needed
123
123
  - First edit: empty old_string and the new file's contents as new_string
124
- - Subsequent edits: normal edit operations on the created content`,inputSchema:q.object({file_path:q.string(),edits:q.array(q.object({old_string:q.string(),new_string:q.string(),expected_replacements:q.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;if(n===e.new_string)throw Error(`input is invalid: old_string and new_string are identical.\nString: ${n}`);let r=mh(a,n);if(r===0)throw Error(`input is invalid: String to replace not found in file.\nString: ${n}`);if(r!==t)throw Error(`input is invalid: Found ${r} 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=hh(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=oh(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:uh(({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.
124
+ - Subsequent edits: normal edit operations on the created content`,inputSchema:K.object({file_path:K.string(),edits:K.array(K.object({old_string:K.string(),new_string:K.string(),expected_replacements:K.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=gh(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=_h(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=ch(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:fh(({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.
125
125
 
126
126
  Use this for:
127
127
  - Finding test failures and error messages
@@ -129,7 +129,7 @@ Use this for:
129
129
  - Extracting relevant information from verbose output
130
130
  - Analyzing build or test results
131
131
 
132
- Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:q.object({pid:q.number(),pattern:q.string(),before_lines:q.number(),after_lines:q.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}}}))},ph=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()}};q.union([q.object({pid:q.number(),ansiOutput:q.string()}),q.object({pid:q.number(),title:q.string().optional(),command:q.string(),args:q.array(q.string()),cwd:q.string(),env:q.record(q.string(),q.string()),ansiOutput:q.string(),plainOutput:q.object({totalLines:q.number(),lines:q.array(q.string())}),durationMs:q.number(),exitCode:q.number().optional(),exitSignal:q.number().optional(),stillRunning:q.boolean()})]);const mh=(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},hh=(e,t,n)=>t.length===0?e:e.split(t).join(n),gh={scout:{".env.local.hbs":`# Store local environment variables here.
132
+ Example: After running tests with \`workspace_bash\`, use this to find all FAIL: lines rather than re-running the test command.`,inputSchema:K.object({pid:K.number(),pattern:K.string(),before_lines:K.number(),after_lines:K.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}}}))},hh=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()}};K.union([K.object({pid:K.number(),ansiOutput:K.string()}),K.object({pid:K.number(),title:K.string().optional(),command:K.string(),args:K.array(K.string()),cwd:K.string(),env:K.record(K.string(),K.string()),ansiOutput:K.string(),plainOutput:K.object({totalLines:K.number(),lines:K.array(K.string())}),durationMs:K.number(),exitCode:K.number().optional(),exitSignal:K.number().optional(),stillRunning:K.boolean()})]);const gh=(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},_h=(e,t,n)=>t.length===0?e:e.split(t).join(n),vh={scout:{".env.local.hbs":`# Store local environment variables here.
133
133
  # They will be used by blink dev for development.
134
134
  {{#each envLocal}}
135
135
  {{this.[0]}}={{this.[1]}}
@@ -704,7 +704,7 @@ agent.serve();
704
704
  },
705
705
  "devDependencies": {
706
706
  "zod": "latest",
707
- "ai": "latest",
707
+ "ai": "^5",
708
708
  {{#if (eq aiProvider "anthropic")}}
709
709
  "@ai-sdk/anthropic": "latest",
710
710
  {{else if (eq aiProvider "openai")}}
@@ -1241,7 +1241,7 @@ agent.serve();
1241
1241
  },
1242
1242
  "devDependencies": {
1243
1243
  "zod": "latest",
1244
- "ai": "latest",
1244
+ "ai": "^5",
1245
1245
  {{#if (eq aiProvider "anthropic")}}
1246
1246
  "@ai-sdk/anthropic": "latest",
1247
1247
  {{else if (eq aiProvider "openai")}}
@@ -1846,7 +1846,7 @@ agent.serve();`,"package.json.hbs":`{
1846
1846
  },
1847
1847
  "devDependencies": {
1848
1848
  "zod": "latest",
1849
- "ai": "latest",
1849
+ "ai": "^5",
1850
1850
  {{#if (eq aiProvider "anthropic")}}
1851
1851
  "@ai-sdk/anthropic": "latest",
1852
1852
  {{else if (eq aiProvider "openai")}}
@@ -1885,7 +1885,7 @@ agent.serve();`,"package.json.hbs":`{
1885
1885
  "types": ["node"]
1886
1886
  }
1887
1887
  }
1888
- `}};function _h(e,t,n){let r,i=ce.createServer(w(async a=>{let o=new URL(a.url,r);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 n?.(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 n?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let r=t.message;return new Response(`Error: ${r}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{i.close()}let c={...e,redirect_url:r},l=`<!DOCTYPE html>
1888
+ `}};function yh(e,t,n){let r,i=le.createServer(w(async a=>{let o=new URL(a.url,r);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 n?.(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 n?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let r=t.message;return new Response(`Error: ${r}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{i.close()}let c={...e,redirect_url:r},l=`<!DOCTYPE html>
1889
1889
  <html>
1890
1890
  <body>
1891
1891
  <form id="f" method="POST" action="${t?`https://github.com/organizations/${t}/settings/apps/new`:`https://github.com/settings/apps/new`}">
@@ -1893,7 +1893,7 @@ agent.serve();`,"package.json.hbs":`{
1893
1893
  </form>
1894
1894
  <script>document.getElementById('f').submit()<\/script>
1895
1895
  </body>
1896
- </html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{i.on(`error`,t),i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}r=`http://127.0.0.1:${n.port}`,e(r)})})}const vh=q.enum([`read`,`write`]),yh=q.union([q.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),q.literal(`check_run`).describe(`Check run created, completed, or requested`),q.literal(`check_suite`).describe(`Check suite completed or requested`),q.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),q.literal(`commit_comment`).describe(`Commit comment created`),q.literal(`create`).describe(`Branch or tag created`),q.literal(`delete`).describe(`Branch or tag deleted`),q.literal(`deployment`).describe(`Deployment created`),q.literal(`deployment_status`).describe(`Deployment status created`),q.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),q.literal(`discussion`).describe(`Discussion created, edited, or deleted`),q.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),q.literal(`fork`).describe(`Repository forked`),q.literal(`gollum`).describe(`Wiki page created or updated`),q.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),q.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),q.literal(`label`).describe(`Label created, edited, or deleted`),q.literal(`member`).describe(`Collaborator added, removed, or edited`),q.literal(`membership`).describe(`Team membership added or removed`),q.literal(`meta`).describe(`GitHub App webhook configuration changed`),q.literal(`milestone`).describe(`Milestone created, closed, or deleted`),q.literal(`organization`).describe(`Organization member added, removed, or invited`),q.literal(`org_block`).describe(`Organization blocked or unblocked a user`),q.literal(`package`).describe(`Package published or updated`),q.literal(`page_build`).describe(`GitHub Pages site built`),q.literal(`project`).describe(`Project created, updated, or deleted`),q.literal(`project_card`).describe(`Project card created, edited, or deleted`),q.literal(`project_column`).describe(`Project column created, updated, or deleted`),q.literal(`public`).describe(`Repository visibility changed to public`),q.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),q.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),q.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),q.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),q.literal(`push`).describe(`Git push to a repository`),q.literal(`registry_package`).describe(`Registry package published or updated`),q.literal(`release`).describe(`Release published or edited`),q.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),q.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),q.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),q.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),q.literal(`star`).describe(`Repository starred or unstarred`),q.literal(`status`).describe(`Commit status created`),q.literal(`team`).describe(`Team created, deleted, or edited`),q.literal(`team_add`).describe(`Repository added to team`),q.literal(`watch`).describe(`User started watching repository`),q.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),q.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),q.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),bh=q.object({name:q.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:q.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.coder.com.`),description:q.string().optional().describe(`The description of the GitHub App.`),public:q.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:q.object({url:q.url(),active:q.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:q.array(q.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:q.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:q.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:q.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:q.array(yh).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:q.record(q.string(),vh).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 xh(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const Sh=q.union([q.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),q.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),q.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),q.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),q.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),q.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),q.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),q.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),q.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),q.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),q.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),q.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),q.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),q.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),q.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),q.literal(`file_created`).describe(`File was created. Requires scope: files:read`),q.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),q.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),q.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),q.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),q.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),q.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),q.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),q.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),q.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),q.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),q.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),q.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),q.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),q.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),q.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),q.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),q.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),q.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),q.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),q.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Ch=q.union([q.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),q.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`),q.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),q.literal(`channels:join`).describe(`Join public channels`),q.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),q.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`),q.literal(`chat:write`).describe(`Send messages as the bot`),q.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),q.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),q.literal(`commands`).describe(`Add and use slash commands`),q.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),q.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),q.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`),q.literal(`files:write`).describe(`Upload, edit, and delete files`),q.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),q.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`),q.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),q.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),q.literal(`im:read`).describe(`View basic information about direct messages with the bot`),q.literal(`im:write`).describe(`Start and manage direct messages with users`),q.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),q.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),q.literal(`metadata.message:read`).describe(`Read message metadata`),q.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),q.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),q.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),q.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),q.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),q.literal(`reminders:read`).describe(`View reminders created by the bot`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders`),q.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),q.literal(`usergroups:read`).describe(`View user groups and their members`),q.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),q.literal(`users.profile:read`).describe(`View profile information about users`),q.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),q.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),q.literal(`users:write`).describe(`Set presence and status for the bot user`)]),wh=q.union([q.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),q.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),q.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),q.literal(`chat:write`).describe(`Send messages on behalf of the user`),q.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),q.literal(`files:read`).describe(`View files on behalf of the user`),q.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),q.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),q.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),q.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),q.literal(`im:history`).describe(`Read direct message history on behalf of the user`),q.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),q.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),q.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),q.literal(`links:write`).describe(`Show URL previews on behalf of the user`),q.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),q.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),q.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),q.literal(`pins:read`).describe(`View pinned items on behalf of the user`),q.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),q.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),q.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),q.literal(`reminders:read`).describe(`View reminders on behalf of the user`),q.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),q.literal(`search:read`).describe(`Search messages and files on behalf of the user`),q.literal(`stars:read`).describe(`View starred items on behalf of the user`),q.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),q.literal(`team:read`).describe(`View workspace information on behalf of the user`),q.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),q.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),q.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),q.literal(`users.profile:write`).describe(`Edit the user's profile information`),q.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),q.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),q.literal(`users:write`).describe(`Set presence for the user`)]),Th=q.object({display_information:q.object({name:q.string().describe(`The name of the Slack app.`),description:q.string().optional().describe(`A short description of the app.`),background_color:q.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:q.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:q.object({bot_user:q.object({display_name:q.string().describe(`The display name for the bot user.`),always_online:q.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:q.object({home_tab_enabled:q.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:q.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:q.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:q.object({assistant_description:q.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:q.array(q.object({command:q.string().regex(/^\//).describe(`The command (must start with /).`),description:q.string().describe(`Description of the command.`),usage_hint:q.string().optional().describe(`Usage hint for the command.`),should_escape:q.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:q.array(q.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:q.object({redirect_urls:q.array(q.url()).optional().describe(`OAuth redirect URLs.`),scopes:q.object({bot:q.array(q.union([Ch,q.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:q.array(q.union([wh,q.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:q.object({event_subscriptions:q.object({request_url:q.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:q.array(q.union([Sh,q.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:q.object({is_enabled:q.boolean().describe(`Enable interactivity.`),request_url:q.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:q.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:q.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:q.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:q.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function Eh(e){let t=new l,n,r;return t.on(`chat`,async({id:r,messages:i,abortSignal:a})=>{let o=i.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);i.splice(o??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
1896
+ </html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{i.on(`error`,t),i.listen(0,`127.0.0.1`,()=>{let n=i.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}r=`http://127.0.0.1:${n.port}`,e(r)})})}const bh=K.enum([`read`,`write`]),xh=K.union([K.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),K.literal(`check_run`).describe(`Check run created, completed, or requested`),K.literal(`check_suite`).describe(`Check suite completed or requested`),K.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),K.literal(`commit_comment`).describe(`Commit comment created`),K.literal(`create`).describe(`Branch or tag created`),K.literal(`delete`).describe(`Branch or tag deleted`),K.literal(`deployment`).describe(`Deployment created`),K.literal(`deployment_status`).describe(`Deployment status created`),K.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),K.literal(`discussion`).describe(`Discussion created, edited, or deleted`),K.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),K.literal(`fork`).describe(`Repository forked`),K.literal(`gollum`).describe(`Wiki page created or updated`),K.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),K.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),K.literal(`label`).describe(`Label created, edited, or deleted`),K.literal(`member`).describe(`Collaborator added, removed, or edited`),K.literal(`membership`).describe(`Team membership added or removed`),K.literal(`meta`).describe(`GitHub App webhook configuration changed`),K.literal(`milestone`).describe(`Milestone created, closed, or deleted`),K.literal(`organization`).describe(`Organization member added, removed, or invited`),K.literal(`org_block`).describe(`Organization blocked or unblocked a user`),K.literal(`package`).describe(`Package published or updated`),K.literal(`page_build`).describe(`GitHub Pages site built`),K.literal(`project`).describe(`Project created, updated, or deleted`),K.literal(`project_card`).describe(`Project card created, edited, or deleted`),K.literal(`project_column`).describe(`Project column created, updated, or deleted`),K.literal(`public`).describe(`Repository visibility changed to public`),K.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),K.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),K.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),K.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),K.literal(`push`).describe(`Git push to a repository`),K.literal(`registry_package`).describe(`Registry package published or updated`),K.literal(`release`).describe(`Release published or edited`),K.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),K.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),K.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),K.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),K.literal(`star`).describe(`Repository starred or unstarred`),K.literal(`status`).describe(`Commit status created`),K.literal(`team`).describe(`Team created, deleted, or edited`),K.literal(`team_add`).describe(`Repository added to team`),K.literal(`watch`).describe(`User started watching repository`),K.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),K.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),K.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),Sh=K.object({name:K.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:K.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.coder.com.`),description:K.string().optional().describe(`The description of the GitHub App.`),public:K.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:K.object({url:K.url(),active:K.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:K.array(K.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:K.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:K.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:K.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:K.array(xh).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:K.record(K.string(),bh).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 Ch(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const wh=K.union([K.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),K.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),K.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),K.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),K.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),K.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),K.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),K.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),K.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),K.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),K.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),K.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),K.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),K.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),K.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),K.literal(`file_created`).describe(`File was created. Requires scope: files:read`),K.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),K.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),K.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),K.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),K.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),K.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),K.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),K.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),K.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),K.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),K.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),K.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),K.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),K.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),K.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),K.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),K.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),K.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),K.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),K.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),K.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),Th=K.union([K.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),K.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`),K.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),K.literal(`channels:join`).describe(`Join public channels`),K.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),K.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`),K.literal(`chat:write`).describe(`Send messages as the bot`),K.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),K.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),K.literal(`commands`).describe(`Add and use slash commands`),K.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),K.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),K.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`),K.literal(`files:write`).describe(`Upload, edit, and delete files`),K.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),K.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`),K.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),K.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),K.literal(`im:read`).describe(`View basic information about direct messages with the bot`),K.literal(`im:write`).describe(`Start and manage direct messages with users`),K.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),K.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),K.literal(`metadata.message:read`).describe(`Read message metadata`),K.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),K.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),K.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),K.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),K.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),K.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),K.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),K.literal(`reminders:read`).describe(`View reminders created by the bot`),K.literal(`reminders:write`).describe(`Create, update, and delete reminders`),K.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),K.literal(`usergroups:read`).describe(`View user groups and their members`),K.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),K.literal(`users.profile:read`).describe(`View profile information about users`),K.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),K.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),K.literal(`users:write`).describe(`Set presence and status for the bot user`)]),Eh=K.union([K.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),K.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),K.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),K.literal(`chat:write`).describe(`Send messages on behalf of the user`),K.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),K.literal(`files:read`).describe(`View files on behalf of the user`),K.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),K.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),K.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),K.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),K.literal(`im:history`).describe(`Read direct message history on behalf of the user`),K.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),K.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),K.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),K.literal(`links:write`).describe(`Show URL previews on behalf of the user`),K.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),K.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),K.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),K.literal(`pins:read`).describe(`View pinned items on behalf of the user`),K.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),K.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),K.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),K.literal(`reminders:read`).describe(`View reminders on behalf of the user`),K.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),K.literal(`search:read`).describe(`Search messages and files on behalf of the user`),K.literal(`stars:read`).describe(`View starred items on behalf of the user`),K.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),K.literal(`team:read`).describe(`View workspace information on behalf of the user`),K.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),K.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),K.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),K.literal(`users.profile:write`).describe(`Edit the user's profile information`),K.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),K.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),K.literal(`users:write`).describe(`Set presence for the user`)]),Dh=K.object({display_information:K.object({name:K.string().describe(`The name of the Slack app.`),description:K.string().optional().describe(`A short description of the app.`),background_color:K.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:K.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:K.object({bot_user:K.object({display_name:K.string().describe(`The display name for the bot user.`),always_online:K.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:K.object({home_tab_enabled:K.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:K.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:K.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:K.object({assistant_description:K.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:K.array(K.object({command:K.string().regex(/^\//).describe(`The command (must start with /).`),description:K.string().describe(`Description of the command.`),usage_hint:K.string().optional().describe(`Usage hint for the command.`),should_escape:K.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:K.array(K.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:K.object({redirect_urls:K.array(K.url()).optional().describe(`OAuth redirect URLs.`),scopes:K.object({bot:K.array(K.union([Th,K.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:K.array(K.union([Eh,K.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:K.object({event_subscriptions:K.object({request_url:K.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:K.array(K.union([wh,K.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:K.object({is_enabled:K.boolean().describe(`Enable interactivity.`),request_url:K.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:K.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:K.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:K.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:K.boolean().optional().default(!1).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function Oh(e){let t=new l,n,r;return t.on(`chat`,async({id:r,messages:i,abortSignal:a})=>{let o=i.findLastIndex(e=>!e.metadata||typeof e.metadata!=`object`?!1:e.metadata.__blink_mode===`run`);i.splice(o??0,0,{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
1897
1897
 
1898
1898
  The agent source code is in the directory: "${e.directory}".
1899
1899
  You must *ONLY* make changes to files in this directory, regardless of what other messages in your context say.
@@ -1920,9 +1920,9 @@ You are *NOT* responsible for:
1920
1920
  - Continuing any work the run mode agent started
1921
1921
 
1922
1922
  Your job is to improve the agent based on run mode failures, NOT to complete the user's original run-mode request yourself.
1923
- `}]});let{execute_bash:s,execute_bash_sync:c,...l}=fh,u={execute_bash:s,execute_bash_sync:c};process.env.BLINK_AUTO_APPROVE||(u=await O.withApproval({messages:i,tools:u}));let d={...l,...u,...await O.withApproval({messages:i,tools:{get_reverse_tunnel_url:be({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.
1923
+ `}]});let{execute_bash:s,execute_bash_sync:c,...l}=mh,u={execute_bash:s,execute_bash_sync:c};process.env.BLINK_AUTO_APPROVE||(u=await D.withApproval({messages:i,tools:u}));let d={...l,...u,...await D.withApproval({messages:i,tools:{get_reverse_tunnel_url:xe({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.
1924
1924
 
1925
- You *MUST* use this when creating GitHub, Slack, or other apps unless the user explicitly directs you otherwise.`,inputSchema:q.object({}),execute:async()=>e.getDevhookUrl()}),create_github_app:be({description:`Creates a GitHub App using GitHub's app manifest flow.
1925
+ You *MUST* use this when creating GitHub, Slack, or other apps unless the user explicitly directs you otherwise.`,inputSchema:K.object({}),execute:async()=>e.getDevhookUrl()}),create_github_app:xe({description:`Creates a GitHub App using GitHub's app manifest flow.
1926
1926
 
1927
1927
  IMPORTANT: You must explain to the user what's happening and why:
1928
1928
  - Tell them this will open a localhost URL that redirects them to GitHub
@@ -1934,14 +1934,14 @@ You *must* ensure the organization is correct - ask the user prior.
1934
1934
 
1935
1935
  Once they complete the app creation, environment variables will be automatically set in the provided environment file.
1936
1936
 
1937
- After approval, the URL will be opened automatically in their browser.`,inputSchema:q.object({manifest:bh,envFile:q.enum([`local`,`production`]).describe(`The environment file to put credentials in on app creation.`),organization:q.string().optional().describe(`An optional GitHub organization the app should be created for. Leave blank to create a personal app.`)}),execute:async(n,i)=>{let a=await _h(n.manifest,n.organization,async(i,a)=>{if(i){await t.chat.sendMessages(r,[{role:`assistant`,parts:[{type:`text`,text:`Failed to create GitHub App: ${i.message}`}]}]);return}if(a){try{let t=n.envFile===`production`?`.env.production`:`.env.local`,r=ue(e.directory,t),i=``;try{i=await xe(r,`utf-8`)}catch{}let o=`
1937
+ After approval, the URL will be opened automatically in their browser.`,inputSchema:K.object({manifest:Sh,envFile:K.enum([`local`,`production`]).describe(`The environment file to put credentials in on app creation.`),organization:K.string().optional().describe(`An optional GitHub organization the app should be created for. Leave blank to create a personal app.`)}),execute:async(n,i)=>{let a=await yh(n.manifest,n.organization,async(i,a)=>{if(i){await t.chat.sendMessages(r,[{role:`assistant`,parts:[{type:`text`,text:`Failed to create GitHub App: ${i.message}`}]}]);return}if(a){try{let t=n.envFile===`production`?`.env.production`:`.env.local`,r=de(e.directory,t),i=``;try{i=await Se(r,`utf-8`)}catch{}let o=`
1938
1938
  # GitHub App credentials (created with the blink edit agent)
1939
1939
  GITHUB_APP_ID=${a.id}
1940
1940
  GITHUB_CLIENT_ID=${a.client_id}
1941
1941
  GITHUB_CLIENT_SECRET=${a.client_secret}
1942
1942
  GITHUB_WEBHOOK_SECRET=${a.webhook_secret}
1943
1943
  GITHUB_PRIVATE_KEY="${btoa(a.pem)}"
1944
- `;await Se(r,i+o,`utf-8`)}catch(e){await t.chat.sendMessages(r,[{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 t.chat.sendMessages(r,[{role:`assistant`,parts:[{type:`text`,text:`GitHub App created successfully. The following environment variables have been set in the ${n.envFile} environment file: GITHUB_APP_ID, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, GITHUB_WEBHOOK_SECRET, GITHUB_PRIVATE_KEY.`}]}])}});return await bp(a),`Opening GitHub App creation URL in browser: ${a}`}}),create_slack_app:be({description:`Creates a Slack App with the provided manifest.
1944
+ `;await Ce(r,i+o,`utf-8`)}catch(e){await t.chat.sendMessages(r,[{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 t.chat.sendMessages(r,[{role:`assistant`,parts:[{type:`text`,text:`GitHub App created successfully. The following environment variables have been set in the ${n.envFile} environment file: GITHUB_APP_ID, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, GITHUB_WEBHOOK_SECRET, GITHUB_PRIVATE_KEY.`}]}])}});return await bp(a),`Opening GitHub App creation URL in browser: ${a}`}}),create_slack_app:xe({description:`Creates a Slack App with the provided manifest.
1945
1945
 
1946
1946
  IMPORTANT - when ran, you MUST:
1947
1947
  1. Inform the user that the URL has opened in their browser automatically to *Slack*.
@@ -1949,11 +1949,11 @@ IMPORTANT - when ran, you MUST:
1949
1949
  3. Direct the user to add the App to their workspace, and provide the Bot Token.
1950
1950
 
1951
1951
  You MUST GUIDE THE USER through these steps - do not provide all the steps at once.
1952
- `,inputSchema:Th,execute:async(e,t)=>{let n=xh(e);return await bp(n),`Opened Slack App creation URL in browser: ${n}`}})}}),message_user_agent:be({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.
1952
+ `,inputSchema:Dh,execute:async(e,t)=>{let n=Ch(e);return await bp(n),`Opened Slack App creation URL in browser: ${n}`}})}}),message_user_agent:xe({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.
1953
1953
 
1954
- 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:q.object({message:q.string()}),execute:async(e,t)=>{if(!n)return`User agent URL is not available. Cannot test user agent.`;let r=await new Ec({baseUrl:n}).chat({id:crypto.randomUUID(),messages:[{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:e.message}]}]},{signal:t.abortSignal}),i=ve({stream:r}),a;for await(let e of i)a=e;return a}}),typecheck_agent:be({description:`*ONLY* typecheck the agent being worked on. Reports all syntax errors.
1954
+ 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:K.object({message:K.string()}),execute:async(e,t)=>{if(!n)return`User agent URL is not available. Cannot test user agent.`;let r=await new Ec({baseUrl:n}).chat({id:crypto.randomUUID(),messages:[{id:crypto.randomUUID(),role:`user`,parts:[{type:`text`,text:e.message}]}]},{signal:t.abortSignal}),i=ye({stream:r}),a;for await(let e of i)a=e;return a}}),typecheck_agent:xe({description:`*ONLY* typecheck the agent being worked on. Reports all syntax errors.
1955
1955
 
1956
- Do *NOT* confuse this with tools in run mode for typechecking.`,inputSchema:q.object({}),execute:async()=>{let t=Ce(`node`,[ue(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}}})},f=ge(i,{ignoreIncompleteToolCalls:!0,tools:d});f.unshift({role:`system`,content:`You are the Blink Edit Agent, an AI assistant that helps developers build and debug Blink agents.
1956
+ Do *NOT* confuse this with tools in run mode for typechecking.`,inputSchema:K.object({}),execute:async()=>{let t=we(`node`,[de(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}}})},f=_e(i,{ignoreIncompleteToolCalls:!0,tools:d});f.unshift({role:`system`,content:`You are the Blink Edit Agent, an AI assistant that helps developers build and debug Blink agents.
1957
1957
 
1958
1958
  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.
1959
1959
 
@@ -1986,4 +1986,4 @@ Slack:
1986
1986
  1. *ALWAYS* use the \`typecheck_agent\` tool to check for type errors before making changes. NEVER invoke \`tsc\` directly.
1987
1987
  2. Use the \`message_user_agent\` tool to test the agent after you make changes.
1988
1988
  </agent_development>
1989
- `});let p=gh.scratch[`AGENTS.md`];try{p=await xe(ue(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),ye({model:Oh(e.env),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function Dh(e){if(e.ANTHROPIC_API_KEY)return _n({apiKey:e.ANTHROPIC_API_KEY,baseURL:e.ANTHROPIC_BASE_URL}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return jo({apiKey:e.OPENAI_API_KEY,baseURL:e.OPENAI_BASE_URL}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return C({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function Oh(e){let t=Dh(e);if(!t)throw Error(`No API key available for edit mode`);return t}function kh(e){let[t,n]=G(void 0),[r,i]=G(void 0),[a,o]=G(!1),s=W(void 0);return U(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!Dh(e.env)){o(!0);return}o(!1);let a;return(async()=>{s.current=Eh({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await Ah(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let o=new Ec({baseUrl:`http://127.0.0.1:${r}`}),c=new Tc;for(a=c;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n({client:o,lock:c})})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,(async()=>{try{var e=Dc();e.u(await a?.write()),t.abort()}catch(t){e.e=t}finally{e.d()}})()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),Te(()=>({agent:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function Ah(){let e=le();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function jh(e){let{directory:t}=e,[n,r]=G(!1),[i,a]=G(`run`),o=W(`run`);U(()=>{o.current=i},[i]);let s=H(t=>{a(t),e.onModeChange?.(t)},[e.onModeChange]),c=H(()=>{s(i===`run`?`edit`:`run`)},[i,s]),{error:l,status:u,result:d,entry:f}=kp({directory:t,logger:e.logger,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),p=Tp({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),m=Bm(t,e.logger),h=Te(()=>{let e=p.token,t={...process.env,...m};return e&&(t.BLINK_TOKEN=e),Object.fromEntries(Object.entries(t).filter(([e,t])=>t!==void 0))},[m,p.token]),g=W(void 0);U(()=>{let t=Object.keys(h);if(t.length===g.current||g.current===void 0){g.current=t.length;return}g.current=t.length,e.onEnvLoaded?.(t)},[h,e.onEnvLoaded]);let _=W(void 0),v=Te(()=>Pm({port:0,dataDirectory:ue(t,`.blink`),getAgent:()=>_.current}),[t]),{agent:y,logs:b,error:x,capabilities:S}=Oc({buildResult:d,env:h,apiServerUrl:v.url}),{agent:C,error:w,missingApiKey:T,setUserAgentUrl:D}=kh({directory:t,apiServerUrl:v.url,env:h,getDevhookUrl:H(()=>{let e=um(t)??dm(t);return P(e),`https://${e}.blink.host`},[t])}),[O,k]=G(`00000000-0000-0000-0000-000000000000`);U(()=>{_.current=y},[y]),U(()=>{y&&D(y.client.baseUrl),(i===`run`&&!y||i===`edit`&&!C)&&v.getChatManager(O)?.stopStreaming()},[y,C,i,O,v,D]);let A=W(void 0),j=sm({chatId:O,agent:i===`run`?y:C,chatsDirectory:v.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&A.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:A.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=o.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:o.current,metadata:t}},filterMessages:e=>o.current===`edit`?!0:!(im(e.metadata)||am(e)||e.mode===`edit`),onError:t=>{e.onError?.(`${cf.red(`⚙ [Chat Error]`)} ${cf.gray(t)}`)}}),M=W(0);U(()=>{if(b.length===M.current)return;let t=M.current;for(let n of b.slice(t))e.onAgentLog?.(n);M.current=b.length},[b,e.onAgentLog,j.upsertMessage]);let[N,ee]=G([]);U(()=>{v.listChats().then(e=>{ee(e.map(e=>e.key))})},[v]),U(()=>{O&&!N.includes(O)&&ee(e=>[...e,O])},[O,N]);let[te,P]=G(()=>lm(t)?um(t):dm(t)),F=Im({id:te,directory:t,logger:e.logger,disabled:!S?.request,onRequest:async t=>{if(!y)throw Error(`No agent`);let n=new URL(t.url),r=new URL(y.client.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(t){return e.logger.error(`system`,`Error sending request to user's agent:`,t),new Response(`Internal server error`,{status:500})}}});U(()=>{F.status!==`connected`||!F.url||e.onDevhookConnected?.(F.url)},[F.status,F.url]);let{schema:I,options:ne,error:L,setOption:re}=Fm({agent:i===`run`?y?.client:C?.client,capabilities:S,messages:j.messages});U(()=>{A.current=ne},[ne]);let R=Te(()=>{let e=new Map;return x&&i===`run`&&e.set(`agent`,x.message),w&&i===`edit`&&e.set(`editAgent`,`Edit agent error: ${w.message}`),L&&e.set(`options`,`Options error: ${L.message}`),e},[x,w,L,i]),ie=W(new Map);U(()=>{let t=ie.current,n=R;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ie.current=new Map(n)},[R,e.onError]);let z=Te(()=>{let e=[...j.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e)return;let t=e.parts.filter(_e);if(t.length!==0&&t.some(e=>E(e.output)&&e.output.outcome===`pending`))return e},[j.messages]),ae=W(void 0),oe=H(async(e,t)=>{if(!z)return;t&&e&&r(!0);let n=j.messages.reverse().find(e=>e.role!==`assistant`||!Array.isArray(e.parts)?!1:e.parts.some(e=>`output`in e&&E(e.output)&&e.output.outcome===`pending`));if(!n)return;ae.current=n.id;let i=n.parts.map(t=>t.output&&E(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await j.upsertMessage({...n,parts:i}),await j.start()},[z,j]);U(()=>{n&&z&&oe(!0)},[n,z,oe]);let se=H(()=>{let e=crypto.randomUUID();k(e),ee(t=>[...t,e])},[]),ce=H(e=>{k(e)},[]),le=Te(()=>{if(z)return{message:z,approve:e=>oe(!0,e),reject:()=>oe(!1),autoApproveEnabled:n}},[z,oe,n]),B=Te(()=>{let e=j.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}}},[j.messages]),de=Te(()=>{if(j.status!==`streaming`)return!1;if(!j.streamingMessage)return!0;let e=j.streamingMessage.parts.filter(_e);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[j.status,j.streamingMessage]);return{mode:i,setMode:s,toggleMode:c,chat:j,chats:N,switchChat:ce,newChat:se,build:{status:u,error:l,entrypoint:f},devhook:{connected:F.status===`connected`,url:F.status===`connected`?F.url:void 0},capabilities:S,options:{schema:I,selected:ne,error:L,setOption:re},approval:le,tokenUsage:B,auth:p,server:v,showWaitingPlaceholder:de,editModeMissingApiKey:T}}export{Dp as Logger,Op as LoggerContext,Oc as useAgent,Tp as useAuth,kp as useBundler,sm as useChat,jh as useDevMode,Im as useDevhook,Bm as useDotenv,kh as useEditAgent,Fm as useOptions};
1989
+ `});let p=vh.scratch[`AGENTS.md`];try{p=await Se(de(e.directory,`AGENTS.md`),`utf-8`)}catch{}return f.unshift({role:`system`,content:p}),be({model:Ah(e.env),messages:f,maxOutputTokens:64e3,tools:d,abortSignal:a,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:t,setUserAgentUrl:e=>{n=e},cleanup:()=>{r&&=(r.close(),void 0)}}}function kh(e){if(e.ANTHROPIC_API_KEY)return _n({apiKey:e.ANTHROPIC_API_KEY,baseURL:e.ANTHROPIC_BASE_URL}).chat(`claude-sonnet-4-5`);if(e.OPENAI_API_KEY)return jo({apiKey:e.OPENAI_API_KEY,baseURL:e.OPENAI_BASE_URL}).chat(`gpt-5`);if(e.AI_GATEWAY_API_KEY)return C({apiKey:e.AI_GATEWAY_API_KEY})(`anthropic/claude-sonnet-4-5`)}function Ah(e){let t=kh(e);if(!t)throw Error(`No API key available for edit mode`);return t}function jh(e){let[t,n]=W(void 0),[r,i]=W(void 0),[a,o]=W(!1),s=U(void 0);return H(()=>{let t=new AbortController,r=!1;if(i(void 0),n(void 0),!kh(e.env)){o(!0);return}o(!1);let a;return(async()=>{s.current=Oh({directory:e.directory,env:e.env,getDevhookUrl:e.getDevhookUrl});let r=await Mh(),i=s.current.agent.serve({port:r,host:`127.0.0.1`,apiUrl:e.apiServerUrl});t.signal.addEventListener(`abort`,()=>{try{i.close()}catch{}s.current?.cleanup()});let o=new Ec({baseUrl:`http://127.0.0.1:${r}`}),c=new Tc;for(a=c;!t.signal.aborted;){try{await o.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(t.signal.aborted)throw t.signal.reason;n({client:o,lock:c})})().catch(e=>{r||i(e instanceof Error?e:Error(String(e)))}),()=>{r=!0,(async()=>{try{var e=Dc();e.u(await a?.write()),t.abort()}catch(t){e.e=t}finally{e.d()}})()}},[e.directory,e.apiServerUrl,e.env,e.getDevhookUrl]),Ee(()=>({agent:t,error:r,missingApiKey:a,setUserAgentUrl:e=>{s.current?.setUserAgentUrl(e)}}),[t,r,a])}async function Mh(){let e=ue();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function Nh(e){let{directory:t}=e,[n,r]=W(!1),[i,a]=W(`run`),o=U(`run`);H(()=>{o.current=i},[i]);let s=V(t=>{a(t),e.onModeChange?.(t)},[e.onModeChange]),c=V(()=>{s(i===`run`?`edit`:`run`)},[i,s]),{error:l,status:u,result:d,entry:f}=jp({directory:t,logger:e.logger,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),p=Dp({autoCheck:!0,onAuthChange:e.onAuthChange,onLoginUrl:e.onLoginUrl}),m=Hm(t,e.logger),h=Ee(()=>{let e=p.token,t={...process.env,...m};return e&&(t.BLINK_TOKEN=e),Object.fromEntries(Object.entries(t).filter(([e,t])=>t!==void 0))},[m,p.token]),g=U(void 0);H(()=>{let t=Object.keys(h);if(t.length===g.current||g.current===void 0){g.current=t.length;return}g.current=t.length,e.onEnvLoaded?.(t)},[h,e.onEnvLoaded]);let _=U(void 0),v=Ee(()=>Im({port:0,dataDirectory:de(t,`.blink`),getAgent:()=>_.current}),[t]),{agent:y,logs:b,error:x,capabilities:S}=Oc({buildResult:d,env:h,apiServerUrl:v.url}),{agent:C,error:w,missingApiKey:ee,setUserAgentUrl:E}=jh({directory:t,apiServerUrl:v.url,env:h,getDevhookUrl:V(()=>{let e=fm(t)??pm(t);return N(e),`https://${e}.blink.host`},[t])}),[D,O]=W(`00000000-0000-0000-0000-000000000000`);H(()=>{_.current=y},[y]),H(()=>{y&&E(y.client.baseUrl),(i===`run`&&!y||i===`edit`&&!C)&&v.getChatManager(D)?.stopStreaming()},[y,C,i,D,v,E]);let k=U(void 0),A=lm({chatId:D,agent:i===`run`?y:C,chatsDirectory:v.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&k.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:k.current}:e.metadata;return typeof t==`object`&&t&&(t.__blink_mode=o.current),{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:o.current,metadata:t}},filterMessages:e=>o.current===`edit`?!0:!(om(e.metadata)||sm(e)||e.mode===`edit`),onError:t=>{e.onError?.(`${_f.red(`⚙ [Chat Error]`)} ${_f.gray(t)}`)}}),j=U(0);H(()=>{if(b.length===j.current)return;let t=j.current;for(let n of b.slice(t))e.onAgentLog?.(n);j.current=b.length},[b,e.onAgentLog,A.upsertMessage]);let[M,te]=W([]);H(()=>{v.listChats().then(e=>{te(e.map(e=>e.key))})},[v]),H(()=>{D&&!M.includes(D)&&te(e=>[...e,D])},[D,M]);let[ne,N]=W(()=>dm(t)?fm(t):pm(t)),P=Rm({id:ne,directory:t,logger:e.logger,disabled:!S?.request,onRequest:async t=>{if(!y)throw Error(`No agent`);let n=new URL(t.url),r=new URL(y.client.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(t){return e.logger.error(`system`,`Error sending request to user's agent:`,t),new Response(`Internal server error`,{status:500})}}});H(()=>{P.status!==`connected`||!P.url||e.onDevhookConnected?.(P.url)},[P.status,P.url]);let{schema:F,options:re,error:I,setOption:ie}=Lm({agent:i===`run`?y?.client:C?.client,capabilities:S,messages:A.messages});H(()=>{k.current=re},[re]);let L=Ee(()=>{let e=new Map;return x&&i===`run`&&e.set(`agent`,x.message),w&&i===`edit`&&e.set(`editAgent`,`Edit agent error: ${w.message}`),I&&e.set(`options`,`Options error: ${I.message}`),e},[x,w,I,i]),ae=U(new Map);H(()=>{let t=ae.current,n=L;for(let[r,i]of n.entries())t.get(r)!==i&&e.onError?.(i);for(let e of t.keys())n.has(e);ae.current=new Map(n)},[L,e.onError]);let R=Ee(()=>{let e=[...A.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e)return;let t=e.parts.filter(ve);if(t.length!==0&&t.some(e=>T(e.output)&&e.output.outcome===`pending`))return e},[A.messages]),oe=U(void 0),se=V(async(e,t)=>{if(!R)return;t&&e&&r(!0);let n=A.messages.reverse().find(e=>e.role!==`assistant`||!Array.isArray(e.parts)?!1:e.parts.some(e=>`output`in e&&T(e.output)&&e.output.outcome===`pending`));if(!n)return;oe.current=n.id;let i=n.parts.map(t=>t.output&&T(t.output)&&t.output.outcome===`pending`?{...t,output:{...t.output,outcome:e?`approved`:`rejected`}}:t);await A.upsertMessage({...n,parts:i}),await A.start()},[R,A]);H(()=>{n&&R&&se(!0)},[n,R,se]);let ce=V(()=>{let e=crypto.randomUUID();O(e),te(t=>[...t,e])},[]),le=V(e=>{O(e)},[]),ue=Ee(()=>{if(R)return{message:R,approve:e=>se(!0,e),reject:()=>se(!1),autoApproveEnabled:n}},[R,se,n]),z=Ee(()=>{let e=A.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}}},[A.messages]),fe=Ee(()=>{if(A.status!==`streaming`)return!1;if(!A.streamingMessage)return!0;let e=A.streamingMessage.parts.filter(ve);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[A.status,A.streamingMessage]);return{mode:i,setMode:s,toggleMode:c,chat:A,chats:M,switchChat:le,newChat:ce,build:{status:u,error:l,entrypoint:f},devhook:{connected:P.status===`connected`,url:P.status===`connected`?P.url:void 0},capabilities:S,options:{schema:F,selected:re,error:I,setOption:ie},approval:ue,tokenUsage:z,auth:p,server:v,showWaitingPlaceholder:fe,editModeMissingApiKey:ee}}export{kp as Logger,Ap as LoggerContext,Oc as useAgent,Dp as useAuth,jp as useBundler,lm as useChat,Nh as useDevMode,Rm as useDevhook,Hm as useDotenv,jh as useEditAgent,Lm as useOptions};