@aventurevc/aventure-cli 0.8.540 → 0.8.542

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 (43) hide show
  1. package/dist/aventure-cli/command-catalog.compact.txt +1 -0
  2. package/dist/aventure-cli/index.js +1 -1
  3. package/dist/aventure-cli/unified-operations.json +21 -2
  4. package/dist/chunks/{api-key-credential-verification--t6xqyOf.js → api-key-credential-verification-B6huNLH0.js} +1 -1
  5. package/dist/chunks/{api-key-credential-verification-DumwjaIx.js → api-key-credential-verification-OsWZKwl7.js} +1 -1
  6. package/dist/chunks/{api-key-login-BfIKEuSP.js → api-key-login-BM_Qf1G7.js} +1 -1
  7. package/dist/chunks/{auth-status-check-Cpr00fVl.js → auth-status-check-BtidwdOi.js} +1 -1
  8. package/dist/chunks/{auth-status-check-C_6QK43e.js → auth-status-check-CIhiEOp6.js} +1 -1
  9. package/dist/chunks/{auth-status-render-CNRHMyym.js → auth-status-render-BB0kFNVt.js} +1 -1
  10. package/dist/chunks/{aventure-cli-DyJGWZir.js → aventure-cli-jn56A9U7.js} +5 -5
  11. package/dist/chunks/{builtin-auth-yLw-NtDA.js → builtin-auth-m2FPArfQ.js} +4 -4
  12. package/dist/chunks/{builtin-run-wait-DrGSEY9-.js → builtin-run-wait-DLDJ7yRy.js} +1 -1
  13. package/dist/chunks/{builtin-update-CYtY3qyJ.js → builtin-update-B_kUIu_9.js} +1 -1
  14. package/dist/chunks/{completion-Ds-cNY-l.js → completion-B_JaUgpy.js} +1 -1
  15. package/dist/chunks/{logout-DxCEYVMK.js → logout-B0l8iuqb.js} +1 -1
  16. package/dist/chunks/logout-B0pjuc7f.js +1 -0
  17. package/dist/chunks/mcp-generation-contract-BlpBOJIz.js +1 -0
  18. package/dist/chunks/{mcp-generation-contract-CJ_yoZ27.js → mcp-generation-contract-BuyNZRp_.js} +1 -1
  19. package/dist/chunks/{oauth-bearer-credential-MfThcH_T.js → oauth-bearer-credential-BR4awrGN.js} +1 -1
  20. package/dist/chunks/oauth-bearer-credential-CtO3WUQu.js +1 -0
  21. package/dist/chunks/{oauth-login-GMqpfheN.js → oauth-login-CLs5I6qE.js} +1 -1
  22. package/dist/chunks/{oauth-login-B9nepzT3.js → oauth-login-S-dSN87V.js} +1 -1
  23. package/dist/chunks/{openapi-call-BC15WKDc.js → openapi-call-BI8CGnE_.js} +1 -1
  24. package/dist/chunks/{openapi-call-clLC3Asi.js → openapi-call-ClCLSAAC.js} +1 -1
  25. package/dist/chunks/openapi-commands-BdBexCKS.js +1 -0
  26. package/dist/chunks/{openapi-commands-CNNA8W8A.js → openapi-commands-CGbbB5-6.js} +1 -1
  27. package/dist/chunks/openapi-snapshot.json +1 -1
  28. package/dist/chunks/{operations-BODdM2Ga.js → operations-Bvggt3LV.js} +2 -2
  29. package/dist/chunks/operations-catalog-CQFKHke7.js +1 -0
  30. package/dist/chunks/{operations-catalog-CRvCSEb4.js → operations-catalog-JFOVBOxk.js} +1 -1
  31. package/dist/chunks/{output-xAunlynM.js → output-CymBUz8d.js} +1 -1
  32. package/dist/chunks/{output-DLHdNwfR.js → output-RQ11ln2r.js} +1 -1
  33. package/dist/chunks/{parse-error-hint-DIpiPEri.js → parse-error-hint-BaVmjYnp.js} +1 -1
  34. package/dist/chunks/{search-narrowing-BSrVT7gb.js → search-narrowing-CxgU8Ea4.js} +1 -1
  35. package/dist/chunks/startup-auth-BP2U832O.js +1 -0
  36. package/dist/chunks/{startup-auth-DsF2Xejk.js → startup-auth-JHwfu-Sq.js} +1 -1
  37. package/package.json +3 -3
  38. package/dist/chunks/logout-CDi5Sp3N.js +0 -1
  39. package/dist/chunks/mcp-generation-contract-Dls2wCU1.js +0 -1
  40. package/dist/chunks/oauth-bearer-credential-B6BYzOT9.js +0 -1
  41. package/dist/chunks/openapi-commands-B50MxuWH.js +0 -1
  42. package/dist/chunks/operations-catalog-BGLsQcuZ.js +0 -1
  43. package/dist/chunks/startup-auth-ZwE80Yyj.js +0 -1
@@ -1 +1 @@
1
- export{r as MCP_GENERATION_CONTRACT}from"./mcp-generation-contract-Dls2wCU1.js";
1
+ export{r as MCP_GENERATION_CONTRACT}from"./mcp-generation-contract-BlpBOJIz.js";
@@ -1 +1 @@
1
- import{a as e}from"./package-DEeHDoOT.js";import{p as t,t as n}from"./env-kXzA7vyc.js";import{r}from"./auth-resolver-OZXOLfIX.js";import{o as i}from"./logging-Dtl-o9fo.js";import{r as a}from"./api-target-vxev2RKl.js";import{i as o}from"./api-key-credential-DlohywU1.js";import{t as s}from"./credential-redaction-DGm2KLQy.js";import{a as c}from"./credential-store-Du_vAX6P.js";import{t as l}from"./api-key-bearer-credential-8hv5Fce9.js";import{a as u,f as d,h as f,n as p,o as m,t as h}from"./oauth-credential-BGft0Yo9.js";import"./http-credentials-BUPEQD7v.js";async function g(){let e=await o(a(t().host)).catch(()=>null);return e===null||e.state===`unavailable`||e.state===`found`&&e.stored.activation===`active`}async function _(n,r){if(O())return;let o=async(t,a,o,c=!1)=>{if(await l(r),!O())throw c?a:A(t,n,a,o);i({component:n??e().bin[0],event:`oauth_credential_bypassed`,message:`OAuth sign-in is unavailable (${t}); using the stored API key.`,...a===void 0?{}:{error:Error(s(a,D(o)))}})},c=async(t,r,a,c)=>{if(c){let e=await m(t.host).catch(()=>void 0);if(e?.state===`found`&&e.stored.credential.tokens.access_token!==t.credential.tokens.access_token)return await d(e.stored,!1)}try{await p(t.host)}catch(a){i({component:n??e().bin[0],event:`oauth_credential_retire_failed`,message:`the saved OAuth credential is dead (${r}) but could not be removed`,error:Error(s(a,D(t)))})}await o(r,a,t)},d=async(e,t)=>{let r=(n,r)=>c(e,n,r,t),i=e.credential;if(u(i)){if(i.tokens.refresh_token===void 0)return await r(`the saved OAuth credential has expired`);try{i=await x(e)}catch(t){return await w(t)?await r(`aVenture sign-in rejected the saved refresh token`,t):await o(`the saved OAuth credential could not be renewed`,t,e,!await C(t))}}if(t&&i===e.credential&&(T(i)||!await g()))return f(e,i);let a;try{let{verifyUserBearerToken:e}=await import(`./openapi-call-clLC3Asi.js`);a=await e(i.tokens.access_token,new URL(i.client.resource))!==null}catch(t){let{errors:n}=await import(`./webapi-WYeLOETY.js`);return t instanceof n.JWTInvalid?await r(`the saved OAuth credential is malformed`,t):await o(`the saved OAuth credential could not be verified`,t,e,!0)}if(!a)return await r(`the saved OAuth credential was rejected`);await E(e.host,i,n),f(e,i)},f=(e,t)=>{O()||(S({...e,credential:t}),r?.(`oauth`))},h;try{h=a(t().host)}catch(e){throw A(`the API host could not select its OAuth credential`,n,e)}let _;try{_=await m(h)}catch(e){return await o(`the saved OAuth credential is invalid or expired`,e)}if(_.state!==`missing`){if(_.state===`unavailable`)return await o(`the saved OAuth credential could not be read`,Error(_.summary));await d(_.stored,!0)}}async function v(){if(O())return;let e=await m(a(t().host));e.state===`found`&&(process.env[n.authToken]=e.stored.credential.tokens.access_token)}var y;function b(){return y!==void 0}async function x(t){return await c(async()=>{let n=await m(t.host),r=n.state===`found`?n.stored:t,a=y?.stored.host===r.host&&y.replaced===r.credential.tokens.access_token?y.stored:r;if(!u(a.credential))return a.credential;let{renewOAuthTokens:o}=await import(`./oauth-login-GMqpfheN.js`),c=h(a.credential.client,await o(a));try{await f(t.host,c),y=void 0}catch(t){y={replaced:r.credential.tokens.access_token,stored:{...a,credential:c}},i({component:e().bin[0],event:`oauth_credential_store_failed`,message:`renewed OAuth credential could not be stored; this command uses it and the next one falls back to the API key or sign-in`,error:Error(s(t,d(c.tokens)))})}return c})}function S(e){let t=e.credential.tokens.access_token,i,a;r(t,async()=>a===void 0?i!==void 0||process.env[n.authToken]!==t||!u(e.credential)?i:(a=o().finally(()=>{a=void 0}),await a):await a);async function o(){delete process.env[n.authToken];let r=A(`no saved credential could serve this command`,void 0);try{let{materializeCommandCredential:e}=await import(`./startup-auth-DsF2Xejk.js`);if(await e(`required`),O())return}catch(e){r=e}process.env[n.authToken]=t;let{BearerVerificationUnavailableError:a}=await import(`./openapi-call-clLC3Asi.js`);if(r instanceof a)return r.problem;let o=!(r instanceof k),c={status:o?503:401,title:`the saved OAuth sign-in expired during this command and could not be renewed`,type:`about:blank`,detail:s(r,D(e))};return o||(i=c),c}}async function C(e){let{OAuthError:t,OAuthErrorCode:n}=await import(`./dist-kcBdiGJh.js`),r=[n.ServerError,n.TemporarilyUnavailable];return e instanceof t&&!r.includes(e.code)}async function w(e){let{OAuthError:t,OAuthErrorCode:n}=await import(`./dist-kcBdiGJh.js`),r=n.InvalidGrant;return e instanceof t&&e.code===r}function T(e){if(e.verifiedAt===void 0)return!1;let t=Date.now()-new Date(e.verifiedAt).getTime();return t>=0&&t<9e5}async function E(t,n,r){let a=new Date().toISOString();try{await c(async()=>{let e=await m(t);e.state===`found`&&e.stored.credential.tokens.access_token===n.tokens.access_token&&await f(t,{...e.stored.credential,verifiedAt:a})})}catch(t){i({component:r??e().bin[0],event:`oauth_credential_verification_unrecorded`,message:`the saved OAuth credential was verified but the verification could not be stored`,error:Error(s(t,d(n.tokens)))})}}function D(e){return e===void 0?[]:d(e.credential.tokens)}function O(){return(process.env[n.authToken]?.trim().length??0)>0}var k=class extends Error{};function A(t,n,r,i){let a=r===void 0?``:` — ${s(r,D(i))}`;return new k(`OAuth sign-in is required: ${t}. Run \`${n??e().bin[0]} auth login\` before retrying.${a}`)}export{x as i,_ as n,v as r,b as t};
1
+ import{a as e}from"./package-DEeHDoOT.js";import{p as t,t as n}from"./env-kXzA7vyc.js";import{r}from"./auth-resolver-OZXOLfIX.js";import{o as i}from"./logging-Dtl-o9fo.js";import{r as a}from"./api-target-vxev2RKl.js";import{i as o}from"./api-key-credential-DlohywU1.js";import{t as s}from"./credential-redaction-DGm2KLQy.js";import{a as c}from"./credential-store-Du_vAX6P.js";import{t as l}from"./api-key-bearer-credential-8hv5Fce9.js";import{a as u,f as d,h as f,n as p,o as m,t as h}from"./oauth-credential-BGft0Yo9.js";import"./http-credentials-BUPEQD7v.js";async function g(){let e=await o(a(t().host)).catch(()=>null);return e===null||e.state===`unavailable`||e.state===`found`&&e.stored.activation===`active`}async function _(n,r){if(O())return;let o=async(t,a,o,c=!1)=>{if(await l(r),!O())throw c?a:A(t,n,a,o);i({component:n??e().bin[0],event:`oauth_credential_bypassed`,message:`OAuth sign-in is unavailable (${t}); using the stored API key.`,...a===void 0?{}:{error:Error(s(a,D(o)))}})},c=async(t,r,a,c)=>{if(c){let e=await m(t.host).catch(()=>void 0);if(e?.state===`found`&&e.stored.credential.tokens.access_token!==t.credential.tokens.access_token)return await d(e.stored,!1)}try{await p(t.host)}catch(a){i({component:n??e().bin[0],event:`oauth_credential_retire_failed`,message:`the saved OAuth credential is dead (${r}) but could not be removed`,error:Error(s(a,D(t)))})}await o(r,a,t)},d=async(e,t)=>{let r=(n,r)=>c(e,n,r,t),i=e.credential;if(u(i)){if(i.tokens.refresh_token===void 0)return await r(`the saved OAuth credential has expired`);try{i=await x(e)}catch(t){return await w(t)?await r(`aVenture sign-in rejected the saved refresh token`,t):await o(`the saved OAuth credential could not be renewed`,t,e,!await C(t))}}if(t&&i===e.credential&&(T(i)||!await g()))return f(e,i);let a;try{let{verifyUserBearerToken:e}=await import(`./openapi-call-ClCLSAAC.js`);a=await e(i.tokens.access_token,new URL(i.client.resource))!==null}catch(t){let{errors:n}=await import(`./webapi-WYeLOETY.js`);return t instanceof n.JWTInvalid?await r(`the saved OAuth credential is malformed`,t):await o(`the saved OAuth credential could not be verified`,t,e,!0)}if(!a)return await r(`the saved OAuth credential was rejected`);await E(e.host,i,n),f(e,i)},f=(e,t)=>{O()||(S({...e,credential:t}),r?.(`oauth`))},h;try{h=a(t().host)}catch(e){throw A(`the API host could not select its OAuth credential`,n,e)}let _;try{_=await m(h)}catch(e){return await o(`the saved OAuth credential is invalid or expired`,e)}if(_.state!==`missing`){if(_.state===`unavailable`)return await o(`the saved OAuth credential could not be read`,Error(_.summary));await d(_.stored,!0)}}async function v(){if(O())return;let e=await m(a(t().host));e.state===`found`&&(process.env[n.authToken]=e.stored.credential.tokens.access_token)}var y;function b(){return y!==void 0}async function x(t){return await c(async()=>{let n=await m(t.host),r=n.state===`found`?n.stored:t,a=y?.stored.host===r.host&&y.replaced===r.credential.tokens.access_token?y.stored:r;if(!u(a.credential))return a.credential;let{renewOAuthTokens:o}=await import(`./oauth-login-CLs5I6qE.js`),c=h(a.credential.client,await o(a));try{await f(t.host,c),y=void 0}catch(t){y={replaced:r.credential.tokens.access_token,stored:{...a,credential:c}},i({component:e().bin[0],event:`oauth_credential_store_failed`,message:`renewed OAuth credential could not be stored; this command uses it and the next one falls back to the API key or sign-in`,error:Error(s(t,d(c.tokens)))})}return c})}function S(e){let t=e.credential.tokens.access_token,i,a;r(t,async()=>a===void 0?i!==void 0||process.env[n.authToken]!==t||!u(e.credential)?i:(a=o().finally(()=>{a=void 0}),await a):await a);async function o(){delete process.env[n.authToken];let r=A(`no saved credential could serve this command`,void 0);try{let{materializeCommandCredential:e}=await import(`./startup-auth-JHwfu-Sq.js`);if(await e(`required`),O())return}catch(e){r=e}process.env[n.authToken]=t;let{BearerVerificationUnavailableError:a}=await import(`./openapi-call-ClCLSAAC.js`);if(r instanceof a)return r.problem;let o=!(r instanceof k),c={status:o?503:401,title:`the saved OAuth sign-in expired during this command and could not be renewed`,type:`about:blank`,detail:s(r,D(e))};return o||(i=c),c}}async function C(e){let{OAuthError:t,OAuthErrorCode:n}=await import(`./dist-kcBdiGJh.js`),r=[n.ServerError,n.TemporarilyUnavailable];return e instanceof t&&!r.includes(e.code)}async function w(e){let{OAuthError:t,OAuthErrorCode:n}=await import(`./dist-kcBdiGJh.js`),r=n.InvalidGrant;return e instanceof t&&e.code===r}function T(e){if(e.verifiedAt===void 0)return!1;let t=Date.now()-new Date(e.verifiedAt).getTime();return t>=0&&t<9e5}async function E(t,n,r){let a=new Date().toISOString();try{await c(async()=>{let e=await m(t);e.state===`found`&&e.stored.credential.tokens.access_token===n.tokens.access_token&&await f(t,{...e.stored.credential,verifiedAt:a})})}catch(t){i({component:r??e().bin[0],event:`oauth_credential_verification_unrecorded`,message:`the saved OAuth credential was verified but the verification could not be stored`,error:Error(s(t,d(n.tokens)))})}}function D(e){return e===void 0?[]:d(e.credential.tokens)}function O(){return(process.env[n.authToken]?.trim().length??0)>0}var k=class extends Error{};function A(t,n,r,i){let a=r===void 0?``:` — ${s(r,D(i))}`;return new k(`OAuth sign-in is required: ${t}. Run \`${n??e().bin[0]} auth login\` before retrying.${a}`)}export{x as i,_ as n,v as r,b as t};
@@ -0,0 +1 @@
1
+ export{n as materializeCliOAuthBearerCredential,r as materializeSavedCliOAuthBearerCredential}from"./oauth-bearer-credential-BR4awrGN.js";
@@ -1 +1 @@
1
- export{n as fetchAuthProviderCatalog,r as loginOAuthCredential,i as renewOAuthTokens}from"./oauth-login-B9nepzT3.js";
1
+ export{n as fetchAuthProviderCatalog,r as loginOAuthCredential,i as renewOAuthTokens}from"./oauth-login-S-dSN87V.js";
@@ -1,4 +1,4 @@
1
- import{R as e}from"./webapi-B2JTupyg.js";import{f as t,o as n,s as r,u as i}from"./dist-Dt0qAmdj.js";import{Gt as a,Yt as o}from"./auth-BNDyLTqp-z6VNZXaE.js";import{p as s}from"./env-kXzA7vyc.js";import{c,r as l}from"./result-envelope-fUFmAu5G.js";import{a as u,n as d,o as f}from"./openapi-call-BC15WKDc.js";import{a as ee,r as p}from"./api-target-vxev2RKl.js";import{n as m,t as h}from"./credential-redaction-DGm2KLQy.js";import{n as g,s as te}from"./credential-store-Du_vAX6P.js";import"./dist-oUS6BQ43.js";import{a as ne,c as _,d as v,f as y,h as b,m as x,p as S,r as C,s as w,t as T,u as E}from"./oauth-credential-BGft0Yo9.js";import{t as re}from"./provider-catalog-CT1LnhCO.js";import{i as ie}from"./oauth-bearer-credential-MfThcH_T.js";import{once as ae}from"node:events";import{stderr as D}from"node:process";import{createServer as oe}from"node:http";import{setTimeout as se}from"node:timers/promises";import{randomBytes as ce,timingSafeEqual as O}from"node:crypto";var k=5e3,A=500,j=`Approval poll was interrupted; retrying.
1
+ import{R as e}from"./webapi-B2JTupyg.js";import{f as t,o as n,s as r,u as i}from"./dist-Dt0qAmdj.js";import{Gt as a,Yt as o}from"./auth-BNDyLTqp-z6VNZXaE.js";import{p as s}from"./env-kXzA7vyc.js";import{c,r as l}from"./result-envelope-fUFmAu5G.js";import{a as u,n as d,o as f}from"./openapi-call-BI8CGnE_.js";import{a as ee,r as p}from"./api-target-vxev2RKl.js";import{n as m,t as h}from"./credential-redaction-DGm2KLQy.js";import{n as g,s as te}from"./credential-store-Du_vAX6P.js";import"./dist-oUS6BQ43.js";import{a as ne,c as _,d as v,f as y,h as b,m as x,p as S,r as C,s as w,t as T,u as E}from"./oauth-credential-BGft0Yo9.js";import{t as re}from"./provider-catalog-CT1LnhCO.js";import{i as ie}from"./oauth-bearer-credential-BR4awrGN.js";import{once as ae}from"node:events";import{stderr as D}from"node:process";import{createServer as oe}from"node:http";import{setTimeout as se}from"node:timers/promises";import{randomBytes as ce,timingSafeEqual as O}from"node:crypto";var k=5e3,A=500,j=`Approval poll was interrupted; retrying.
2
2
  `,M=`urn:ietf:params:oauth:grant-type:device_code`;function N(e){let t=Reflect.get(e,`device_authorization_endpoint`);if(typeof t!=`string`)throw Error(`OAuth authorization-server metadata lacks device_authorization_endpoint`);return x(t,`device authorization endpoint`,!0)}async function P(e,t){if(t.grant_types_supported?.includes(M)!==!0)throw Error(`OAuth authorization-server metadata must advertise the device authorization grant`);let n=await fetch(N(t),{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:_(e),scope:v(e).join(` `),resource:E(e).toString()})});if(!n.ok)throw Error(`device authorization endpoint answered ${n.status}`);return I(await F(n,`device authorization`),Date.now())}async function F(e,t){try{return await e.json()}catch(n){throw Error(`${t} endpoint answered ${e.status} without a JSON body`,{cause:n})}}function I(e,t){if(typeof e!=`object`||!e)throw Error(`device authorization response is not an object`);let n=Reflect.get(e,`device_code`),r=Reflect.get(e,`user_code`),i=Reflect.get(e,`verification_uri_complete`),a=Reflect.get(e,`verification_uri`),o=Reflect.get(e,`expires_in`),s=Reflect.get(e,`interval`);if(typeof n!=`string`||typeof r!=`string`||n.length===0||r.length===0)throw Error(`device authorization response lacks device_code or user_code`);let c=typeof i==`string`&&i.length>0?i:a;if(typeof c!=`string`)throw Error(`device authorization response lacks a verification URI`);if(typeof o!=`number`||o<=0)throw Error(`device authorization response lacks a positive expires_in`);return{deviceCode:n,userCode:r,verificationUri:x(c,`verification URI`,!0),expiresAt:t+o*1e3,intervalMilliseconds:(typeof s==`number`&&s>=0?s:5)*1e3}}async function L(e,t,n){let r=x(t.token_endpoint,`token endpoint`,!0),i=n.intervalMilliseconds,s=null;for(;Date.now()<n.expiresAt;){await se(i);let t;try{t=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:_(e),grant_type:M,device_code:n.deviceCode})})}catch(e){s=`the token endpoint was unreachable — ${h(e)}`,D.write(j);continue}if(t.status>=A){await t.body?.cancel(),s=`the token endpoint answered ${t.status}`,D.write(j);continue}s=null;let c=await F(t,`token`);if(t.ok){let e=o.safeParse(c);if(!e.success)throw Error(`token endpoint returned an invalid token response`);return e.data}let l=a.safeParse(c),u=l.success?l.data.error:`HTTP ${t.status}`;if(u!==`authorization_pending`){if(u===`slow_down`)i+=k;else throw Error(u===`access_denied`?`the sign-in was denied in the browser`:u===`expired_token`?`the device code expired before approval`:`token endpoint answered ${u}`)}}throw Error(s===null?`the device code expired before approval`:`the device code expired before approval — last failure: ${s}`)}var R=3e5;function z(e){let t;try{t=new URL(e.redirectUri)}catch(e){throw Error(`OAuth callback configuration is not a valid URL`,{cause:e})}if(t.protocol!==`http:`||t.hostname!==`127.0.0.1`||t.port.length>0||t.pathname!==`/callback`||t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0)throw Error(`OAuth callback configuration must be http://127.0.0.1/callback without a port, query, or fragment`);return t}async function B(e,t){let n,r=new Promise(e=>{n=e}),i=oe((r,i)=>{i.setHeader(`Cache-Control`,`no-store`),i.setHeader(`Content-Type`,`text/plain; charset=utf-8`);let a=new URL(r.url??`/`,e);if(r.method!==`GET`||a.pathname!==e.pathname){i.statusCode=404,i.end(`OAuth callback not found.`);return}let o=a.searchParams.getAll(`state`),s=Buffer.from(o[0]??``),c=Buffer.from(t);if(o.length!==1||s.length!==c.length||!O(s,c)){i.statusCode=400,i.end(`OAuth callback state did not match. Return to the CLI and retry.`);return}if(a.searchParams.has(`error`)){i.statusCode=400,i.end(`OAuth authorization was not completed. Return to the CLI.`),n({state:`failed`,message:`OAuth authorization server returned an error`});return}let l=a.searchParams.getAll(`code`),u=l[0]?.trim();if(l.length!==1||u===void 0||u.length===0){i.statusCode=400,i.end(`OAuth callback did not include an authorization code.`);return}let d=a.searchParams.getAll(`iss`);d.length>1?(i.statusCode=400,i.end(`OAuth callback named more than one issuer.`)):(i.statusCode=200,i.end(`OAuth authorization completed. Return to the CLI.`),n({state:`code`,authorizationCode:u,iss:d[0]}))});i.on(`error`,e=>n({state:`failed`,message:`OAuth callback listener failed: ${h(e)}`}));try{let t=ae(i,`listening`);i.listen({host:`127.0.0.1`,port:0}),await t;let n=i.address();if(n===null||typeof n==`string`||n.port<=0)throw Error(`OAuth callback listener did not receive an ephemeral loopback port`);let a=new URL(e);return a.port=String(n.port),{redirectUri:a,waitForAuthorizationCode:async()=>{let e;return await Promise.race([r,new Promise(t=>{e=setTimeout(()=>t({state:`timed-out`}),R)})]).finally(()=>{e!==void 0&&clearTimeout(e)})},close:async()=>await V(i)}}catch(e){throw i.listening&&await V(i),e}}function V(e){return new Promise((t,n)=>{e.close(e=>e===void 0?t():n(e))})}var H=`the OAuth credential is valid, but the API refused this account (HTTP 403); signing in again will not change that`;async function U(t){let n;try{n=p(s().host)}catch(e){return l(`auth login: invalid API host — ${h(e)}`)}let r=await C(n);if(r.state===`missing`)return G(n,t);if(r.state===`unavailable`)return l(`auth login: ${r.summary}`);if(r.state===`invalid`)return G(n,t,`Saved OAuth credential cannot be read — ${r.summary}`);let{stored:i}=r;if(ne(i.credential))return await W(i,t);let a;try{a=await u(i.credential.tokens.access_token,E(i.credential.client))}catch(r){return r instanceof e?G(n,t,`Saved OAuth credential was rejected`):l(`auth login: saved OAuth credential could not be verified — ${h(r,y(i.credential.tokens))}`)}return a===`forbidden`?l(`auth login: ${H}`):a===null?G(n,t,`Saved OAuth credential was rejected`):c(`OAuth CLI access token is already stored and verified.`,$(i))}async function W(e,t){let n=await S(e.host);if(n.state===`unavailable`)return l(`auth login: ${n.summary}`);let{tokens:r}=e.credential;if(r.refresh_token===void 0)return G(e.host,t,`Saved OAuth access token expired`,n);let i;try{i=await ie(e)}catch(i){return G(e.host,t,`Saved OAuth credential could not be renewed — ${h(i,y(r))}`,n)}J(n);let a=await Q(e.host,i,`OAuth CLI access token renewed and verified.`);if(!a.ok)return a;let o=await Z(i);return o.state===`failed`?l(`auth login: ${o.summary}`):o.state===`rejected`?G(e.host,t,`Renewed OAuth access token was rejected`,n):a}async function G(e,n,i,a){let o=a??await S(e);if(o.state===`unavailable`)return l(`auth login: ${o.summary}`);J(o),i!==void 0&&D.write(`${i}; continuing to browser sign-in.\n`);let s;try{let e=(await Y()).oauthClient;if(e==null)throw Error(`the API does not advertise an OAuth CLI client`);s=e}catch(e){return l(`auth login: OAuth configuration is unavailable — ${h(e)}`)}let c;try{c=await X(s)}catch(e){return l(`auth login: OAuth authorization-server discovery failed — ${h(e)}`)}if(n.noBrowser)return await K(e,s,c);let u=ce(32).toString(`base64url`),d;try{d=await B(z(s),u);let n=await t(w(s),{metadata:c,clientInformation:{client_id:_(s)},redirectUrl:d.redirectUri,resource:E(s),scope:v(s).join(` `),state:u});n.authorizationUrl.searchParams.delete(`prompt`);let i=await te(n.authorizationUrl,{noBrowser:!1});i.state===`opened`?D.write(`Browser sign-in opened: choose the account, then approve. Waiting for the loopback callback...
3
3
  `):D.write(`Browser not opened automatically (${i.reason}).\nOpen this private sign-in URL in a browser that can reach this machine's loopback callback:
4
4
  ${n.authorizationUrl.toString()}\nWaiting for the loopback callback...\n`);let a=await d.waitForAuthorizationCode();if(a.state===`timed-out`)return await d.close(),d=void 0,D.write(`Browser sign-in was not completed; continuing with a device code.
@@ -99,4 +99,4 @@ Content-Type: ${a.type||`application/octet-stream`}\r\n\r\n`);u.push(e,a,d),type
99
99
  )
100
100
  `)}close(){this.#r.close()}get(e){i(e);let t=this.#p(e);return t?{body:t.body?t.compressed===`zstd`?s(Buffer.from(t.body.buffer,t.body.byteOffset,t.body.byteLength)):Buffer.from(t.body.buffer,t.body.byteOffset,t.body.byteLength):void 0,statusCode:t.statusCode,statusMessage:t.statusMessage,headers:t.headers?JSON.parse(t.headers):void 0,etag:t.etag?t.etag:void 0,vary:t.vary?JSON.parse(t.vary):void 0,cacheControlDirectives:t.cacheControlDirectives?JSON.parse(t.cacheControlDirectives):void 0,cachedAt:t.cachedAt,staleAt:t.staleAt,deleteAt:t.deleteAt}:void 0}set(e,t){i(e);let n=this.#f(e),r=Array.isArray(t.body)?Buffer.concat(t.body):t.body,a=r?.byteLength;if(a&&a>this.#e)return;let s=null,c=r;if(r&&f&&(a>this.#n||h(m(t.headers)))){let e=o(r);e.byteLength<r.byteLength&&(c=e,s=`zstd`)}let l=this.#p(e,!0);l?this.#a.run(c,s,t.deleteAt,t.statusCode,t.statusMessage,t.headers?JSON.stringify(t.headers):null,t.etag?t.etag:null,t.cacheControlDirectives?JSON.stringify(t.cacheControlDirectives):null,t.vary?JSON.stringify(t.vary):null,t.cachedAt,t.staleAt,l.id):(this.#o.run(n,e.method,c,s,t.deleteAt,t.statusCode,t.statusMessage,t.headers?JSON.stringify(t.headers):null,t.etag?t.etag:null,t.cacheControlDirectives?JSON.stringify(t.cacheControlDirectives):null,t.vary?JSON.stringify(t.vary):null,t.cachedAt,t.staleAt),this.#d())}createWriteStream(e,t){i(e),a(t);let n=0,o=[],s=this;return new r({decodeStrings:!0,write(e,t,r){n+=e.byteLength,n<=s.#e?o.push(e):this.destroy(),r()},final(n){s.set(e,{...t,body:o}),n()}})}delete(e){if(typeof e!=`object`)throw TypeError(`expected key to be object, got ${typeof e}`);this.#c.run(this.#f(e))}#d(){if(Number.isFinite(this.#t)&&this.size<=this.#t)return 0;{let e=this.#s.run(Date.now()).changes;if(e)return e}{let e=this.#u?.run(Math.max(Math.floor(this.#t*.1),1)).changes;if(e)return e}return 0}get size(){let{total:e}=this.#l.get();return e}#f(e){return`${e.origin}/${e.path}`}#p(e,t=!1){let n=this.#f(e),{headers:r,method:i}=e,a=this.#i.all(n,i);if(a.length===0)return;let o=Date.now();for(let e of a){if(o>=e.deleteAt&&!t)continue;let n=!0;if(e.vary){let t=JSON.parse(e.vary);for(let e in t)if(!p(r[e],t[e])){n=!1;break}}if(n)return e}}};function p(e,t){if(e==null&&t==null)return!0;if(e==null&&t!=null||e!=null&&t==null)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}return e===t}function m(e){if(e!=null){for(let t in e)if(t.toLowerCase()===`content-type`){let n=e[t];return Array.isArray(n)?n[0]:n}}}function h(e){if(e==null)return!1;let t=e.toLowerCase();return/^text\//.test(t)||/^application\/(json|xml|javascript|x-www-form-urlencoded|graphql)(\s|;|$)/.test(t)||/\+(json|xml)(\s|;|$)/.test(t)}})),kr=t(((t,n)=>{var{kConstruct:r}=Z(),{kEnumerableProperty:i,setHeader:a}=$(),{iteratorMixin:o,isValidHeaderName:s,isValidHeaderValue:c}=dn(),{webidl:l}=un(),u=e(`node:assert`),d=e(`node:util`);function f(e){return e===10||e===13||e===9||e===32}function p(e){let t=0,n=e.length;for(;n>t&&f(e.charCodeAt(n-1));)--n;for(;n>t&&f(e.charCodeAt(t));)++t;return t===0&&n===e.length?e:e.substring(t,n)}function m(e,t){if(Array.isArray(t))for(let n=0;n<t.length;++n){let r=t[n];if(r.length!==2)throw l.errors.exception({header:`Headers constructor`,message:`expected name/value pair to be length 2, found ${r.length}.`});h(e,r[0],r[1])}else if(typeof t==`object`&&t){let n=Object.keys(t);for(let r=0;r<n.length;++r)h(e,n[r],t[n[r]])}else throw l.errors.conversionFailed({prefix:`Headers constructor`,argument:`Argument 1`,types:[`sequence<sequence<ByteString>>`,`record<ByteString, ByteString>`]})}function h(e,t,n){if(n=p(n),!s(t))throw l.errors.invalidArgument({prefix:`Headers.append`,value:t,type:`header name`});if(!c(n))throw l.errors.invalidArgument({prefix:`Headers.append`,value:n,type:`header value`});if(y(e)===`immutable`)throw TypeError(`immutable`);return x(e).append(t,n,!1)}function g(e){let t=x(e);if(!t)return[];if(t.sortedMap)return t.sortedMap;let n=[],r=t.toSortedArray(),i=t.cookies;if(i===null||i.length===1)return t.sortedMap=r;for(let e=0;e<r.length;++e){let{0:t,1:a}=r[e];if(t===`set-cookie`)for(let e=0;e<i.length;++e)n.push([t,i[e]]);else n.push([t,a])}return t.sortedMap=n}function _(e,t){return e[0]<t[0]?-1:1}var v=class e{cookies=null;sortedMap;headersMap;constructor(t){t instanceof e?(this.headersMap=new Map(t.headersMap),this.sortedMap=t.sortedMap,this.cookies=t.cookies===null?null:[...t.cookies]):(this.headersMap=new Map(t),this.sortedMap=null)}contains(e,t){return this.headersMap.has(t?e:e.toLowerCase())}clear(){this.headersMap.clear(),this.sortedMap=null,this.cookies=null}append(e,t,n){this.sortedMap=null;let r=n?e:e.toLowerCase(),i=this.headersMap.get(r);if(i){let e=r===`cookie`?`; `:`, `;this.headersMap.set(r,{name:i.name,value:`${i.value}${e}${t}`})}else this.headersMap.set(r,{name:e,value:t});r===`set-cookie`&&(this.cookies??=[]).push(t)}set(e,t,n){this.sortedMap=null;let r=n?e:e.toLowerCase();r===`set-cookie`&&(this.cookies=[t]),this.headersMap.set(r,{name:e,value:t})}delete(e,t){this.sortedMap=null,t||(e=e.toLowerCase()),e===`set-cookie`&&(this.cookies=null),this.headersMap.delete(e)}get(e,t){return this.headersMap.get(t?e:e.toLowerCase())?.value??null}*[Symbol.iterator](){for(let{0:e,1:{value:t}}of this.headersMap)yield[e,t]}get entries(){let e={};if(this.headersMap.size!==0)for(let{name:t,value:n}of this.headersMap.values())a(e,t,n);return e}rawValues(){return this.headersMap.values()}get entriesList(){let e=[];if(this.headersMap.size!==0)for(let{0:t,1:{name:n,value:r}}of this.headersMap)if(t===`set-cookie`)for(let t of this.cookies)e.push([n,t]);else e.push([n,r]);return e}toSortedArray(){let e=this.headersMap.size,t=Array(e);if(e<=32){if(e===0)return t;let n=this.headersMap[Symbol.iterator](),r=n.next().value;t[0]=[r[0],r[1].value],u(r[1].value!==null);for(let r=1,i=0,a=0,o=0,s=0,c,l;r<e;++r){for(l=n.next().value,c=t[r]=[l[0],l[1].value],u(c[1]!==null),o=0,a=r;o<a;)s=o+(a-o>>1),t[s][0]<=c[0]?o=s+1:a=s;if(r!==s){for(i=r;i>o;)t[i]=t[--i];t[o]=c}}if(!n.next().done)throw TypeError(`Unreachable`);return t}{let e=0;for(let{0:n,1:{value:r}}of this.headersMap)t[e++]=[n,r],u(r!==null);return t.sort(_)}}},y,b,x,S,C=class{#e;#t;constructor(e=void 0){l.util.markAsUncloneable(this),e!==r&&(this.#t=new v,this.#e=`none`,e!==void 0&&(e=l.converters.HeadersInit(e,`Headers constructor`,`init`),m(this,e)))}append(e,t){l.brandCheck(this,l.is.Headers),l.argumentLengthCheck(arguments,2,`Headers.append`);let n=`Headers.append`;return e=l.converters.ByteString(e,n,`name`),t=l.converters.ByteString(t,n,`value`),h(this,e,t)}delete(e){if(l.brandCheck(this,l.is.Headers),l.argumentLengthCheck(arguments,1,`Headers.delete`),e=l.converters.ByteString(e,`Headers.delete`,`name`),!s(e))throw l.errors.invalidArgument({prefix:`Headers.delete`,value:e,type:`header name`});if(this.#e===`immutable`)throw TypeError(`immutable`);this.#t.contains(e,!1)&&this.#t.delete(e,!1)}get(e){l.brandCheck(this,l.is.Headers),l.argumentLengthCheck(arguments,1,`Headers.get`);let t=`Headers.get`;if(e=l.converters.ByteString(e,t,`name`),!s(e))throw l.errors.invalidArgument({prefix:t,value:e,type:`header name`});return this.#t.get(e,!1)}has(e){l.brandCheck(this,l.is.Headers),l.argumentLengthCheck(arguments,1,`Headers.has`);let t=`Headers.has`;if(e=l.converters.ByteString(e,t,`name`),!s(e))throw l.errors.invalidArgument({prefix:t,value:e,type:`header name`});return this.#t.contains(e,!1)}set(e,t){l.brandCheck(this,l.is.Headers),l.argumentLengthCheck(arguments,2,`Headers.set`);let n=`Headers.set`;if(e=l.converters.ByteString(e,n,`name`),t=l.converters.ByteString(t,n,`value`),t=p(t),!s(e))throw l.errors.invalidArgument({prefix:n,value:e,type:`header name`});if(!c(t))throw l.errors.invalidArgument({prefix:n,value:t,type:`header value`});if(this.#e===`immutable`)throw TypeError(`immutable`);this.#t.set(e,t,!1)}getSetCookie(){l.brandCheck(this,l.is.Headers);let e=this.#t.cookies;return e?[...e]:[]}[d.inspect.custom](e,t){return t.depth??=e,`Headers ${d.formatWithOptions(t,this.#t.entries)}`}static{y=e=>e.#e,b=(e,t)=>{e.#e=t},x=e=>e.#t,S=(e,t)=>{e.#t=t},l.is.Headers=e=>typeof e==`object`&&!!e&&#e in e}};o(`Headers`,C,g,0,1,l.is.Headers),Object.defineProperties(C.prototype,{append:i,delete:i,get:i,has:i,set:i,getSetCookie:i,[Symbol.toStringTag]:{value:`Headers`,configurable:!0},[d.inspect.custom]:{enumerable:!1}}),l.converters.HeadersInit=function(e,t,n){if(l.util.Type(e)===l.util.Types.OBJECT){let r=Reflect.get(e,Symbol.iterator);if(!d.types.isProxy(e)&&r===C.prototype.entries)try{return x(e).entriesList}catch{}return typeof r==`function`?l.converters[`sequence<sequence<ByteString>>`](e,t,n,r.bind(e)):l.converters[`record<ByteString, ByteString>`](e,t,n)}throw l.errors.conversionFailed({prefix:`Headers constructor`,argument:`Argument 1`,types:[`sequence<sequence<ByteString>>`,`record<ByteString, ByteString>`]})},n.exports={fill:m,compareHeaderName:_,Headers:C,HeadersList:v,getHeadersGuard:y,setHeadersGuard:b,setHeadersList:S,getHeadersList:x}})),Ar=t(((t,n)=>{var{Headers:r,HeadersList:i,fill:a,getHeadersGuard:o,setHeadersGuard:s,setHeadersList:c}=kr(),{extractBody:l,cloneBody:u,mixinBody:d,streamRegistry:f,bodyUnusable:p}=En(),m=$(),h=e(`node:util`),{kEnumerableProperty:g}=m,{isValidReasonPhrase:_,isCancelled:v,isAborted:y,isErrorLike:b,environmentSettingsObject:x}=dn(),{redirectStatusSet:S,nullBodyStatus:C}=an(),{webidl:w}=un(),{URLSerializer:T}=ln(),{kConstruct:E}=Z(),D=e(`node:assert`),{isomorphicEncode:O,serializeJavascriptValueToJSONString:k}=cn(),A=new TextEncoder(`utf-8`),j,M,N,P,F=class{#e;#t;static error(){return V(R(),`immutable`)}static json(e,t=void 0){w.argumentLengthCheck(arguments,1,`Response.json`),t=w.converters.ResponseInit(t);let n=l(A.encode(k(e))),r=V(L({}),`response`);return ne(r,t,{body:n[0],type:`application/json`}),r}static redirect(e,t=302){w.argumentLengthCheck(arguments,1,`Response.redirect`),e=w.converters.USVString(e),t=w.converters[`unsigned short`](t);let n;try{n=new URL(e,x.settingsObject.baseUrl)}catch(t){throw TypeError(`Failed to parse URL from ${e}`,{cause:t})}if(!S.has(t))throw RangeError(`Invalid status code ${t}`);let r=V(L({}),`immutable`);r.#t.status=t;let i=O(T(n));return r.#t.headersList.append(`location`,i,!0),r}constructor(e=null,t=void 0){if(w.util.markAsUncloneable(this),e===E)return;e!==null&&(e=w.converters.BodyInit(e,`Response`,`body`)),t=w.converters.ResponseInit(t),this.#t=L({}),this.#e=new r(E),s(this.#e,`response`),c(this.#e,this.#t.headersList);let n=null;if(e!=null){let[t,r]=l(e);n={body:t,type:r}}ne(this,t,n)}get type(){return w.brandCheck(this,w.is.Response),this.#t.type}get url(){w.brandCheck(this,w.is.Response);let e=this.#t.urlList,t=e[e.length-1]??null;return t===null?``:T(t,!0)}get redirected(){return w.brandCheck(this,w.is.Response),this.#t.urlList.length>1}get status(){return w.brandCheck(this,w.is.Response),this.#t.status}get ok(){return w.brandCheck(this,w.is.Response),this.#t.status>=200&&this.#t.status<=299}get statusText(){return w.brandCheck(this,w.is.Response),this.#t.statusText}get headers(){return w.brandCheck(this,w.is.Response),this.#e}get body(){return w.brandCheck(this,w.is.Response),this.#t.body?this.#t.body.stream:null}get bodyUsed(){return w.brandCheck(this,w.is.Response),!!this.#t.body&&m.isDisturbed(this.#t.body.stream)}clone(){if(w.brandCheck(this,w.is.Response),p(this.#t))throw w.errors.exception({header:`Response.clone`,message:`Body has already been consumed.`});let e=I(this.#t);return this.#t.urlList.length!==0&&this.#t.body?.stream&&f.register(this,new WeakRef(this.#t.body.stream)),V(e,o(this.#e))}[h.inspect.custom](e,t){t.depth===null&&(t.depth=2),t.colors??=!0;let n={status:this.status,statusText:this.statusText,headers:this.headers,body:this.body,bodyUsed:this.bodyUsed,ok:this.ok,redirected:this.redirected,type:this.type,url:this.url};return`Response ${h.formatWithOptions(t,n)}`}static{j=e=>e.#e,M=(e,t)=>{e.#e=t},N=e=>e.#t,P=(e,t)=>{e.#t=t},w.is.Response=e=>typeof e==`object`&&!!e&&#t in e}};d(F,N,w.is.Response),Object.defineProperties(F.prototype,{type:g,url:g,status:g,ok:g,redirected:g,statusText:g,headers:g,clone:g,body:g,bodyUsed:g,[Symbol.toStringTag]:{value:`Response`,configurable:!0}}),Object.defineProperties(F,{json:g,redirect:g,error:g});function I(e){if(e.internalResponse)return B(I(e.internalResponse),e.type);let t=L({...e,body:null});return e.body!=null&&(t.body=u(e.body)),t}function L(e){return{aborted:!1,rangeRequested:!1,timingAllowPassed:!1,requestIncludesCredentials:!1,type:`default`,status:200,timingInfo:null,cacheState:``,statusText:``,...e,headersList:e?.headersList?new i(e?.headersList):new i,urlList:e?.urlList?[...e.urlList]:[]}}function R(e){return L({type:`error`,status:0,error:b(e)?e:Error(e&&String(e)),aborted:e&&e.name===`AbortError`})}function ee(e){return e.type===`error`&&e.status===0}function z(e,t){return t={internalResponse:e,...t},new Proxy(e,{get(e,n){return n in t?t[n]:e[n]},set(e,n,r){return D(!(n in t)),e[n]=r,!0}})}function B(e,t){if(t===`basic`)return z(e,{type:`basic`,headersList:e.headersList});if(t===`cors`)return z(e,{type:`cors`,headersList:e.headersList});if(t===`opaque`)return z(e,{type:`opaque`,urlList:[],status:0,statusText:``,body:null});if(t===`opaqueredirect`)return z(e,{type:`opaqueredirect`,status:0,statusText:``,headersList:[],body:null});D(!1)}function te(e,t=null){return D(v(e)),y(e)?R(Object.assign(new DOMException(`The operation was aborted.`,`AbortError`),{cause:t})):R(Object.assign(new DOMException(`Request was cancelled.`),{cause:t}))}function ne(e,t,n){if(t.status!==null&&(t.status<200||t.status>599))throw RangeError(`init["status"] must be in the range of 200 to 599, inclusive.`);if(`statusText`in t&&t.statusText!=null&&!_(String(t.statusText)))throw TypeError(`Invalid statusText`);if(`status`in t&&t.status!=null&&(N(e).status=t.status),`statusText`in t&&t.statusText!=null&&(N(e).statusText=t.statusText),`headers`in t&&t.headers!=null&&a(j(e),t.headers),n){if(C.includes(e.status))throw w.errors.exception({header:`Response constructor`,message:`Invalid response status code ${e.status}`});N(e).body=n.body,n.type!=null&&!N(e).headersList.contains(`content-type`,!0)&&N(e).headersList.append(`content-type`,n.type,!0)}}function V(e,t){let n=new F(E);P(n,e);let i=new r(E);return M(n,i),c(i,e.headersList),s(i,t),e.urlList.length!==0&&e.body?.stream&&f.register(n,new WeakRef(e.body.stream)),n}w.converters.XMLHttpRequestBodyInit=function(e,t,n){return typeof e==`string`?w.converters.USVString(e,t,n):w.is.Blob(e)||w.is.BufferSource(e)||w.is.FormData(e)||w.is.URLSearchParams(e)?e:w.converters.DOMString(e,t,n)},w.converters.BodyInit=function(e,t,n){return w.is.ReadableStream(e)||e?.[Symbol.asyncIterator]?e:w.converters.XMLHttpRequestBodyInit(e,t,n)},w.converters.ResponseInit=w.dictionaryConverter([{key:`status`,converter:w.converters[`unsigned short`],defaultValue:()=>200},{key:`statusText`,converter:w.converters.ByteString,defaultValue:()=>``},{key:`headers`,converter:w.converters.HeadersInit}]),n.exports={isNetworkError:ee,makeNetworkError:R,makeResponse:L,makeAppropriateNetworkError:te,filterResponse:B,Response:F,cloneResponse:I,fromInnerResponse:V,getResponseState:N}})),jr=t(((t,n)=>{var{extractBody:r,mixinBody:i,cloneBody:a,bodyUnusable:o}=En(),{Headers:s,fill:c,HeadersList:l,setHeadersGuard:u,getHeadersGuard:d,setHeadersList:f,getHeadersList:p}=kr(),m=$(),h=e(`node:util`),{isValidHTTPToken:g,sameOrigin:_,environmentSettingsObject:v}=dn(),{forbiddenMethodsSet:y,corsSafeListedMethodsSet:b,referrerPolicy:x,requestRedirect:S,requestMode:C,requestCredentials:w,requestCache:T,requestDuplex:E}=an(),{kEnumerableProperty:D,normalizedMethodRecordsBase:O,normalizedMethodRecords:k}=m,{webidl:A}=un(),{URLSerializer:j}=ln(),{kConstruct:M}=Z(),N=e(`node:assert`),{getMaxListeners:P,setMaxListeners:F,defaultMaxListeners:I}=e(`node:events`),L=Symbol(`abortController`),R=new FinalizationRegistry(({signal:e,abort:t})=>{e.removeEventListener(`abort`,t)}),ee=new WeakMap,z;try{z=P(new AbortController().signal)>0}catch{z=!1}function B(e){return t;function t(){let n=e.deref();if(n!==void 0){R.unregister(t),this.removeEventListener(`abort`,t),n.abort(this.reason);let e=ee.get(n.signal);if(e!==void 0){if(e.size!==0){for(let t of e){let e=t.deref();e!==void 0&&e.abort(this.reason)}e.clear()}ee.delete(n.signal)}}}}var te=!1,ne,V,re,ie,ae,H,oe,U=class{#e;#t;#n;#r;#i=null;constructor(e,t=void 0){if(A.util.markAsUncloneable(this),e===M)return;A.argumentLengthCheck(arguments,1,`Request constructor`),e=A.converters.RequestInfo(e),t=A.converters.RequestInit(t);let n=null,i=null,a=v.settingsObject.baseUrl,d=null;if(typeof e==`string`){this.#t=t.dispatcher;let r;try{r=new URL(e,a)}catch(t){throw TypeError(`Failed to parse URL from `+e,{cause:t})}if(r.username||r.password)throw TypeError(`Request cannot be constructed from a URL that includes credentials: `+e);n=W({urlList:[r]}),i=`cors`}else N(A.is.Request(e)),n=e.#r,d=e.#e,this.#t=t.dispatcher||e.#t;let h=v.settingsObject.origin,x=`client`;if(n.window?.constructor?.name===`EnvironmentSettingsObject`&&_(n.window,h)&&(x=n.window),t.window!=null)throw TypeError(`'window' option '${x}' must be null`);`window`in t&&(x=`no-window`),n=W({method:n.method,headersList:n.headersList,unsafeRequest:n.unsafeRequest,client:v.settingsObject,window:x,priority:n.priority,origin:n.origin,referrer:n.referrer,referrerPolicy:n.referrerPolicy,mode:n.mode,credentials:n.credentials,cache:n.cache,redirect:n.redirect,integrity:n.integrity,keepalive:n.keepalive,reloadNavigation:n.reloadNavigation,historyNavigation:n.historyNavigation,urlList:[...n.urlList]});let S=Object.keys(t).length!==0;if(S&&(n.mode===`navigate`&&(n.mode=`same-origin`),n.reloadNavigation=!1,n.historyNavigation=!1,n.origin=`client`,n.referrer=`client`,n.referrerPolicy=``,n.url=n.urlList[n.urlList.length-1],n.urlList=[n.url]),t.referrer!==void 0){let e=t.referrer;if(e===``)n.referrer=`no-referrer`;else{let t;try{t=new URL(e,a)}catch(t){throw TypeError(`Referrer "${e}" is not a valid URL.`,{cause:t})}t.protocol===`about:`&&t.hostname===`client`||h&&!_(t,v.settingsObject.baseUrl)?n.referrer=`client`:n.referrer=t}}t.referrerPolicy!==void 0&&(n.referrerPolicy=t.referrerPolicy);let C;if(C=t.mode===void 0?i:t.mode,C===`navigate`)throw A.errors.exception({header:`Request constructor`,message:`invalid request mode navigate.`});if(C!=null&&(n.mode=C),t.credentials!==void 0&&(n.credentials=t.credentials),t.cache!==void 0&&(n.cache=t.cache),n.cache===`only-if-cached`&&n.mode!==`same-origin`)throw TypeError(`'only-if-cached' can be set only with 'same-origin' mode`);if(t.redirect!==void 0&&(n.redirect=t.redirect),t.integrity!=null&&(n.integrity=String(t.integrity)),t.keepalive!==void 0&&(n.keepalive=!!t.keepalive),t.method!==void 0){let e=t.method,r=k[e];if(r!==void 0)n.method=r;else{if(!g(e))throw TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(y.has(t))throw TypeError(`'${e}' HTTP method is unsupported.`);e=O[t]??e,n.method=e}!te&&n.method===`patch`&&(process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.",{code:`UNDICI-FETCH-patch`}),te=!0)}t.signal!==void 0&&(d=t.signal),this.#r=n;let w=new AbortController;if(this.#e=w.signal,d!=null){if(d.aborted)w.abort(d.reason);else{this[L]=w;let e=B(new WeakRef(w));z&&P(d)===I&&F(1500,d);let t=m.addAbortListener(d,e);R.register(w,{signal:d,abort:e},e),this.#i=()=>{R.unregister(e),t(),this.#i=null}}}if(this.#n=new s(M),f(this.#n,n.headersList),u(this.#n,`request`),C===`no-cors`){if(!b.has(n.method))throw TypeError(`'${n.method} is unsupported in no-cors mode.`);u(this.#n,`request-no-cors`)}if(S){let e=p(this.#n),n=t.headers===void 0?new l(e):t.headers;if(e.clear(),n instanceof l){for(let{name:t,value:r}of n.rawValues())e.append(t,r,!1);e.cookies=n.cookies}else c(this.#n,n)}let T=A.is.Request(e)?e.#r.body:null;if((t.body!=null||T!=null)&&(n.method===`GET`||n.method===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body.`);let E=null;if(t.body!=null){let[e,i]=r(t.body,n.keepalive);E=e,i&&!p(this.#n).contains(`content-type`,!0)&&this.#n.append(`content-type`,i,!0)}let D=E??T;if(D!=null&&D.source==null){if(E!=null&&t.duplex==null)throw TypeError(`RequestInit: duplex option is required when sending a body.`);if(n.mode!==`same-origin`&&n.mode!==`cors`)throw TypeError(`If request is made from ReadableStream, mode should be "same-origin" or "cors"`);n.useCORSPreflightFlag=!0}let j=D;if(E==null&&T!=null){if(o(e.#r))throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);let t=new TransformStream;T.stream.pipeThrough(t),j={source:T.source,length:T.length,stream:t.readable}}this.#r.body=j}get method(){return A.brandCheck(this,A.is.Request),this.#r.method}get url(){return A.brandCheck(this,A.is.Request),j(this.#r.url)}get headers(){return A.brandCheck(this,A.is.Request),this.#n}get destination(){return A.brandCheck(this,A.is.Request),this.#r.destination}get referrer(){return A.brandCheck(this,A.is.Request),this.#r.referrer===`no-referrer`?``:this.#r.referrer===`client`?`about:client`:this.#r.referrer.toString()}get referrerPolicy(){return A.brandCheck(this,A.is.Request),this.#r.referrerPolicy}get mode(){return A.brandCheck(this,A.is.Request),this.#r.mode}get credentials(){return A.brandCheck(this,A.is.Request),this.#r.credentials}get cache(){return A.brandCheck(this,A.is.Request),this.#r.cache}get redirect(){return A.brandCheck(this,A.is.Request),this.#r.redirect}get integrity(){return A.brandCheck(this,A.is.Request),this.#r.integrity}get keepalive(){return A.brandCheck(this,A.is.Request),this.#r.keepalive}get isReloadNavigation(){return A.brandCheck(this,A.is.Request),this.#r.reloadNavigation}get isHistoryNavigation(){return A.brandCheck(this,A.is.Request),this.#r.historyNavigation}get signal(){return A.brandCheck(this,A.is.Request),this.#e}get body(){return A.brandCheck(this,A.is.Request),this.#r.body?this.#r.body.stream:null}get bodyUsed(){return A.brandCheck(this,A.is.Request),!!this.#r.body&&m.isDisturbed(this.#r.body.stream)}get duplex(){return A.brandCheck(this,A.is.Request),`half`}clone(){if(A.brandCheck(this,A.is.Request),o(this.#r))throw TypeError(`unusable`);let e=G(this.#r),t=new AbortController;if(this.signal.aborted)t.abort(this.signal.reason);else{let e=ee.get(this.signal);e===void 0&&(e=new Set,ee.set(this.signal,e));let n=new WeakRef(t);e.add(n),m.addAbortListener(t.signal,B(n))}return K(e,this.#t,t.signal,d(this.#n))}[h.inspect.custom](e,t){t.depth===null&&(t.depth=2),t.colors??=!0;let n={method:this.method,url:this.url,headers:this.headers,destination:this.destination,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,isReloadNavigation:this.isReloadNavigation,isHistoryNavigation:this.isHistoryNavigation,signal:this.signal};return`Request ${h.formatWithOptions(t,n)}`}static{ne=(e,t)=>{e.#e=t},V=e=>e.#t,re=(e,t)=>{e.#t=t},ie=(e,t)=>{e.#n=t},ae=e=>e.#r,H=(e,t)=>{e.#r=t},oe=e=>{e.#i?.()},A.is.Request=e=>typeof e==`object`&&!!e&&#r in e}};i(U,ae,A.is.Request);function W(e){return{method:e.method??`GET`,localURLsOnly:e.localURLsOnly??!1,unsafeRequest:e.unsafeRequest??!1,body:e.body??null,client:e.client??null,reservedClient:e.reservedClient??null,replacesClientId:e.replacesClientId??``,window:e.window??`client`,keepalive:e.keepalive??!1,serviceWorkers:e.serviceWorkers??`all`,initiator:e.initiator??``,destination:e.destination??``,priority:e.priority??`auto`,origin:e.origin??`client`,policyContainer:e.policyContainer??`client`,referrer:e.referrer??`client`,referrerPolicy:e.referrerPolicy??``,mode:e.mode??`no-cors`,useCORSPreflightFlag:e.useCORSPreflightFlag??!1,credentials:e.credentials??`same-origin`,useCredentials:e.useCredentials??!1,cache:e.cache??`default`,redirect:e.redirect??`follow`,integrity:e.integrity??``,cryptoGraphicsNonceMetadata:e.cryptoGraphicsNonceMetadata??``,parserMetadata:e.parserMetadata??``,reloadNavigation:e.reloadNavigation??!1,historyNavigation:e.historyNavigation??!1,userActivation:e.userActivation??!1,taintedOrigin:e.taintedOrigin??!1,redirectCount:e.redirectCount??0,responseTainting:e.responseTainting??`basic`,preventNoCacheCacheControlHeaderModification:e.preventNoCacheCacheControlHeaderModification??!1,done:e.done??!1,timingAllowFailed:e.timingAllowFailed??!1,useURLCredentials:e.useURLCredentials??void 0,traversableForUserPrompts:e.traversableForUserPrompts??`client`,urlList:e.urlList,url:e.urlList[0],headersList:e.headersList?new l(e.headersList):new l}}function G(e){let t=W({...e,body:null});return e.body!=null&&(t.body=a(e.body)),t}function K(e,t,n,r){let i=new U(M);H(i,e),re(i,t),ne(i,n);let a=new s(M);return ie(i,a),f(a,e.headersList),u(a,r),i}Object.defineProperties(U.prototype,{method:D,url:D,headers:D,redirect:D,clone:D,signal:D,duplex:D,destination:D,body:D,bodyUsed:D,isHistoryNavigation:D,isReloadNavigation:D,keepalive:D,integrity:D,cache:D,credentials:D,attribute:D,referrerPolicy:D,referrer:D,mode:D,[Symbol.toStringTag]:{value:`Request`,configurable:!0}}),A.converters.RequestInfo=function(e){return typeof e==`string`?A.converters.USVString(e):A.is.Request(e)?e:A.converters.USVString(e)},A.converters.RequestInit=A.dictionaryConverter([{key:`method`,converter:A.converters.ByteString},{key:`headers`,converter:A.converters.HeadersInit},{key:`body`,converter:A.nullableConverter(A.converters.BodyInit)},{key:`referrer`,converter:A.converters.USVString},{key:`referrerPolicy`,converter:A.converters.DOMString,allowedValues:x},{key:`mode`,converter:A.converters.DOMString,allowedValues:C},{key:`credentials`,converter:A.converters.DOMString,allowedValues:w},{key:`cache`,converter:A.converters.DOMString,allowedValues:T},{key:`redirect`,converter:A.converters.DOMString,allowedValues:S},{key:`integrity`,converter:A.converters.DOMString},{key:`keepalive`,converter:A.converters.boolean},{key:`signal`,converter:A.nullableConverter(e=>A.converters.AbortSignal(e,`RequestInit`,`signal`))},{key:`window`,converter:A.converters.any},{key:`duplex`,converter:A.converters.DOMString,allowedValues:E},{key:`dispatcher`,converter:A.converters.any},{key:`priority`,converter:A.converters.DOMString,allowedValues:[`high`,`low`,`auto`]}]),n.exports={Request:U,makeRequest:W,fromInnerRequest:K,cloneRequest:G,getRequestDispatcher:V,getRequestState:ae,removeRequestAbortListener:oe}})),Mr=t(((t,n)=>{var r=e(`node:assert`),{runtimeFeatures:i}=fn(),{asciiLowercase:a}=cn(),o=new Map([[`sha256`,0],[`sha384`,1],[`sha512`,2]]),s;if(i.has(`crypto`)){s=e(`node:crypto`);let t=s.getHashes();t.length===0&&o.clear();for(let e of o.keys())t.includes(e)===!1&&o.delete(e)}else o.clear();var c=Map.prototype.get.bind(o),l=e=>o.has(a(e)),u=i.has(`crypto`)===!1||o.size===0?()=>!0:(e,t)=>{let n=f(t);if(n.length===0)return!0;let r=d(n);for(let t of r){let n=t.alg,r=t.val;if(m(p(n,e),r))return!0}return!1};function d(e){let t=[],n=null;for(let i of e){if(r(l(i.alg),`Invalid SRI hash algorithm token`),t.length===0){t.push(i),n=i;continue}let e=n.alg,a=c(e),o=i.alg,s=c(o);s<a||(s>a?(n=i,t[0]=i,t.length=1):t.push(i))}return t}function f(e){let t=[];for(let n of e.split(` `)){let e=n.split(`?`,1)[0],r=``,i=[e.slice(0,6),e.slice(7)],o=i[0];if(!l(o))continue;i[1]&&(r=i[1]);let s={alg:a(o),val:r};t.push(s)}return t}var p=(e,t)=>s.hash(e,t,`base64`);function m(e,t){let n=e.length;n!==0&&e[n-1]===`=`&&--n,n!==0&&e[n-1]===`=`&&--n;let r=t.length;if(r!==0&&t[r-1]===`=`&&--r,r!==0&&t[r-1]===`=`&&--r,n!==r)return!1;for(let r=0;r<n;++r)if(!(e[r]===t[r]||e[r]===`+`&&t[r]===`-`||e[r]===`/`&&t[r]===`_`))return!1;return!0}n.exports={applyAlgorithmToBytes:p,bytesMatch:u,caseSensitiveMatch:m,isValidSRIHashAlgorithm:l,getStrongestMetadata:d,parseMetadata:f}})),Nr=t(((t,n)=>{var{makeNetworkError:r,makeAppropriateNetworkError:i,filterResponse:a,makeResponse:o,fromInnerResponse:s,getResponseState:c}=Ar(),{HeadersList:l}=kr(),{Request:u,cloneRequest:d,getRequestDispatcher:f,getRequestState:p,removeRequestAbortListener:m}=jr(),h=e(`node:zlib`),{makePolicyContainer:g,clonePolicyContainer:_,requestBadPort:v,TAOCheck:y,appendRequestOriginHeader:b,responseLocationURL:x,requestCurrentURL:S,setRequestReferrerPolicyOnRedirect:C,tryUpgradeRequestToAPotentiallyTrustworthyURL:w,createOpaqueTimingInfo:T,appendFetchMetadata:E,corsCheck:D,crossOriginResourcePolicyCheck:O,determineRequestsReferrer:k,coarsenedSharedCurrentTime:A,sameOrigin:j,isCancelled:M,isAborted:N,isErrorLike:P,fullyReadBody:F,readableStreamClose:I,urlIsLocal:L,urlIsHttpHttpsScheme:R,urlHasHttpsScheme:ee,clampAndCoarsenConnectionTimingInfo:z,simpleRangeHeaderValue:B,buildContentRange:te,createInflate:ne,extractMimeType:V,hasAuthenticationEntry:re,includesCredentials:ie,isTraversableNavigable:ae}=dn(),H=e(`node:assert`),{safelyExtractBody:oe,extractBody:U}=En(),{redirectStatusSet:W,nullBodyStatus:G,safeMethodsSet:K,requestBodyHeader:se,subresourceSet:ce}=an(),le=e(`node:events`),{Readable:ue,pipeline:q,finished:de,isErrored:fe,isReadable:pe}=e(`node:stream`),{addAbortListener:me,bufferToLowerCasedHeaderName:he}=$(),{SocketError:ge}=Q(),{dataURLProcessor:J,serializeAMimeType:Y,minimizeSupportedMimeType:X}=ln(),{getGlobalDispatcher:_e}=dr(),{webidl:ve}=un(),{STATUS_CODES:ye}=e(`node:http`),{bytesMatch:be}=Mr(),{isomorphicEncode:xe}=cn(),Se=[`GET`,`HEAD`],Ce=typeof __UNDICI_IS_NODE__<`u`||typeof esbuildDetection<`u`?`node`:`undici`,we;function Te(e,t,n){if(Array.isArray(n))for(let t=0;t<n.length;t+=2){let r=he(n[t]),i=n[t+1];if(Array.isArray(i)&&!Buffer.isBuffer(i))for(let t of i)e.append(r,t.toString(`latin1`),!0);else e.append(r,i.toString(`latin1`),!0)}else for(let[n,r]of Object.entries(t??{}))if(Array.isArray(r))for(let t of r)e.append(n,`${t}`,!0);else e.append(n,`${r}`,!0)}var Ee=class extends le{constructor(e){super(),this.dispatcher=e,this.connection=null,this.dump=!1,this.state=`ongoing`}terminate(e){this.state===`ongoing`&&(this.state=`terminated`,this.connection?.destroy(e),this.emit(`terminated`,e))}abort(e){this.state===`ongoing`&&(this.state=`aborted`,e||=new DOMException(`The operation was aborted.`,`AbortError`),this.serializedAbortReason=e,this.connection?.destroy(e),this.emit(`terminated`,e))}};function De(e){ke(e,`fetch`)}function Oe(e,t=void 0){ve.argumentLengthCheck(arguments,1,`globalThis.fetch`);let n=Promise.withResolvers(),r;try{r=new u(e,t)}catch(e){return n.reject(e),n.promise}let i=p(r);if(r.signal.aborted)return je(n,i,null,r.signal.reason,null),n.promise;i.client.globalObject?.constructor?.name===`ServiceWorkerGlobalScope`&&(i.serviceWorkers=`none`);let a=null,o=!1,c=null,l=me(r.signal,()=>{o=!0,H(c!=null),c.abort(r.signal.reason);let e=a?.deref();je(n,i,e,r.signal.reason,c.controller)}),d=()=>{l(),m(r)};return c=Me({request:i,processResponseEndOfBody:e=>{De(e),d()},processResponse:e=>{o||(e.aborted?(je(n,i,a,c.serializedAbortReason,c.controller),d()):e.type===`error`?(n.reject(TypeError(`fetch failed`,{cause:e.error})),d()):(a=new WeakRef(s(e,`immutable`)),n.resolve(a.deref()),n=null))},dispatcher:f(r),requestObject:r}),n.promise}function ke(e,t=`other`){if(e.type===`error`&&e.aborted||!e.urlList?.length)return;let n=e.urlList[0],r=e.timingInfo,i=e.cacheState;R(n)&&r!==null&&(e.timingAllowPassed||(r=T({startTime:r.startTime}),i=``),r.endTime=A(),e.timingInfo=r,Ae(r,n.href,t,globalThis,i,``,e.status))}var Ae=performance.markResourceTiming;function je(e,t,n,r,i){if(e&&e.reject(r),t.body?.stream!=null&&pe(t.body.stream)&&t.body.stream.cancel(r).catch(e=>{if(e.code!==`ERR_INVALID_STATE`)throw e}),n==null)return;let a=c(n);a.body?.stream!=null&&pe(a.body.stream)&&i.error(r)}function Me({request:e,processRequestBodyChunkLength:t,processRequestEndOfBody:n,processResponse:r,processResponseEndOfBody:i,processResponseConsumeBody:a,useParallelQueue:o=!1,dispatcher:s=_e(),requestObject:c=null}){H(s);let l=null,u=!1;e.client!=null&&(l=e.client.globalObject,u=e.client.crossOriginIsolatedCapability);let d=T({startTime:A(u)}),f={controller:new Ee(s),request:e,timingInfo:d,processRequestBodyChunkLength:t,processRequestEndOfBody:n,processResponse:r,processResponseConsumeBody:a,processResponseEndOfBody:i,taskDestination:l,crossOriginIsolatedCapability:u,requestObject:c};return H(!e.body||e.body.stream),e.window===`client`&&(e.window=e.client?.globalObject?.constructor?.name===`Window`?e.client:`no-window`),e.origin===`client`&&(e.origin=e.client.origin),e.policyContainer===`client`&&(e.policyContainer=e.client==null?g():_(e.client.policyContainer)),e.headersList.contains(`accept`,!0)||e.headersList.append(`accept`,`*/*`,!0),e.headersList.contains(`accept-language`,!0)||e.headersList.append(`accept-language`,`*`,!0),e.priority,ce.has(e.destination),Ne(f,!1),f.controller}async function Ne(e,t){try{let n=e.request,i=null;if(n.localURLsOnly&&!L(S(n))&&(i=r(`local URLs only`)),w(n),v(n)===`blocked`&&(i=r(`bad port`)),n.referrerPolicy===``&&(n.referrerPolicy=n.policyContainer.referrerPolicy),n.referrer!==`no-referrer`&&(n.referrer=k(n)),i===null){let t=S(n);j(t,n.url)&&n.responseTainting===`basic`||t.protocol===`data:`||n.mode===`navigate`||n.mode===`websocket`?(n.responseTainting=`basic`,i=await Pe(e)):n.mode===`same-origin`?i=r(`request mode cannot be "same-origin"`):n.mode===`no-cors`?n.redirect===`follow`?(n.responseTainting=`opaque`,i=await Pe(e)):i=r(`redirect mode cannot be "follow" for "no-cors" request`):R(S(n))?(n.responseTainting=`cors`,i=await Le(e)):i=r(`URL scheme must be a HTTP(S) scheme`)}if(t)return i;i.status!==0&&!i.internalResponse&&(n.responseTainting,n.responseTainting===`basic`?i=a(i,`basic`):n.responseTainting===`cors`?i=a(i,`cors`):n.responseTainting===`opaque`?i=a(i,`opaque`):H(!1));let o=i.status===0?i:i.internalResponse;if(o.urlList.length===0&&o.urlList.push(...n.urlList),n.timingAllowFailed||(i.timingAllowPassed=!0),i.type===`opaque`&&o.status===206&&o.rangeRequested&&!n.headers.contains(`range`,!0)&&(i=o=r()),i.status!==0&&(n.method===`HEAD`||n.method===`CONNECT`||G.includes(o.status))&&(o.body=null,e.controller.dump=!0),n.integrity){let t=t=>Ie(e,r(t));if(n.responseTainting===`opaque`||i.body==null){t(i.error);return}F(i.body,r=>{be(r,n.integrity)?(i.body=oe(r)[0],Ie(e,i)):t(`integrity mismatch`)},t)}else Ie(e,i)}catch(t){e.controller.terminate(t)}}function Pe(t){if(M(t))return Promise.resolve(i(t));let{request:n}=t,{protocol:a}=S(n);switch(a){case`about:`:return Promise.resolve(r(`about scheme is not supported`));case`blob:`:{we||=e(`node:buffer`).resolveObjectURL;let t=S(n);if(t.search.length!==0)return Promise.resolve(r(`NetworkError when attempting to fetch resource.`));let i=we(t.toString());if(n.method!==`GET`||!ve.is.Blob(i))return Promise.resolve(r(`invalid method`));let a=o(),s=i.size,c=xe(`${s}`),l=i.type;if(n.headersList.contains(`range`,!0)){a.rangeRequested=!0;let e=B(n.headersList.get(`range`,!0),!0);if(e===`failure`)return Promise.resolve(r(`failed to fetch the data URL`));let{rangeStartValue:t,rangeEndValue:o}=e;if(t===null)t=s-o,o=t+o-1;else{if(t>=s)return Promise.resolve(r(`Range start is greater than the blob's size.`));(o===null||o>=s)&&(o=s-1)}let c=i.slice(t,o+1,l);a.body=U(c)[0];let u=xe(`${c.size}`),d=te(t,o,s);a.status=206,a.statusText=`Partial Content`,a.headersList.set(`content-length`,u,!0),a.headersList.set(`content-type`,l,!0),a.headersList.set(`content-range`,d,!0)}else{let e=U(i);a.statusText=`OK`,a.body=e[0],a.headersList.set(`content-length`,c,!0),a.headersList.set(`content-type`,l,!0)}return Promise.resolve(a)}case`data:`:{let e=J(S(n));if(e===`failure`)return Promise.resolve(r(`failed to fetch the data URL`));let t=Y(e.mimeType);return Promise.resolve(o({statusText:`OK`,headersList:[[`content-type`,{name:`Content-Type`,value:t}]],body:oe(e.body)[0]}))}case`file:`:return Promise.resolve(r(`not implemented... yet...`));case`http:`:case`https:`:return Le(t).catch(e=>r(e));default:return Promise.resolve(r(`unknown scheme`))}}function Fe(e,t){e.request.done=!0,e.processResponseDone!=null&&queueMicrotask(()=>e.processResponseDone(t))}function Ie(e,t){let n=e.timingInfo;e.request.destination===`document`&&(e.controller.fullTimingInfo=n);let r=()=>{let r=Date.now();e.controller.reportTimingSteps=()=>{if(!R(e.request.url))return;n.endTime=r;let i=t.cacheState,a=t.bodyInfo;t.timingAllowPassed||(n=T(n),i=``);let o=0;if(e.request.mode!==`navigate`||!t.hasCrossOriginRedirects){o=t.status;let e=V(t.headersList);e!==`failure`&&(a.contentType=X(e))}e.request.initiatorType!=null&&Ae(n,e.request.url.href,e.request.initiatorType,globalThis,i,a,o)};let i=()=>{e.request.done=!0,e.processResponseEndOfBody!=null&&queueMicrotask(()=>e.processResponseEndOfBody(t)),e.request.initiatorType!=null&&e.controller.reportTimingSteps()};queueMicrotask(()=>i())};e.processResponse!=null&&queueMicrotask(()=>{e.processResponse(t),e.processResponse=null});let i=t.type===`error`?t:t.internalResponse??t;if(i.body==null?r():de(i.body.stream,()=>{r()}),e.processResponseConsumeBody!=null){let n=n=>e.processResponseConsumeBody(t,n);i.body==null?queueMicrotask(()=>n(null)):F(i.body,n,()=>e.processResponseConsumeBody(t,`failure`))}}async function Le(e){let t=e.request,n=null,i=null,a=e.timingInfo;if(t.serviceWorkers,n===null){if(t.redirect===`follow`&&(t.serviceWorkers=`none`),i=n=await ze(e),t.responseTainting===`cors`&&D(t,n)===`failure`)return r(`cors failure`);y(t,n)===`failure`&&(t.timingAllowFailed=!0)}return(t.responseTainting===`opaque`||n.type===`opaque`)&&O(t.origin,t.client,t.destination,i)===`blocked`?r(`blocked`):(W.has(i.status)&&(t.redirect!==`manual`&&e.controller.connection.destroy(),t.redirect===`error`?n=r(`unexpected redirect`):t.redirect===`manual`?n=i:t.redirect===`follow`?n=await Re(e,n):H(!1)),n.timingInfo=a,n)}function Re(e,t){let n=e.request,i=t.internalResponse?t.internalResponse:t,a;try{if(a=x(i,S(n).hash),a==null)return t}catch(e){return Promise.resolve(r(e))}if(!R(a))return Promise.resolve(r(`URL scheme must be a HTTP(S) scheme`));if(n.redirectCount===20)return Promise.resolve(r(`redirect count exceeded`));if(n.redirectCount+=1,n.mode===`cors`&&(a.username||a.password)&&!j(n,a))return Promise.resolve(r(`cross origin not allowed for request mode "cors"`));if(n.responseTainting===`cors`&&(a.username||a.password))return Promise.resolve(r(`URL cannot contain credentials for request mode "cors"`));if(i.status!==303&&n.body!=null&&n.body.source==null)return Promise.resolve(r());if([301,302].includes(i.status)&&n.method===`POST`||i.status===303&&!Se.includes(n.method)){n.method=`GET`,n.body=null;for(let e of se)n.headersList.delete(e)}j(S(n),a)||(n.headersList.delete(`authorization`,!0),n.headersList.delete(`proxy-authorization`,!0),n.headersList.delete(`cookie`,!0),n.headersList.delete(`host`,!0)),n.body!=null&&(H(n.body.source!=null),n.body=oe(n.body.source)[0]);let o=e.timingInfo;return o.redirectEndTime=o.postRedirectStartTime=A(e.crossOriginIsolatedCapability),o.redirectStartTime===0&&(o.redirectStartTime=o.startTime),n.urlList.push(a),C(n,i),Ne(e,!0)}async function ze(e,t=!1,n=!1){let a=e.request,o=null,s=null,c=null;a.window===`no-window`&&a.redirect===`error`?(o=e,s=a):(a.body?.source==null?(s=d({...a,body:null}),s.body=a.body):s=d(a),o={...e},o.request=s);let l=a.credentials===`include`||a.credentials===`same-origin`&&a.responseTainting===`basic`,u=s.body?s.body.length:null,f=null;if(s.body==null&&[`POST`,`PUT`].includes(s.method)&&(f=`0`),u!=null&&(f=xe(`${u}`)),f!=null&&!s.headersList.contains(`content-length`,!0)&&s.headersList.append(`content-length`,f,!0),u!=null&&s.keepalive,ve.is.URL(s.referrer)&&s.headersList.append(`referer`,xe(s.referrer.href),!0),b(s),E(s),s.headersList.contains(`user-agent`,!0)||s.headersList.append(`user-agent`,Ce,!0),s.cache==="default"&&(s.headersList.contains(`if-modified-since`,!0)||s.headersList.contains(`if-none-match`,!0)||s.headersList.contains(`if-unmodified-since`,!0)||s.headersList.contains(`if-match`,!0)||s.headersList.contains(`if-range`,!0))&&(s.cache=`no-store`),s.cache===`no-cache`&&!s.preventNoCacheCacheControlHeaderModification&&!s.headersList.contains(`cache-control`,!0)&&s.headersList.append(`cache-control`,`max-age=0`,!0),(s.cache===`no-store`||s.cache===`reload`)&&(s.headersList.contains(`pragma`,!0)||s.headersList.append(`pragma`,`no-cache`,!0),s.headersList.contains(`cache-control`,!0)||s.headersList.append(`cache-control`,`no-cache`,!0)),s.headersList.contains(`range`,!0)&&s.headersList.append(`accept-encoding`,`identity`,!0),s.headersList.contains(`accept-encoding`,!0)||(ee(S(s))?s.headersList.append(`accept-encoding`,`br, gzip, deflate, zstd`,!0):s.headersList.append(`accept-encoding`,`gzip, deflate`,!0)),s.headersList.delete(`host`,!0),l&&!s.headersList.contains(`authorization`,!0)){let e=null;if((!re(s)||s.useURLCredentials!==void 0&&ie(S(s)))&&ie(S(s))&&t){let{username:t,password:n}=S(s);e=`Basic ${Buffer.from(`${t}:${n}`).toString(`base64`)}`}e!==null&&s.headersList.append(`Authorization`,e,!1)}if(s.cache=`no-store`,s.cache!==`no-store`&&s.cache,c==null){if(s.cache===`only-if-cached`)return r(`only if cached`);let e=await Be(o,l,n);!K.has(s.method)&&e.status>=200&&e.status,c??=e}if(c.urlList=[...s.urlList],s.headersList.contains(`range`,!0)&&(c.rangeRequested=!0),c.requestIncludesCredentials=l,c.status===401&&s.responseTainting!==`cors`&&l&&(a.useURLCredentials!==void 0||ae(a.traversableForUserPrompts))){if(a.body!=null){if(a.body.source==null)return c;a.body=oe(a.body.source)[0]}if(a.useURLCredentials===void 0||t)return M(e)?i(e):c;e.controller.connection.destroy(),c=await ze(e,!0)}if(c.status===407)return a.window===`no-window`?r():M(e)?i(e):r(`proxy authentication required`);if(c.status===421&&!n&&(a.body==null||a.body.source!=null)){if(M(e))return i(e);e.controller.connection.destroy(),c=await ze(e,t,!0)}return c}async function Be(e,t=!1,n=!1){H(!e.controller.connection||e.controller.connection.destroyed),e.controller.connection={abort:null,destroyed:!1,destroy(e){this.destroyed||(this.destroyed=!0,this.abort?.(e??new DOMException(`The operation was aborted.`,`AbortError`)))}};let a=e.request,s=null,c=e.timingInfo;a.cache=`no-store`,a.mode;let u=null;if(a.body==null&&e.processRequestEndOfBody)queueMicrotask(()=>e.processRequestEndOfBody());else if(a.body!=null){let t=async function*(t){M(e)||(yield t,e.processRequestBodyChunkLength?.(t.byteLength))},n=()=>{M(e)||e.processRequestEndOfBody&&e.processRequestEndOfBody()},r=t=>{M(e)||(t.name===`AbortError`?e.controller.abort():e.controller.terminate(t))};u=(async function*(){try{for await(let e of a.body.stream)yield*t(e);n()}catch(e){r(e)}})()}try{let{body:t,status:n,statusText:r,headersList:i,socket:a}=await p({body:u});if(a)s=o({status:n,statusText:r,headersList:i,socket:a});else{let a=t[Symbol.asyncIterator]();e.controller.next=()=>a.next(),s=o({status:n,statusText:r,headersList:i})}}catch(t){return t.name===`AbortError`?(e.controller.connection.destroy(),i(e,t)):r(t)}let d=new ReadableStream({start(t){e.controller.controller=t},pull:()=>e.controller.resume(),cancel:t=>{M(e)||e.controller.abort(t)},type:`bytes`});s.body={stream:d,source:null,length:null},e.controller.resume||e.controller.on(`terminated`,f),e.controller.resume=async()=>{for(;;){let t,n;try{let{done:n,value:r}=await e.controller.next();if(N(e))break;t=n?void 0:r}catch(r){e.controller.ended&&!c.encodedBodySize?t=void 0:(t=r,n=!0)}if(t===void 0){I(e.controller.controller),Fe(e,s);return}if(c.decodedBodySize+=t?.byteLength??0,n){e.controller.terminate(t);return}let r=new Uint8Array(t);if(r.byteLength&&e.controller.controller.enqueue(r),fe(d)){e.controller.terminate();return}if(e.controller.controller.desiredSize<=0)return}};function f(t){N(e)?(s.aborted=!0,pe(d)&&e.controller.controller.error(e.controller.serializedAbortReason)):pe(d)&&e.controller.controller.error(TypeError(`terminated`,{cause:P(t)?t:void 0})),e.controller.connection.destroy()}return s;function p({body:t}){let n=S(a),r=e.controller.dispatcher,i=n.pathname+n.search,o=n.search.length===0&&n.href[n.href.length-n.hash.length-1]===`?`;return s(t);function s(t,u){return new Promise((d,f)=>r.dispatch({path:o?`${i}?`:i,origin:n.origin,method:a.method,body:r.isMockActive?a.body&&(a.body.source||a.body.stream):t,__mockAgentBodyForDispatch:t,headers:a.headersList.entries,maxRedirections:0,upgrade:a.mode===`websocket`?`websocket`:void 0,...u===!1?{allowH2:u}:null},{body:null,abort:null,onRequestStart(t){let{connection:n}=e.controller;c.finalConnectionTimingInfo=z(void 0,c.postRedirectStartTime,e.crossOriginIsolatedCapability);let r=e=>t.abort(e);n.destroyed?r(new DOMException(`The operation was aborted.`,`AbortError`)):(e.controller.on(`terminated`,r),this.abort=n.abort=r),c.finalNetworkRequestStartTime=A(e.crossOriginIsolatedCapability)},onResponseStarted(){c.finalNetworkResponseStartTime=A(e.crossOriginIsolatedCapability)},onResponseStart(e,t,n,r){if(t<200)return;let i=e?.rawHeaders??[],o=new l;Te(o,n,i);let s=o.get(`location`,!0)&&a.redirect===`follow`&&W.has(t),c=[];if(a.method!==`HEAD`&&a.method!==`CONNECT`&&!G.includes(t)&&!s){let t=o.get(`content-encoding`,!0),n=t?t.toLowerCase().split(`,`):[];if(n.length>5){e.abort(Error(`too many content-encodings in response: ${n.length}, maximum allowed is 5`));return}for(let e=n.length-1;e>=0;--e){let t=n[e].trim();if(t===`x-gzip`||t===`gzip`)c.push(h.createGunzip({flush:h.constants.Z_SYNC_FLUSH,finishFlush:h.constants.Z_SYNC_FLUSH}));else if(t===`deflate`)c.push(ne({flush:h.constants.Z_SYNC_FLUSH,finishFlush:h.constants.Z_SYNC_FLUSH}));else if(t===`br`)c.push(h.createBrotliDecompress({flush:h.constants.BROTLI_OPERATION_FLUSH,finishFlush:h.constants.BROTLI_OPERATION_FLUSH}));else if(t===`zstd`)c.push(h.createZstdDecompress({flush:h.constants.ZSTD_e_continue,finishFlush:h.constants.ZSTD_e_end,params:{[h.constants.ZSTD_d_windowLogMax]:23}}));else{c.length=0;break}}}this.body=new ue({read:()=>e.resume()});let u=t=>this.onResponseError(e,t);d({status:t,statusText:r,headersList:o,body:c.length?q(this.body,...c,t=>{t&&this.onResponseError(e,t)}).on(`error`,u):this.body.on(`error`,u)})},onResponseData(t,n){if(e.controller.dump)return;let r=n;c.encodedBodySize+=r.byteLength,this.body.push(r)===!1&&t.pause()},onResponseEnd(){this.abort&&e.controller.off(`terminated`,this.abort),e.controller.ended=!0,this.body?.push(null)},onResponseError(n,r){this.abort&&e.controller.off(`terminated`,this.abort),a.mode===`websocket`&&u!==!1&&r?.code===`UND_ERR_INFO`&&r?.message===`HTTP/2: Extended CONNECT protocol not supported by server`?d(s(t,!1)):(this.body?.destroy(r),n?.aborted||e.controller.terminate(r),f(r))},onRequestUpgrade(e,t,n,r){if(r.session!=null&&t!==200||r.session==null&&t!==101)return r.session!=null&&e.abort(new ge(`bad upgrade`,null)),!1;let i=e?.rawHeaders??[],a=new l;return Te(a,n,i),d({status:t,statusText:ye[t],headersList:a,socket:r}),!0}}))}}}n.exports={fetch:Oe,Fetch:Ee,fetching:Me,finalizeAndReportTiming:ke}})),Pr=t(((t,n)=>{var r=e(`node:assert`),{URLSerializer:i}=ln(),{isValidHeaderName:a}=dn();function o(e,t,n=!1){return i(e,n)===i(t,n)}function s(e){r(e!==null);let t=[];for(let n of e.split(`,`))n=n.trim(),a(n)&&t.push(n);return t}n.exports={urlEquals:o,getFieldValues:s}})),Fr=t(((t,n)=>{var r=e(`node:assert`),{kConstruct:i}=Z(),{urlEquals:a,getFieldValues:o}=Pr(),{kEnumerableProperty:s,isDisturbed:c}=$(),{webidl:l}=un(),{cloneResponse:u,fromInnerResponse:d,getResponseState:f}=Ar(),{Request:p,fromInnerRequest:m,getRequestState:h}=jr(),{fetching:g}=Nr(),{urlIsHttpHttpsScheme:_,readAllBytes:v}=dn(),y=class{#e;constructor(){arguments[0]!==i&&l.illegalConstructor(),l.util.markAsUncloneable(this),this.#e=arguments[1]}async match(e,t={}){l.brandCheck(this,l.is.Cache);let n=`Cache.match`;l.argumentLengthCheck(arguments,1,n),e=l.converters.RequestInfo(e),t=l.converters.CacheQueryOptions(t,n,`options`);let r=this.#i(e,t,1);if(r.length!==0)return r[0]}async matchAll(e=void 0,t={}){return l.brandCheck(this,l.is.Cache),e!==void 0&&(e=l.converters.RequestInfo(e)),t=l.converters.CacheQueryOptions(t,`Cache.matchAll`,`options`),this.#i(e,t)}async add(e){l.brandCheck(this,l.is.Cache),l.argumentLengthCheck(arguments,1,`Cache.add`),e=l.converters.RequestInfo(e);let t=[e];return await this.addAll(t)}async addAll(e){l.brandCheck(this,l.is.Cache);let t=`Cache.addAll`;l.argumentLengthCheck(arguments,1,t);let n=[],r=[];for(let n of e){if(n===void 0)throw l.errors.conversionFailed({prefix:t,argument:`Argument 1`,types:[`undefined is not allowed`]});if(n=l.converters.RequestInfo(n),typeof n==`string`)continue;let e=h(n);if(!_(e.url)||e.method!==`GET`)throw l.errors.exception({header:t,message:`Expected http/s scheme when method is not GET.`})}let i=[];for(let a of e){let e=h(new p(a));if(!_(e.url))throw l.errors.exception({header:t,message:`Expected http/s scheme.`});e.initiator=`fetch`,e.destination=`subresource`,r.push(e);let s=Promise.withResolvers();i.push(g({request:e,processResponse(e){if(e.type===`error`||e.status===206||e.status<200||e.status>299)s.reject(l.errors.exception({header:`Cache.addAll`,message:`Received an invalid status code or the request failed.`}));else if(e.headersList.contains(`vary`)){let t=o(e.headersList.get(`vary`));for(let e of t)if(e===`*`){s.reject(l.errors.exception({header:`Cache.addAll`,message:`invalid vary field value`}));for(let e of i)e.abort();return}}},processResponseConsumeBody(e){e.aborted?s.reject(new DOMException(`aborted`,`AbortError`)):s.resolve(e)}})),n.push(s.promise)}let a=await Promise.all(n),s=[],c=0;for(let e of a){let t={type:`put`,request:r[c],response:e};s.push(t),c++}let u=Promise.withResolvers(),d=null;try{this.#t(s)}catch(e){d=e}return queueMicrotask(()=>{d===null?u.resolve(void 0):u.reject(d)}),u.promise}async put(e,t){l.brandCheck(this,l.is.Cache);let n=`Cache.put`;l.argumentLengthCheck(arguments,2,n),e=l.converters.RequestInfo(e),t=l.converters.Response(t,n,`response`);let r=null;if(r=l.is.Request(e)?h(e):h(new p(e)),!_(r.url)||r.method!==`GET`)throw l.errors.exception({header:n,message:`Expected an http/s scheme when method is not GET`});let i=f(t);if(i.status===206)throw l.errors.exception({header:n,message:`Got 206 status`});if(i.headersList.contains(`vary`)){let e=o(i.headersList.get(`vary`));for(let t of e)if(t===`*`)throw l.errors.exception({header:n,message:`Got * vary field value`})}if(i.body&&(c(i.body.stream)||i.body.stream.locked))throw l.errors.exception({header:n,message:`Response body is locked or disturbed`});let a=u(i),s=Promise.withResolvers();i.body==null?s.resolve(void 0):v(i.body.stream.getReader(),s.resolve,s.reject);let d=[],m={type:`put`,request:r,response:a};d.push(m);let g=await s.promise;a.body!=null&&(a.body.source=g);let y=Promise.withResolvers(),b=null;try{this.#t(d)}catch(e){b=e}return queueMicrotask(()=>{b===null?y.resolve():y.reject(b)}),y.promise}async delete(e,t={}){l.brandCheck(this,l.is.Cache);let n=`Cache.delete`;l.argumentLengthCheck(arguments,1,n),e=l.converters.RequestInfo(e),t=l.converters.CacheQueryOptions(t,n,`options`);let i=null;if(l.is.Request(e)){if(i=h(e),i.method!==`GET`&&!t.ignoreMethod)return!1}else r(typeof e==`string`),i=h(new p(e));let a=[],o={type:`delete`,request:i,options:t};a.push(o);let s=Promise.withResolvers(),c=null,u;try{u=this.#t(a)}catch(e){c=e}return queueMicrotask(()=>{c===null?s.resolve(!!u?.length):s.reject(c)}),s.promise}async keys(e=void 0,t={}){l.brandCheck(this,l.is.Cache),e!==void 0&&(e=l.converters.RequestInfo(e)),t=l.converters.CacheQueryOptions(t,`Cache.keys`,`options`);let n=null;if(e!==void 0){if(l.is.Request(e)){if(n=h(e),n.method!==`GET`&&!t.ignoreMethod)return[]}else typeof e==`string`&&(n=h(new p(e)))}let r=Promise.withResolvers(),i=[];if(e===void 0)for(let e of this.#e)i.push(e[0]);else{let e=this.#n(n,t);for(let t of e)i.push(t[0])}return queueMicrotask(()=>{let e=[];for(let t of i){let n=m(t,void 0,new AbortController().signal,`immutable`);e.push(n)}r.resolve(Object.freeze(e))}),r.promise}#t(e){let t=this.#e,n=[...t],i=[],a=[];try{for(let n of e){if(n.type!==`delete`&&n.type!==`put`)throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`operation type does not match "delete" or "put"`});if(n.type===`delete`&&n.response!=null)throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`delete operation should not have an associated response`});if(this.#n(n.request,n.options,i).length)throw new DOMException(`???`,`InvalidStateError`);let e;if(n.type===`delete`){if(e=this.#n(n.request,n.options),e.length===0)return[];for(let n of e){let e=t.indexOf(n);r(e!==-1),t.splice(e,1)}}else if(n.type===`put`){if(n.response==null)throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`put operation should have an associated response`});let a=n.request;if(!_(a.url))throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`expected http or https scheme`});if(a.method!==`GET`)throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`not get method`});if(n.options!=null)throw l.errors.exception({header:`Cache.#batchCacheOperations`,message:`options must not be defined`});e=this.#n(n.request);for(let n of e){let e=t.indexOf(n);r(e!==-1),t.splice(e,1)}t.push([n.request,n.response]),i.push([n.request,n.response])}a.push([n.request,n.response])}return a}catch(e){throw this.#e.length=0,this.#e=n,e}}#n(e,t,n){let r=[],i=n??this.#e;for(let n of i){let[i,a]=n;this.#r(e,i,a,t)&&r.push(n)}return r}#r(e,t,n=null,r){let i=new URL(e.url),s=new URL(t.url);if(r?.ignoreSearch&&(s.search=``,i.search=``),!a(i,s,!0))return!1;if(n==null||r?.ignoreVary||!n.headersList.contains(`vary`))return!0;let c=o(n.headersList.get(`vary`));for(let n of c)if(n===`*`||t.headersList.get(n)!==e.headersList.get(n))return!1;return!0}#i(e,t,n=1/0){let r=null;if(e!==void 0){if(l.is.Request(e)){if(r=h(e),r.method!==`GET`&&!t.ignoreMethod)return[]}else typeof e==`string`&&(r=h(new p(e)))}let i=[];if(e===void 0)for(let e of this.#e)i.push(e[1]);else{let e=this.#n(r,t);for(let t of e)i.push(t[1])}let a=[];for(let e of i){let t=d(u(e),`immutable`);if(a.push(t),a.length>=n)break}return Object.freeze(a)}static{l.is.Cache=e=>typeof e==`object`&&!!e&&#e in e}};Object.defineProperties(y.prototype,{[Symbol.toStringTag]:{value:`Cache`,configurable:!0},match:s,matchAll:s,add:s,addAll:s,put:s,delete:s,keys:s});var b=[{key:`ignoreSearch`,converter:l.converters.boolean,defaultValue:()=>!1},{key:`ignoreMethod`,converter:l.converters.boolean,defaultValue:()=>!1},{key:`ignoreVary`,converter:l.converters.boolean,defaultValue:()=>!1}];l.converters.CacheQueryOptions=l.dictionaryConverter(b),l.converters.MultiCacheQueryOptions=l.dictionaryConverter([...b,{key:`cacheName`,converter:l.converters.DOMString}]),l.converters.Response=l.interfaceConverter(l.is.Response,`Response`),l.converters[`sequence<RequestInfo>`]=l.sequenceConverter(l.converters.RequestInfo),n.exports={Cache:y}})),Ir=t(((e,t)=>{var{Cache:n}=Fr(),{webidl:r}=un(),{kEnumerableProperty:i}=$(),{kConstruct:a}=Z(),o=class{#e=new Map;constructor(){arguments[0]!==a&&r.illegalConstructor(),r.util.markAsUncloneable(this)}async match(e,t={}){if(r.brandCheck(this,r.is.CacheStorage),r.argumentLengthCheck(arguments,1,`CacheStorage.match`),e=r.converters.RequestInfo(e),t=r.converters.MultiCacheQueryOptions(t),t.cacheName!=null){if(this.#e.has(t.cacheName))return await new n(a,this.#e.get(t.cacheName)).match(e,t)}else for(let r of this.#e.values()){let i=await new n(a,r).match(e,t);if(i!==void 0)return i}}async has(e){r.brandCheck(this,r.is.CacheStorage);let t=`CacheStorage.has`;return r.argumentLengthCheck(arguments,1,t),e=r.converters.DOMString(e,t,`cacheName`),this.#e.has(e)}async open(e){r.brandCheck(this,r.is.CacheStorage);let t=`CacheStorage.open`;if(r.argumentLengthCheck(arguments,1,t),e=r.converters.DOMString(e,t,`cacheName`),this.#e.has(e))return new n(a,this.#e.get(e));let i=[];return this.#e.set(e,i),new n(a,i)}async delete(e){r.brandCheck(this,r.is.CacheStorage);let t=`CacheStorage.delete`;return r.argumentLengthCheck(arguments,1,t),e=r.converters.DOMString(e,t,`cacheName`),this.#e.delete(e)}async keys(){return r.brandCheck(this,r.is.CacheStorage),[...this.#e.keys()]}static{r.is.CacheStorage=e=>typeof e==`object`&&!!e&&#e in e}};Object.defineProperties(o.prototype,{[Symbol.toStringTag]:{value:`CacheStorage`,configurable:!0},match:i,has:i,open:i,delete:i,keys:i}),t.exports={CacheStorage:o}})),Lr=t(((e,t)=>{t.exports={maxAttributeValueSize:1024,maxNameValuePairSize:4096}})),Rr=t(((e,t)=>{function n(e){for(let t=0;t<e.length;++t){let n=e.charCodeAt(t);if(n>=0&&n<=8||n>=10&&n<=31||n===127)return!0}return!1}function r(e){for(let t=0;t<e.length;++t){let n=e.charCodeAt(t);if(n<33||n>126||n===34||n===40||n===41||n===60||n===62||n===64||n===44||n===59||n===58||n===92||n===47||n===91||n===93||n===63||n===61||n===123||n===125)throw Error(`Invalid cookie name`)}}function i(e){let t=e.length,n=0;if(e[0]===`"`){if(t===1||e[t-1]!==`"`)throw Error(`Invalid cookie value`);--t,++n}for(;n<t;){let t=e.charCodeAt(n++);if(t<33||t>126||t===34||t===44||t===59||t===92)throw Error(`Invalid cookie value`)}}function a(e){for(let t=0;t<e.length;++t){let n=e.charCodeAt(t);if(n<32||n>126||n===59)throw Error(`Invalid cookie path`)}}function o(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122}function s(e){if(e===` `)return;if(e.length>255)throw Error(`Invalid cookie domain`);let t=0;for(let n=0;n<e.length;++n){let r=e.charCodeAt(n);if(r===46){if(t===0||e.charCodeAt(n-1)===45)throw Error(`Invalid cookie domain`);t=0}else if(t===0&&!o(r)||!o(r)&&r!==45||++t>63)throw Error(`Invalid cookie domain`)}if(t===0||e.charCodeAt(e.length-1)===45)throw Error(`Invalid cookie domain`)}var c=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],l=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],u=Array(61).fill(0).map((e,t)=>t.toString().padStart(2,`0`));function d(e){return typeof e==`number`&&(e=new Date(e)),`${c[e.getUTCDay()]}, ${u[e.getUTCDate()]} ${l[e.getUTCMonth()]} ${e.getUTCFullYear()} ${u[e.getUTCHours()]}:${u[e.getUTCMinutes()]}:${u[e.getUTCSeconds()]} GMT`}function f(e){if(e<0)throw Error(`Invalid cookie max-age`)}function p(e){if(e.name.length===0)return null;r(e.name),i(e.value);let t=[`${e.name}=${e.value}`];if(e.name.startsWith(`__Secure-`)&&(e.secure=!0),e.name.startsWith(`__Host-`)&&(e.secure=!0,e.domain=null,e.path=`/`),e.secure&&t.push(`Secure`),e.httpOnly&&t.push(`HttpOnly`),typeof e.maxAge==`number`&&(f(e.maxAge),t.push(`Max-Age=${e.maxAge}`)),e.domain&&(s(e.domain),t.push(`Domain=${e.domain}`)),e.path&&(a(e.path),t.push(`Path=${e.path}`)),e.expires!=null){let n=e.expires instanceof Date?e.expires.getTime():e.expires;typeof n==`number`&&Number.isFinite(n)&&Math.abs(n)<=864e13&&t.push(`Expires=${d(e.expires)}`)}e.sameSite&&t.push(`SameSite=${e.sameSite}`);for(let n of e.unparsed){if(!n.includes(`=`))throw Error(`Invalid unparsed`);let[e,...a]=n.split(`=`),o=e.trim(),s=a.join(`=`);r(o),i(s),t.push(`${o}=${s}`)}return t.join(`; `)}t.exports={isCTLExcludingHtab:n,validateCookieName:r,validateCookiePath:a,validateCookieValue:i,toIMFDate:d,stringify:p}})),zr=t(((t,n)=>{var{collectASequenceOfCodePointsFast:r}=cn(),{maxNameValuePairSize:i,maxAttributeValueSize:a}=Lr(),{isCTLExcludingHtab:o}=Rr(),s=e(`node:assert`);function c(e){if(o(e))return null;let t=``,n=``,a=``,s=``;if(e.includes(`;`)){let i={position:0};t=r(`;`,e,i),n=e.slice(i.position)}else t=e;if(!t.includes(`=`))s=t;else{let e={position:0};a=r(`=`,t,e),s=t.slice(e.position+1)}return a=a.trim(),s=s.trim(),a.length+s.length>i?null:{name:a,value:s,...l(n)}}function l(e,t={}){for(;;){if(e.length===0)return t;s(e[0]===`;`),e=e.slice(1);let n=``;e.includes(`;`)?(n=r(`;`,e,{position:0}),e=e.slice(n.length)):(n=e,e=``);let i=``,o=``;if(n.includes(`=`)){let e={position:0};i=r(`=`,n,e),o=n.slice(e.position+1)}else i=n;if(i=i.trim(),o=o.trim(),o.length>a)continue;let c=i.toLowerCase();if(c===`expires`){let e=new Date(o);Number.isNaN(e.getTime())||(t.expires=e)}else if(c===`max-age`){let e=o.charCodeAt(0),n=e>=48&&e<=57,r=o[0]===`-`&&o.length>1;if(!n&&!r||/[^\d]/.test(o.slice(1)))continue;t.maxAge=Number(o)}else if(c===`domain`){let e=o;e[0]===`.`&&(e=e.slice(1)),e=e.toLowerCase(),t.domain=e}else if(c===`path`){let e=``;e=o.length===0||o[0]!==`/`?`/`:o,t.path=e}else if(c===`secure`)t.secure=!0;else if(c===`httponly`)t.httpOnly=!0;else if(c===`samesite`){let e=o.toLowerCase();e===`none`?t.sameSite=`None`:e===`strict`?t.sameSite=`Strict`:e===`lax`&&(t.sameSite=`Lax`)}else t.unparsed??=[],t.unparsed.push(`${i}=${o}`)}}n.exports={parseSetCookie:c,parseUnparsedAttributes:l}})),Br=t(((e,t)=>{var{parseSetCookie:n}=zr(),{stringify:r}=Rr(),{webidl:i}=un(),a=e=>i.brandCheck(e,i.util.MakeTypeAssertion(globalThis.Headers)),o=e=>i.brandCheck(e,i.is.Headers);function s(e){try{o(e);return}catch{}a(e)}function c(e){i.argumentLengthCheck(arguments,1,`getCookies`),s(e);let t=e.get(`cookie`),n={__proto__:null};if(!t)return n;for(let e of t.split(`;`)){let[t,...r]=e.split(`=`);n[t.trim()]=r.join(`=`)}return n}function l(e,t,n){s(e);let r=`deleteCookie`;i.argumentLengthCheck(arguments,2,r),t=i.converters.DOMString(t,r,`name`),n=i.converters.DeleteCookieAttributes(n),f(e,{name:t,value:``,expires:new Date(0),...n})}function u(e){i.argumentLengthCheck(arguments,1,`getSetCookies`),s(e);let t=e.getSetCookie();return t?t.map(e=>n(e)):[]}function d(e){return e=i.converters.DOMString(e),n(e)}function f(e,t){i.argumentLengthCheck(arguments,2,`setCookie`),s(e),t=i.converters.Cookie(t);let n=r(t);n&&e.append(`set-cookie`,n,!0)}i.converters.DeleteCookieAttributes=i.dictionaryConverter([{converter:i.nullableConverter(i.converters.DOMString),key:`path`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters.DOMString),key:`domain`,defaultValue:()=>null}]),i.converters.Cookie=i.dictionaryConverter([{converter:i.converters.DOMString,key:`name`},{converter:i.converters.DOMString,key:`value`},{converter:i.nullableConverter(e=>typeof e==`number`?i.converters[`unsigned long long`](e):new Date(e)),key:`expires`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters[`long long`]),key:`maxAge`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters.DOMString),key:`domain`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters.DOMString),key:`path`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters.boolean),key:`secure`,defaultValue:()=>null},{converter:i.nullableConverter(i.converters.boolean),key:`httpOnly`,defaultValue:()=>null},{converter:i.converters.USVString,key:`sameSite`,allowedValues:[`Strict`,`Lax`,`None`]},{converter:i.sequenceConverter(i.converters.DOMString),key:`unparsed`,defaultValue:()=>[]}]),t.exports={getCookies:c,deleteCookie:l,getSetCookies:u,setCookie:f,parseCookie:d}})),Vr=t(((e,t)=>{var{webidl:n}=un(),{kEnumerableProperty:r}=$(),{kConstruct:i}=Z(),a,o=class e extends Event{#e;constructor(e,t={}){if(e===i){super(arguments[1],arguments[2]),n.util.markAsUncloneable(this);return}let r=`MessageEvent constructor`;n.argumentLengthCheck(arguments,1,r),e=n.converters.DOMString(e,r,`type`),t=n.converters.MessageEventInit(t,r,`eventInitDict`),super(e,t),this.#e=t,n.util.markAsUncloneable(this)}get data(){return n.brandCheck(this,n.is.MessageEvent),this.#e.data}get origin(){return n.brandCheck(this,n.is.MessageEvent),this.#e.origin}get lastEventId(){return n.brandCheck(this,n.is.MessageEvent),this.#e.lastEventId}get source(){return n.brandCheck(this,n.is.MessageEvent),this.#e.source}get ports(){return n.brandCheck(this,n.is.MessageEvent),Object.isFrozen(this.#e.ports)||Object.freeze(this.#e.ports),this.#e.ports}initMessageEvent(t,r=!1,i=!1,a=null,o=``,s=``,c=null,l=[]){return n.brandCheck(this,n.is.MessageEvent),n.argumentLengthCheck(arguments,1,`MessageEvent.initMessageEvent`),new e(t,{bubbles:r,cancelable:i,data:a,origin:o,lastEventId:s,source:c,ports:l})}static{a=(t,n)=>{let r=new e(i,t,n);return r.#e=n,r.#e.data??=null,r.#e.origin??=``,r.#e.lastEventId??=``,r.#e.source??=null,r.#e.ports??=[],r},n.is.MessageEvent=e=>typeof e==`object`&&!!e&&#e in e}},s=class extends Event{#e;constructor(e,t={}){let r=`CloseEvent constructor`;n.argumentLengthCheck(arguments,1,r),e=n.converters.DOMString(e,r,`type`),t=n.converters.CloseEventInit(t),super(e,t),this.#e=t,n.util.markAsUncloneable(this)}get wasClean(){return n.brandCheck(this,n.is.CloseEvent),this.#e.wasClean}get code(){return n.brandCheck(this,n.is.CloseEvent),this.#e.code}get reason(){return n.brandCheck(this,n.is.CloseEvent),this.#e.reason}static{n.is.CloseEvent=e=>typeof e==`object`&&!!e&&#e in e}},c=class extends Event{#e;constructor(e,t){let r=`ErrorEvent constructor`;n.argumentLengthCheck(arguments,1,r),super(e,t),n.util.markAsUncloneable(this),e=n.converters.DOMString(e,r,`type`),t=n.converters.ErrorEventInit(t??{}),this.#e=t}get message(){return n.brandCheck(this,n.is.ErrorEvent),this.#e.message}get filename(){return n.brandCheck(this,n.is.ErrorEvent),this.#e.filename}get lineno(){return n.brandCheck(this,n.is.ErrorEvent),this.#e.lineno}get colno(){return n.brandCheck(this,n.is.ErrorEvent),this.#e.colno}get error(){return n.brandCheck(this,n.is.ErrorEvent),this.#e.error}static{n.is.ErrorEvent=e=>typeof e==`object`&&!!e&&#e in e}};Object.defineProperties(o.prototype,{[Symbol.toStringTag]:{value:`MessageEvent`,configurable:!0},data:r,origin:r,lastEventId:r,source:r,ports:r,initMessageEvent:r}),Object.defineProperties(s.prototype,{[Symbol.toStringTag]:{value:`CloseEvent`,configurable:!0},reason:r,code:r,wasClean:r}),Object.defineProperties(c.prototype,{[Symbol.toStringTag]:{value:`ErrorEvent`,configurable:!0},message:r,filename:r,lineno:r,colno:r,error:r}),n.converters.MessagePort=n.interfaceConverter(n.is.MessagePort,`MessagePort`),n.converters[`sequence<MessagePort>`]=n.sequenceConverter(n.converters.MessagePort);var l=[{key:`bubbles`,converter:n.converters.boolean,defaultValue:()=>!1},{key:`cancelable`,converter:n.converters.boolean,defaultValue:()=>!1},{key:`composed`,converter:n.converters.boolean,defaultValue:()=>!1}];n.converters.MessageEventInit=n.dictionaryConverter([...l,{key:`data`,converter:n.converters.any,defaultValue:()=>null},{key:`origin`,converter:n.converters.USVString,defaultValue:()=>``},{key:`lastEventId`,converter:n.converters.DOMString,defaultValue:()=>``},{key:`source`,converter:n.nullableConverter(n.converters.MessagePort),defaultValue:()=>null},{key:`ports`,converter:n.converters[`sequence<MessagePort>`],defaultValue:()=>[]}]),n.converters.CloseEventInit=n.dictionaryConverter([...l,{key:`wasClean`,converter:n.converters.boolean,defaultValue:()=>!1},{key:`code`,converter:n.converters[`unsigned short`],defaultValue:()=>0},{key:`reason`,converter:n.converters.USVString,defaultValue:()=>``}]),n.converters.ErrorEventInit=n.dictionaryConverter([...l,{key:`message`,converter:n.converters.DOMString,defaultValue:()=>``},{key:`filename`,converter:n.converters.USVString,defaultValue:()=>``},{key:`lineno`,converter:n.converters[`unsigned long`],defaultValue:()=>0},{key:`colno`,converter:n.converters[`unsigned long`],defaultValue:()=>0},{key:`error`,converter:n.converters.any}]),t.exports={MessageEvent:o,CloseEvent:s,ErrorEvent:c,createFastMessageEvent:a}})),Hr=t(((e,t)=>{t.exports={uid:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,sentCloseFrameState:{SENT:1,RECEIVED:2},staticPropertyDescriptors:{enumerable:!0,writable:!1,configurable:!1},states:{CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},opcodes:{CONTINUATION:0,TEXT:1,BINARY:2,CLOSE:8,PING:9,PONG:10},maxUnsigned16Bit:65535,parserStates:{INFO:0,PAYLOADLENGTH_16:2,PAYLOADLENGTH_64:3,READ_DATA:4},emptyBuffer:Buffer.allocUnsafe(0),sendHints:{text:1,typedArray:2,arrayBuffer:3,blob:4}}})),Ur=t(((t,n)=>{var{states:r,opcodes:i}=Hr(),{isUtf8:a}=e(`node:buffer`),{removeHTTPWhitespace:o}=ln(),{collectASequenceOfCodePointsFast:s}=cn();function c(e){return e===r.CONNECTING}function l(e){return e===r.OPEN}function u(e){return e===r.CLOSING}function d(e){return e===r.CLOSED}function f(e,t,n=(e,t)=>new Event(e,t),r={}){let i=n(e,r);t.dispatchEvent(i)}function p(e,t,n){e.onMessage(t,n)}function m(e){return e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function h(e){if(e.length===0)return!1;for(let t=0;t<e.length;++t){let n=e.charCodeAt(t);if(n<33||n>126||n===34||n===40||n===41||n===44||n===47||n===58||n===59||n===60||n===61||n===62||n===63||n===64||n===91||n===92||n===93||n===123||n===125)return!1}return!0}function g(e){return e>=1e3&&e<1015?e!==1004&&e!==1005&&e!==1006:e>=3e3&&e<=4999}function _(e){return e===i.CLOSE||e===i.PING||e===i.PONG}function v(e){return e===i.CONTINUATION}function y(e){return e===i.TEXT||e===i.BINARY}function b(e){return y(e)||v(e)||_(e)}function x(e){let t={position:0},n=new Map;for(;t.position<e.length;){let[r,i=``]=s(`;`,e,t).split(`=`,2);n.set(o(r,!0,!1),o(i,!1,!0)),t.position++}return n}function S(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<48||n>57)return!1}let t=Number.parseInt(e,10);return t>=8&&t<=15}function C(e,t){let n;try{n=new URL(e,t)}catch(e){throw new DOMException(e,`SyntaxError`)}if(n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`),n.protocol!==`ws:`&&n.protocol!==`wss:`)throw new DOMException(`expected a ws: or wss: url`,`SyntaxError`);if(n.hash.length||n.href.endsWith(`#`))throw new DOMException(`hash`,`SyntaxError`);return n}function w(e,t){if(e!==null&&e!==1e3&&(e<3e3||e>4999))throw new DOMException(`invalid code`,`InvalidAccessError`);if(t!==null){let e=Buffer.byteLength(t);if(e>123)throw new DOMException(`Reason must be less than 123 bytes; received ${e}`,`SyntaxError`)}}n.exports={isConnecting:c,isEstablished:l,isClosing:u,isClosed:d,fireEvent:f,isValidSubprotocol:h,isValidStatusCode:g,websocketMessageReceived:p,utf8Decode:(()=>{if(typeof process.versions.icu==`string`){let e=new TextDecoder(`utf-8`,{fatal:!0});return e.decode.bind(e)}return function(e){if(a(e))return e.toString(`utf-8`);throw TypeError(`Invalid utf-8 received.`)}})(),isControlFrame:_,isContinuationFrame:v,isTextBinaryFrame:y,isValidOpcode:b,parseExtensions:x,isValidClientWindowBits:S,toArrayBuffer:m,getURLRecord:C,validateCloseCodeAndReason:w}})),Wr=t(((t,n)=>{var{runtimeFeatures:r}=fn(),{maxUnsigned16Bit:i,opcodes:a}=Hr(),o=8192,s=null,c=o,l=r.has(`crypto`)?e(`node:crypto`).randomFillSync:null;function u(){return c===o&&(c=0,l(s??=Buffer.allocUnsafeSlow(o),0,o)),[s[c++],s[c++],s[c++],s[c++]]}n.exports={WebsocketFrameSend:class{constructor(e){this.frameData=e}createFrame(e){let t=this.frameData,n=u(),r=t?.byteLength??0,a=r,o=6;r>i?(o+=8,a=127):r>125&&(o+=2,a=126);let s=Buffer.allocUnsafe(r+o);s[0]=s[1]=0,s[0]|=128,s[0]=(s[0]&240)+e,s[o-4]=n[0],s[o-3]=n[1],s[o-2]=n[2],s[o-1]=n[3],s[1]=a,a===126?s.writeUInt16BE(r,2):a===127&&(s[2]=s[3]=0,s.writeUIntBE(r,4,6)),s[1]|=128;for(let e=0;e<r;++e)s[o+e]=t[e]^n[e&3];return s}static createFastTextFrame(e){let t=u(),n=e.length;for(let r=0;r<n;++r)e[r]^=t[r&3];let r=n,o=6;n>i?(o+=8,r=127):n>125&&(o+=2,r=126);let s=Buffer.allocUnsafeSlow(o);return s[0]=128|a.TEXT,s[1]=r|128,s[o-4]=t[0],s[o-3]=t[1],s[o-2]=t[2],s[o-1]=t[3],r===126?s.writeUInt16BE(n,2):r===127&&(s[2]=s[3]=0,s.writeUIntBE(n,4,6)),[s,e]}},generateMask:u}})),Gr=t(((t,n)=>{var{uid:r,states:i,sentCloseFrameState:a,emptyBuffer:o,opcodes:s}=Hr(),{parseExtensions:c,isClosed:l,isClosing:u,isEstablished:d,isConnecting:f,validateCloseCodeAndReason:p}=Ur(),{makeRequest:m}=jr(),{fetching:h}=Nr(),{Headers:g,getHeadersList:_}=kr(),{getDecodeSplit:v}=dn(),{WebsocketFrameSend:y}=Wr(),b=e(`node:assert`),{runtimeFeatures:x}=fn(),S=x.has(`crypto`)?e(`node:crypto`):null,C=!1;function w(e,t,n,i,a){let o=e;o.protocol=e.protocol===`ws:`?`http:`:`https:`;let s=m({urlList:[o],client:n,serviceWorkers:`none`,referrer:`no-referrer`,mode:`websocket`,credentials:`include`,cache:`no-store`,redirect:`error`,useURLCredentials:!0});a.headers&&(s.headersList=_(new g(a.headers)));let l=S.randomBytes(16).toString(`base64`);s.headersList.append(`sec-websocket-key`,l,!0),s.headersList.append(`sec-websocket-version`,`13`,!0);for(let e of t)s.headersList.append(`sec-websocket-protocol`,e,!0);return s.headersList.append(`sec-websocket-extensions`,`permessage-deflate; client_max_window_bits`,!0),h({request:s,useParallelQueue:!0,dispatcher:a.dispatcher,processResponse(e){if(e.type===`error`||e.status!==101){if(e.socket?.session==null){E(i,e,1002,`Received network error or non-101 status code.`,e.error);return}if(e.status!==200){E(i,e,1002,`Received network error or non-200 status code.`,e.error);return}}if(C===!1&&e.socket?.session!=null&&(process.emitWarning(`WebSocket over HTTP2 is experimental, and subject to change.`,`ExperimentalWarning`),C=!0),t.length!==0&&!e.headersList.get(`Sec-WebSocket-Protocol`)){E(i,e,1002,`Server did not respond with sent protocols.`);return}if(e.socket.session==null&&e.headersList.get(`Upgrade`)?.toLowerCase()!==`websocket`){E(i,e,1002,`Server did not set Upgrade header to "websocket".`);return}if(e.socket.session==null&&e.headersList.get(`Connection`)?.toLowerCase()!==`upgrade`){E(i,e,1002,`Server did not set Connection header to "upgrade".`);return}if(e.socket.session==null&&e.headersList.get(`Sec-WebSocket-Accept`)!==S.hash(`sha1`,l+r,`base64`)){E(i,e,1002,`Incorrect hash received in Sec-WebSocket-Accept header.`);return}let n=e.headersList.get(`Sec-WebSocket-Extensions`),a;if(n!==null&&(a=c(n),!a.has(`permessage-deflate`))){E(i,e,1002,`Sec-WebSocket-Extensions header does not match.`);return}let o=e.headersList.get(`Sec-WebSocket-Protocol`);if(o!==null){let t=v(`sec-websocket-protocol`,s.headersList);if(t===null||!t.includes(o)){E(i,e,1002,`Protocol was not set in the opening handshake.`);return}}e.socket.session!=null&&(e.socket.allowHalfOpen=!1),e.socket.on(`data`,i.onSocketData),e.socket.on(`close`,i.onSocketClose),e.socket.on(`error`,i.onSocketError),i.wasEverConnected=!0,i.onConnectionEstablished(e,a)}})}function T(e,t,n,r=!1){if(t??=null,n??=``,r&&p(t,n),!(l(e.readyState)||u(e.readyState))){if(!d(e.readyState))D(e),e.readyState=i.CLOSING;else if(!e.closeState.has(a.SENT)&&!e.closeState.has(a.RECEIVED)){let r=new y;n.length!==0&&t===null&&(t=1e3),b(t===null||Number.isInteger(t)),t===null&&n.length===0?r.frameData=o:t!==null&&n===null?(r.frameData=Buffer.allocUnsafe(2),r.frameData.writeUInt16BE(t,0)):t!==null&&n!==null?(r.frameData=Buffer.allocUnsafe(2+Buffer.byteLength(n)),r.frameData.writeUInt16BE(t,0),r.frameData.write(n,2,`utf-8`)):r.frameData=o,e.socket.write(r.createFrame(s.CLOSE)),e.closeState.add(a.SENT),e.readyState=i.CLOSING}else e.readyState=i.CLOSING}}function E(e,t,n,r,i){t.socket?.session!=null&&!t.socket.destroyed&&t.socket.destroy(),D(e,n,r,i)}function D(e,t,n,r){d(e.readyState)&&T(e,t,n,!1),e.controller.abort(),f(e.readyState)?e.onSocketClose():e.socket?.destroyed===!1&&e.socket.destroy()}n.exports={establishWebSocketConnection:w,failWebsocketConnection:D,closeWebSocketConnection:T}})),Kr=t(((t,n)=>{var{createInflateRaw:r,Z_DEFAULT_WINDOWBITS:i}=e(`node:zlib`),{isValidClientWindowBits:a}=Ur(),{MessageSizeExceededError:o}=Q(),s=Buffer.from([0,0,255,255]),c=Symbol(`kBuffer`),l=Symbol(`kLength`);n.exports={PerMessageDeflate:class{#e;#t={};#n=0;constructor(e,t){this.#t.serverNoContextTakeover=e.has(`server_no_context_takeover`),this.#t.serverMaxWindowBits=e.get(`server_max_window_bits`),this.#n=t.maxPayloadSize}decompress(e,t,n){if(!this.#e){let e=i;if(this.#t.serverMaxWindowBits){if(!a(this.#t.serverMaxWindowBits)){n(Error(`Invalid server_max_window_bits`));return}e=Number.parseInt(this.#t.serverMaxWindowBits)}try{this.#e=r({windowBits:e})}catch(e){n(e);return}this.#e[c]=[],this.#e[l]=0,this.#e.on(`data`,e=>{this.#e[l]+=e.length,this.#n>0&&this.#e[l]>this.#n?(n(new o),this.#e.removeAllListeners(),this.#e.destroy(),this.#e=null):this.#e[c].push(e)}),this.#e.on(`error`,e=>{this.#e=null,n(e)})}this.#e.write(e),t&&this.#e.write(s),this.#e.flush(()=>{if(!this.#e)return;let e=Buffer.concat(this.#e[c],this.#e[l]);this.#e[c].length=0,this.#e[l]=0,n(null,e)})}}}})),qr=t(((t,n)=>{var{Writable:r}=e(`node:stream`),i=e(`node:assert`),{parserStates:a,opcodes:o,states:s,emptyBuffer:c,sentCloseFrameState:l}=Hr(),{isValidStatusCode:u,isValidOpcode:d,websocketMessageReceived:f,utf8Decode:p,isControlFrame:m,isTextBinaryFrame:h,isContinuationFrame:g}=Ur(),{failWebsocketConnection:_}=Gr(),{WebsocketFrameSend:v}=Wr(),{PerMessageDeflate:y}=Kr(),{MessageSizeExceededError:b}=Q(),{defaultWebSocketMaxFragments:x,defaultWebSocketMaxPayloadSize:S}=en();n.exports={ByteParser:class extends r{#e=[];#t=0;#n=0;#r=!1;#i=a.INFO;#a={};#o=[];#s;#c;#l;#u;constructor(e,t,n={}){super(),this.#c=e,this.#s=t??new Map,this.#l=n.maxFragments??x,this.#u=n.maxPayloadSize??S,this.#s.has(`permessage-deflate`)&&this.#s.set(`permessage-deflate`,new y(t,{maxPayloadSize:this.#u}))}_write(e,t,n){this.#e.push(e),this.#n+=e.length,this.#r=!0,this.run(n)}#d(){return this.#u>0&&!m(this.#a.opcode)&&this.#a.payloadLength+this.#t>this.#u?(_(this.#c,1009,`Payload size exceeds maximum allowed size`),!1):!0}run(e){for(;this.#r;)if(this.#i===a.INFO){if(this.#n<2)return e();let t=this.consume(2),n=!!(t[0]&128),r=t[0]&15,i=(t[1]&128)==128,s=!n&&r!==o.CONTINUATION,c=t[1]&127,l=t[0]&64,u=t[0]&32,f=t[0]&16;if(!d(r))return _(this.#c,1002,`Invalid opcode received`),e();if(i)return _(this.#c,1002,`Frame cannot be masked`),e();if(l!==0&&!this.#s.has(`permessage-deflate`)){_(this.#c,1002,`Expected RSV1 to be clear.`);return}if(u!==0||f!==0){_(this.#c,1002,`RSV1, RSV2, RSV3 must be clear`);return}if(s&&!h(r)){_(this.#c,1002,`Invalid frame type was fragmented.`);return}if(h(r)&&this.#o.length>0){_(this.#c,1002,`Expected continuation frame`);return}if(this.#a.fragmented&&s){_(this.#c,1002,`Fragmented frame exceeded 125 bytes.`);return}if((c>125||s)&&m(r)){_(this.#c,1002,`Control frame either too large or fragmented`);return}if(g(r)&&this.#o.length===0&&!this.#a.compressed){_(this.#c,1002,`Unexpected continuation frame`);return}if(c<=125){if(this.#a.payloadLength=c,this.#i=a.READ_DATA,!this.#d())return}else c===126?this.#i=a.PAYLOADLENGTH_16:c===127&&(this.#i=a.PAYLOADLENGTH_64);h(r)&&(this.#a.binaryType=r,this.#a.compressed=l!==0),this.#a.opcode=r,this.#a.masked=i,this.#a.fin=n,this.#a.fragmented=s}else if(this.#i===a.PAYLOADLENGTH_16){if(this.#n<2)return e();let t=this.consume(2);if(this.#a.payloadLength=t.readUInt16BE(0),this.#i=a.READ_DATA,!this.#d())return}else if(this.#i===a.PAYLOADLENGTH_64){if(this.#n<8)return e();let t=this.consume(8),n=t.readUInt32BE(0),r=t.readUInt32BE(4);if(n!==0||r>2**31-1){_(this.#c,1009,`Received payload length > 2^31 bytes.`);return}if(this.#a.payloadLength=r,this.#i=a.READ_DATA,!this.#d())return}else if(this.#i===a.READ_DATA){if(this.#n<this.#a.payloadLength)return e();let t=this.consume(this.#a.payloadLength);if(m(this.#a.opcode)){if(this.#r=this.parseControlFrame(t),this.#i=a.INFO,this.#r&&this.#c.socket.writableNeedDrain){this.#r=!1,this.#c.socket.once(`drain`,()=>{this.destroyed||(this.#r=!0,this.run(e))});return}}else if(this.#a.compressed){this.#s.get(`permessage-deflate`).decompress(t,this.#a.fin,(t,n)=>{if(t){let e=t instanceof b?1009:1007;_(this.#c,e,t.message)}else this.writeFragments(n)&&(this.#u>0&&this.#t>this.#u?_(this.#c,1009,new b().message):this.#a.fin?(f(this.#c,this.#a.binaryType,this.consumeFragments()),this.#r=!0,this.#i=a.INFO,this.run(e)):(this.#i=a.INFO,this.#r=!0,this.run(e)))},this.#t),this.#r=!1;break}else{if(!this.writeFragments(t))return;!this.#a.fragmented&&this.#a.fin&&f(this.#c,this.#a.binaryType,this.consumeFragments()),this.#i=a.INFO}}}consume(e){if(e>this.#n)throw Error(`Called consume() before buffers satiated.`);if(e===0)return c;this.#n-=e;let t=this.#e[0];if(t.length>e)return this.#e[0]=t.subarray(e,t.length),t.subarray(0,e);if(t.length===e)return this.#e.shift();{let t=0,n=Buffer.allocUnsafeSlow(e);for(;t!==e;){let r=this.#e[0],i=r.length;if(i+t===e){n.set(this.#e.shift(),t);break}if(i+t>e){n.set(r.subarray(0,e-t),t),this.#e[0]=r.subarray(e-t);break}n.set(this.#e.shift(),t),t+=i}return n}}writeFragments(e){return this.#l>0&&this.#o.length===this.#l?(_(this.#c,1008,`Too many message fragments`),!1):(this.#t+=e.length,this.#o.push(e),!0)}consumeFragments(){let e=this.#o;if(this.#a.compressed=!1,e.length===1)return this.#t=0,e.shift();let t=0,n=Buffer.allocUnsafeSlow(this.#t);for(let r=0;r<e.length;++r){let i=e[r];n.set(i,t),t+=i.length}return this.#o=[],this.#t=0,n}parseCloseBody(e){i(e.length!==1);let t;if(e.length>=2&&(t=e.readUInt16BE(0)),t!==void 0&&!u(t))return{code:1002,reason:`Invalid status code`,error:!0};let n=e.subarray(2);n[0]===239&&n[1]===187&&n[2]===191&&(n=n.subarray(3));try{n=p(n)}catch{return{code:1007,reason:`Invalid UTF-8`,error:!0}}return{code:t,reason:n,error:!1}}parseControlFrame(e){let{opcode:t,payloadLength:n}=this.#a;if(t===o.CLOSE){if(n===1)return _(this.#c,1002,`Received close frame with a 1-byte body.`),!1;if(this.#a.closeInfo=this.parseCloseBody(e),this.#a.closeInfo.error){let{code:e,reason:t}=this.#a.closeInfo;return _(this.#c,e,t),!1}if(!this.#c.closeState.has(l.SENT)&&!this.#c.closeState.has(l.RECEIVED)){let e=c;this.#a.closeInfo.code&&(e=Buffer.allocUnsafe(2),e.writeUInt16BE(this.#a.closeInfo.code,0));let t=new v(e);this.#c.socket.write(t.createFrame(o.CLOSE)),this.#c.closeState.add(l.SENT)}return this.#c.readyState=s.CLOSING,this.#c.closeState.add(l.RECEIVED),!1}if(t===o.PING){if(!this.#c.closeState.has(l.RECEIVED)){let t=new v(e);this.#c.socket.write(t.createFrame(o.PONG)),this.#c.onPing(e)}}else t===o.PONG&&this.#c.onPong(e);return!0}get closingInfo(){return this.#a.closeInfo}}}})),Jr=t(((e,t)=>{var{WebsocketFrameSend:n}=Wr(),{opcodes:r,sendHints:i}=Hr(),a=An(),o=class{#e=new a;#t=!1;#n;constructor(e){this.#n=e}add(e,t,r){if(r!==i.blob){if(this.#t){let n={promise:null,callback:t,frame:s(e,r)};this.#e.push(n)}else if(r===i.text){let{0:r,1:i}=n.createFastTextFrame(e);this.#n.cork(),this.#n.write(r),this.#n.write(i,t),this.#n.uncork()}else this.#n.write(s(e,r),t);return}let a={promise:e.arrayBuffer().then(e=>{a.promise=null,a.frame=s(e,r)}),callback:t,frame:null};this.#e.push(a),this.#t||this.#r()}async#r(){this.#t=!0;let e=this.#e;for(;!e.isEmpty();){let t=e.shift();t.promise!==null&&await t.promise,this.#n.write(t.frame,t.callback),t.callback=t.frame=null}this.#t=!1}};function s(e,t){return new n(c(e,t)).createFrame(t===i.text?r.TEXT:r.BINARY)}function c(e,t){switch(t){case i.text:case i.typedArray:return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);case i.arrayBuffer:case i.blob:return new Uint8Array(e)}}t.exports={SendQueue:o}})),Yr=t(((t,n)=>{var{isArrayBuffer:r}=e(`node:util/types`),{webidl:i}=un(),{URLSerializer:a}=ln(),{environmentSettingsObject:o}=dn(),{staticPropertyDescriptors:s,states:c,sentCloseFrameState:l,sendHints:u,opcodes:d}=Hr(),{isConnecting:f,isEstablished:p,isClosing:m,isClosed:h,isValidSubprotocol:g,fireEvent:_,utf8Decode:v,toArrayBuffer:y,getURLRecord:b}=Ur(),{establishWebSocketConnection:x,closeWebSocketConnection:S,failWebsocketConnection:C}=Gr(),{ByteParser:w}=qr(),{kEnumerableProperty:T}=$(),{getGlobalDispatcher:E}=dr(),{ErrorEvent:D,CloseEvent:O,createFastMessageEvent:k}=Vr(),{SendQueue:A}=Jr(),{WebsocketFrameSend:j}=Wr(),{channels:M}=rn(),N=Symbol.for(`nodejs.ref`),P=Symbol.for(`nodejs.unref`),F;function I(e){return typeof e?.address==`function`?e.address():typeof e?.session?.socket?.address==`function`?e.session.socket.address():null}var L=class e extends EventTarget{#e={open:null,error:null,close:null,message:null};#t=0;#n=``;#r=``;#i=!0;#a;#o={onConnectionEstablished:(e,t)=>this.#u(e,t),onMessage:(e,t)=>this.#d(e,t),onParserError:e=>C(this.#o,null,e.message),onParserDrain:()=>this.#f(),onSocketData:e=>{this.#l.write(e)||this.#o.socket.pause()},onSocketError:e=>{this.#o.readyState=c.CLOSING,M.socketError.hasSubscribers&&M.socketError.publish(e),this.#o.socket.destroy()},onSocketClose:()=>this.#p(),onPing:e=>{M.ping.hasSubscribers&&M.ping.publish({payload:e,websocket:this})},onPong:e=>{M.pong.hasSubscribers&&M.pong.publish({payload:e,websocket:this})},readyState:c.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:!1};#s;#c;#l;constructor(t,n=[]){super(),i.util.markAsUncloneable(this);let r=`WebSocket constructor`;i.argumentLengthCheck(arguments,1,r);let a=i.converters[`DOMString or sequence<DOMString> or WebSocketInit`](n,r,`options`);t=i.converters.USVString(t),n=a.protocols;let s=o.settingsObject.baseUrl,c=b(t,s);if(typeof n==`string`&&(n=[n]),n.length!==new Set(n.map(e=>e.toLowerCase())).size||n.length>0&&!n.every(e=>g(e)))throw new DOMException(`Invalid Sec-WebSocket-Protocol value`,`SyntaxError`);this.#s=new URL(c.href);let l=o.settingsObject;this.#o.controller=x(c,n,l,this.#o,a),this.#o.readyState=e.CONNECTING,this.#c=`blob`}[N](){this.#i=!0,this.#o.socket?.ref?.()}[P](){this.#i=!1,this.#o.socket?.unref?.()}close(e=void 0,t=void 0){i.brandCheck(this,i.is.WebSocket),e!==void 0&&(e=i.converters[`unsigned short`](e,`WebSocket.close`,`code`,i.attributes.Clamp)),t!==void 0&&(t=i.converters.USVString(t)),e??=null,t??=``,S(this.#o,e,t,!0)}send(e){i.brandCheck(this,i.is.WebSocket);let t=`WebSocket.send`;if(i.argumentLengthCheck(arguments,1,t),e=i.converters.WebSocketSendData(e,t,`data`),f(this.#o.readyState))throw new DOMException(`Sent before connected.`,`InvalidStateError`);if(p(this.#o.readyState)&&!m(this.#o.readyState)){if(typeof e==`string`){let t=Buffer.from(e);this.#t+=t.byteLength,this.#a.add(t,()=>{this.#t-=t.byteLength},u.text)}else r(e)?(this.#t+=e.byteLength,this.#a.add(e,()=>{this.#t-=e.byteLength},u.arrayBuffer)):ArrayBuffer.isView(e)?(this.#t+=e.byteLength,this.#a.add(e,()=>{this.#t-=e.byteLength},u.typedArray)):i.is.Blob(e)&&(this.#t+=e.size,this.#a.add(e,()=>{this.#t-=e.size},u.blob))}}get readyState(){return i.brandCheck(this,i.is.WebSocket),this.#o.readyState}get bufferedAmount(){return i.brandCheck(this,i.is.WebSocket),this.#t}get url(){return i.brandCheck(this,i.is.WebSocket),a(this.#s)}get extensions(){return i.brandCheck(this,i.is.WebSocket),this.#r}get protocol(){return i.brandCheck(this,i.is.WebSocket),this.#n}get onopen(){return i.brandCheck(this,i.is.WebSocket),this.#e.open}set onopen(e){i.brandCheck(this,i.is.WebSocket),this.#e.open&&this.removeEventListener(`open`,this.#e.open);let t=i.converters.EventHandlerNonNull(e);t===null?this.#e.open=null:(this.addEventListener(`open`,t),this.#e.open=e)}get onerror(){return i.brandCheck(this,i.is.WebSocket),this.#e.error}set onerror(e){i.brandCheck(this,i.is.WebSocket),this.#e.error&&this.removeEventListener(`error`,this.#e.error);let t=i.converters.EventHandlerNonNull(e);t===null?this.#e.error=null:(this.addEventListener(`error`,t),this.#e.error=e)}get onclose(){return i.brandCheck(this,i.is.WebSocket),this.#e.close}set onclose(e){i.brandCheck(this,i.is.WebSocket),this.#e.close&&this.removeEventListener(`close`,this.#e.close);let t=i.converters.EventHandlerNonNull(e);t===null?this.#e.close=null:(this.addEventListener(`close`,t),this.#e.close=e)}get onmessage(){return i.brandCheck(this,i.is.WebSocket),this.#e.message}set onmessage(e){i.brandCheck(this,i.is.WebSocket),this.#e.message&&this.removeEventListener(`message`,this.#e.message);let t=i.converters.EventHandlerNonNull(e);t===null?this.#e.message=null:(this.addEventListener(`message`,t),this.#e.message=e)}get binaryType(){return i.brandCheck(this,i.is.WebSocket),this.#c}set binaryType(e){i.brandCheck(this,i.is.WebSocket),this.#c=e!==`blob`&&e!==`arraybuffer`?`blob`:e}#u(e,t){this.#o.socket=e.socket,this.#i||this.#o.socket.unref?.();let n=this.#o.controller.dispatcher?.webSocketOptions?.maxFragments,r=this.#o.controller.dispatcher?.webSocketOptions?.maxPayloadSize,i=new w(this.#o,t,{maxFragments:n,maxPayloadSize:r});i.on(`drain`,()=>this.#o.onParserDrain()),i.on(`error`,e=>this.#o.onParserError(e)),this.#l=i,this.#a=new A(e.socket),this.#o.readyState=c.OPEN;let a=e.headersList.get(`sec-websocket-extensions`);a!==null&&(this.#r=a);let o=e.headersList.get(`sec-websocket-protocol`);if(o!==null&&(this.#n=o),_(`open`,this),M.open.hasSubscribers){let t=e.headersList.entries;M.open.publish({address:I(e.socket),protocol:this.#n,extensions:this.#r,websocket:this,handshakeResponse:{status:e.status,statusText:e.statusText,headers:t}})}}#d(e,t){if(this.#o.readyState!==c.OPEN)return;let n;if(e===d.TEXT)try{n=v(t)}catch{C(this.#o,1007,`Received invalid UTF-8 in text frame.`);return}else e===d.BINARY&&(n=this.#c===`blob`?new Blob([t]):y(t));_(`message`,this,k,{origin:this.#s.origin,data:n})}#f(){this.#o.socket.resume()}#p(){let e=this.#o.closeState.has(l.SENT)&&this.#o.closeState.has(l.RECEIVED),t=1005,n=``,r=this.#l?.closingInfo;r&&!r.error&&(t=r.code??1005,n=r.reason),this.#o.readyState=c.CLOSED,this.#o.closeState.has(l.RECEIVED)||(t=1006,_(`error`,this,(e,t)=>new D(e,t),{error:TypeError(n)})),_(`close`,this,(e,t)=>new O(e,t),{wasClean:e,code:t,reason:n}),M.close.hasSubscribers&&M.close.publish({websocket:this,code:t,reason:n})}static{F=(e,t)=>{if(Buffer.isBuffer(t)){if(t.length>125)throw TypeError(`A PING frame cannot have a body larger than 125 bytes.`)}else if(t!==void 0)throw TypeError(`Expected buffer payload`);let n=e.#o.readyState;if(p(n)&&!m(n)&&!h(n)){let n=new j(t);e.#o.socket.write(n.createFrame(d.PING))}},i.is.WebSocket=e=>typeof e==`object`&&!!e&&#o in e}};L.CONNECTING=L.prototype.CONNECTING=c.CONNECTING,L.OPEN=L.prototype.OPEN=c.OPEN,L.CLOSING=L.prototype.CLOSING=c.CLOSING,L.CLOSED=L.prototype.CLOSED=c.CLOSED,Object.defineProperties(L.prototype,{CONNECTING:s,OPEN:s,CLOSING:s,CLOSED:s,url:T,readyState:T,bufferedAmount:T,onopen:T,onerror:T,onclose:T,close:T,onmessage:T,binaryType:T,send:T,extensions:T,protocol:T,[Symbol.toStringTag]:{value:`WebSocket`,writable:!1,enumerable:!1,configurable:!0}}),Object.defineProperties(L,{CONNECTING:s,OPEN:s,CLOSING:s,CLOSED:s}),i.converters[`sequence<DOMString>`]=i.sequenceConverter(i.converters.DOMString),i.converters[`DOMString or sequence<DOMString>`]=function(e,t,n){return i.util.Type(e)===i.util.Types.OBJECT&&Symbol.iterator in e?i.converters[`sequence<DOMString>`](e):i.converters.DOMString(e,t,n)},i.converters.WebSocketInit=i.dictionaryConverter([{key:`protocols`,converter:i.converters[`DOMString or sequence<DOMString>`],defaultValue:()=>[]},{key:`dispatcher`,converter:i.converters.any,defaultValue:()=>E()},{key:`headers`,converter:i.nullableConverter(i.converters.HeadersInit)}]),i.converters[`DOMString or sequence<DOMString> or WebSocketInit`]=function(e){return i.util.Type(e)===i.util.Types.OBJECT&&!(Symbol.iterator in e)?i.converters.WebSocketInit(e):{protocols:i.converters[`DOMString or sequence<DOMString>`](e)}},i.converters.WebSocketSendData=function(e){return i.util.Type(e)===i.util.Types.OBJECT&&(i.is.Blob(e)||i.is.BufferSource(e))?e:i.converters.USVString(e)},n.exports={WebSocket:L,ping:F}})),Xr=t(((e,t)=>{var{webidl:n}=un(),{validateCloseCodeAndReason:r}=Ur(),{kConstruct:i}=Z(),{kEnumerableProperty:a}=$();function o(){class e extends DOMException{get reason(){return``}}return new e().reason===void 0?new Proxy(DOMException,{construct(e,t,n){let r=Reflect.construct(e,t,e);return Object.setPrototypeOf(r,n.prototype),r}}):DOMException}var s,c=class e extends o(){#e;#t;constructor(e=``,t=void 0){if(e=n.converters.DOMString(e,`WebSocketError`,`message`),super(e,`WebSocketError`),t===i)return;t!==null&&(t=n.converters.WebSocketCloseInfo(t));let a=t.closeCode??null,o=t.reason??``;r(a,o),o.length!==0&&a===null&&(a=1e3),this.#e=a,this.#t=o}get closeCode(){return this.#e}get reason(){return this.#t}static{s=(t,n,r)=>{let a=new e(t,i);return a.#e=n,a.#t=r,a},n.is.WebSocketError=e=>typeof e==`object`&&!!e&&#t in e}};Object.defineProperties(c.prototype,{closeCode:a,reason:a,[Symbol.toStringTag]:{value:`WebSocketError`,writable:!1,enumerable:!1,configurable:!0}}),t.exports={WebSocketError:c,createUnvalidatedWebSocketError:s}})),Zr=t(((t,n)=>{var{addAbortListener:r}=e(`node:events`),{environmentSettingsObject:i,readableStreamClose:a}=dn(),{states:o,opcodes:s,sentCloseFrameState:c}=Hr(),{webidl:l}=un(),{getURLRecord:u,isValidSubprotocol:d,isEstablished:f,utf8Decode:p}=Ur(),{establishWebSocketConnection:m,failWebsocketConnection:h,closeWebSocketConnection:g}=Gr(),{channels:_}=rn(),{WebsocketFrameSend:v}=Wr(),{ByteParser:y}=qr(),{WebSocketError:b,createUnvalidatedWebSocketError:x}=Xr(),{kEnumerableProperty:S}=$(),{utf8DecodeBytes:C}=sn(),w=!1,T=class{#e;#t;#n;#r;#i;#a;#o=!1;#s={onConnectionEstablished:(e,t)=>this.#u(e,t),onMessage:(e,t)=>this.#d(e,t),onParserError:e=>h(this.#s,null,e.message),onParserDrain:()=>this.#s.socket.resume(),onSocketData:e=>{this.#c.write(e)||this.#s.socket.pause()},onSocketError:e=>{this.#s.readyState=o.CLOSING,_.socketError.hasSubscribers&&_.socketError.publish(e),this.#s.socket.destroy()},onSocketClose:()=>queueMicrotask(()=>this.#f()),onPing:()=>{},onPong:()=>{},readyState:o.CONNECTING,socket:null,closeState:new Set,controller:null,wasEverConnected:!1};#c;constructor(e,t=void 0){w||=(process.emitWarning(`WebSocketStream is experimental! Expect it to change at any time.`,{code:`UNDICI-WSS`}),!0),l.argumentLengthCheck(arguments,1,`WebSocket`),e=l.converters.USVString(e),t!==null&&(t=l.converters.WebSocketStreamOptions(t));let n=i.settingsObject.baseUrl,a=u(e,n),s=t.protocols;if(s.length!==new Set(s.map(e=>e.toLowerCase())).size||s.length>0&&!s.every(e=>d(e)))throw new DOMException(`Invalid Sec-WebSocket-Protocol value`,`SyntaxError`);if(this.#e=a.toString(),this.#t=Promise.withResolvers(),this.#n=Promise.withResolvers(),t.signal!=null){let e=t.signal;if(e.aborted){this.#t.reject(e.reason),this.#n.reject(e.reason);return}r(e,()=>{f(this.#s.readyState)||(h(this.#s),this.#s.readyState=o.CLOSING,this.#t.reject(e.reason),this.#n.reject(e.reason),this.#o=!0)})}let c=i.settingsObject;this.#s.controller=m(a,s,c,this.#s,t)}get url(){return this.#e.toString()}get opened(){return this.#t.promise}get closed(){return this.#n.promise}close(e=void 0){e!==null&&(e=l.converters.WebSocketCloseInfo(e));let t=e.closeCode??null,n=e.reason;g(this.#s,t,n,!0)}#l(e){e=l.converters.WebSocketStreamWrite(e);let t=Promise.withResolvers(),n=null,r=null;if(l.is.BufferSource(e))n=new Uint8Array(ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e.slice()),r=s.BINARY;else{let i;try{i=l.converters.DOMString(e)}catch(e){return t.reject(e),t.promise}n=new TextEncoder().encode(i),r=s.TEXT}if(!this.#s.closeState.has(c.SENT)&&!this.#s.closeState.has(c.RECEIVED)){let e=new v(n);this.#s.socket.write(e.createFrame(r),()=>{t.resolve(void 0)})}else t.resolve(void 0);return t.promise}#u(e,t){this.#s.socket=e.socket;let n=this.#s.controller.dispatcher?.webSocketOptions?.maxFragments,r=this.#s.controller.dispatcher?.webSocketOptions?.maxPayloadSize,i=new y(this.#s,t,{maxFragments:n,maxPayloadSize:r});i.on(`drain`,()=>this.#s.onParserDrain()),i.on(`error`,e=>this.#s.onParserError(e)),this.#c=i,this.#s.readyState=o.OPEN;let a=e.headersList.get(`sec-websocket-extensions`)??``,s=e.headersList.get(`sec-websocket-protocol`)??``,c=new ReadableStream({start:e=>{this.#i=e},pull:()=>this.#m(),cancel:e=>this.#h(e)}),l=new WritableStream({start:e=>{this.#a=e},write:e=>this.#l(e),close:()=>g(this.#s,null,null),abort:e=>this.#p(e)});this.#r=c,this.#t.resolve({extensions:a,protocol:s,readable:c,writable:l})}#d(e,t){if(this.#s.readyState!==o.OPEN)return;let n;if(e===s.TEXT)try{n=p(t)}catch{h(this.#s,1007,`Received invalid UTF-8 in text frame.`);return}else e===s.BINARY&&(n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength));this.#i.enqueue(n),this.#i.desiredSize<=0&&this.#s.socket.pause()}#f(){let e=this.#s.closeState.has(c.SENT)&&this.#s.closeState.has(c.RECEIVED);if(this.#s.readyState=o.CLOSED,this.#o)return;this.#s.wasEverConnected||this.#t.reject(new b(`Socket never opened`));let t=this.#c?.closingInfo,n=t?.code??1005;this.#s.closeState.has(c.RECEIVED)||(n=1006);let r=t?.reason==null?``:C(Buffer.from(t.reason));if(e)a(this.#i),this.#a.error(new DOMException(`A closed WebSocketStream cannot be written to`,`InvalidStateError`)),this.#n.resolve({closeCode:n,reason:r});else{let e=x(`unclean close`,n,r);this.#i?.error(e),this.#a?.error(e),this.#n.reject(e)}}#p(e){let t=null,n=``;l.is.WebSocketError(e)&&(t=e.closeCode,n=e.reason),g(this.#s,t,n)}#m(){this.#s.socket.resume()}#h(e){this.#p(e)}};Object.defineProperties(T.prototype,{url:S,opened:S,closed:S,close:S,[Symbol.toStringTag]:{value:`WebSocketStream`,writable:!1,enumerable:!1,configurable:!0}}),l.converters.WebSocketStreamOptions=l.dictionaryConverter([{key:`protocols`,converter:l.sequenceConverter(l.converters.USVString),defaultValue:()=>[]},{key:`signal`,converter:l.nullableConverter(l.converters.AbortSignal),defaultValue:()=>null}]),l.converters.WebSocketCloseInfo=l.dictionaryConverter([{key:`closeCode`,converter:e=>l.converters[`unsigned short`](e,l.attributes.EnforceRange)},{key:`reason`,converter:l.converters.USVString,defaultValue:()=>``}]),l.converters.WebSocketStreamWrite=function(e){return typeof e==`string`?l.converters.USVString(e):l.converters.BufferSource(e)},n.exports={WebSocketStream:T}})),Qr=t(((e,t)=>{var{makeRequest:n}=jr();function r(e){return e.indexOf(`\0`)===-1}function i(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<48||e.charCodeAt(t)>57)return!1;return!0}function a(e,t,r,i){let a=r===`no cors`?`no-cors`:`cors`;i&&a===`no-cors`&&(a=`same-origin`);let o=`include`;return r===`anonymous`&&(o=`same-origin`),n({urlList:[e],destination:t,mode:a,credentials:o,useURLCredentials:!0})}t.exports={isValidLastEventId:r,isASCIINumber:i,createPotentialCORSRequest:a}})),$r=t(((t,n)=>{var r=e(`node:buffer`),{Transform:i}=e(`node:stream`),{isASCIINumber:a,isValidLastEventId:o}=Qr(),s=[239,187,191],c=10,l=13,u=58,d=32,f=r.kStringMaxLength,p=Buffer.from(`data`),m=Buffer.from(`event`),h=Buffer.from(`id`),g=Buffer.from(`retry`),_=1024,v=131072,y=128;function b(e,t){if(t>=e.length)return!1;for(let n=t;n<e.length;n++)if(e[n]<48||e[n]>57)return!1;return!0}function x(e,t){for(let n=t;n<e.length;n++)if(e[n]===0)return!1;return!0}function S(e,t,n){if(t!==n.length)return!1;for(let r=0;r<t;r++)if(e[r]!==n[r])return!1;return!0}function C(){let e=Error(`EventSource message size exceeded`);return e.aborted=!1,e}n.exports={EventSourceStream:class extends i{state;checkBOM=!0;crlfCheck=!1;eventEndCheck=!1;chunks=[];chunkIndex=0;pos=0;lineChunkIndex=0;linePos=0;lineLength=0;eventSize=0;eventFieldSizes={data:0,event:0,id:0,retry:0};dataLineCount=0;maxEventSize;maxDataLines;maxBufferedChunks;event={data:void 0,event:void 0,id:void 0,retry:void 0};constructor(e={}){e.readableObjectMode=!0,super(e),this.state=e.eventSourceSettings||{},this.maxEventSize=e.maxEventSize??f;let t=this.maxEventSize>0?Math.min(v,Math.max(_,Math.floor(this.maxEventSize/y))):0;this.maxDataLines=t,this.maxBufferedChunks=t,e.push&&(this.push=e.push)}_transform(e,t,n){if(e.length===0)n();else if(this.maxEventSize>0&&this.chunks.length>=this.maxBufferedChunks&&e[0]!==c&&e[0]!==l)n(C());else if(this.chunks.push(e),this.checkBOM&&this.handleBOM())n();else{for(;this.hasCurrentByte();){let e=this.currentByte();if(this.eventEndCheck){if(this.crlfCheck){if(e===c){this.crlfCheck=!1,this.consumeCurrentByte();continue}this.crlfCheck=!1}if(e===c||e===l){e===l&&(this.crlfCheck=!0),this.consumeCurrentByte(),this.hasPendingEvent()&&this.processEvent(this.event),this.clearEvent();continue}this.eventEndCheck=!1}else if(e===c||e===l){e===l&&(this.crlfCheck=!0);try{this.parseLine(this.readLine(),this.event)}catch(e){n(e);return}this.consumeCurrentByte(),this.eventEndCheck=!0}else{if(this.maxEventSize>0&&++this.lineLength>this.maxEventSize+7){n(C());return}this.advanceCursor()}}n()}}_destroy(e,t){this.chunks.length=0,this.clearEvent(),super._destroy(e,t)}parseLine(e,t){if(e.length===0)return;let n=e.indexOf(u);if(n===0)return;let r=e.length,i=e.length;if(n!==-1&&(r=n,i=n+1,e[i]===d&&++i),S(e,r,p)){if(this.maxEventSize>0&&this.dataLineCount>=this.maxDataLines)throw C();let n=e.length-i,r=this.eventFieldSizes.data+(t.data===void 0?0:1)+n;this.setEventFieldSize(`data`,r);let a=e.toString(`utf8`,i);t.data===void 0?t.data=a:t.data+=`\n${a}`,this.dataLineCount++}else S(e,r,g)?b(e,i)&&(this.setEventFieldSize(`retry`,e.length-i),t.retry=e.toString(`utf8`,i)):S(e,r,h)?x(e,i)&&(this.setEventFieldSize(`id`,e.length-i),t.id=e.toString(`utf8`,i)):S(e,r,m)&&i<e.length&&(this.setEventFieldSize(`event`,e.length-i),t.event=e.toString(`utf8`,i))}setEventFieldSize(e,t){let n=this.eventSize-this.eventFieldSizes[e]+t;if(this.maxEventSize>0&&n>this.maxEventSize)throw C();this.eventSize=n,this.eventFieldSizes[e]=t}processEvent(e){e.retry&&a(e.retry)&&(this.state.reconnectionTime=parseInt(e.retry,10)),e.id!==void 0&&o(e.id)&&(this.state.lastEventId=e.id),e.data!==void 0&&this.push({type:e.event||`message`,options:{data:e.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event.data=void 0,this.event.event=void 0,this.event.id=void 0,this.event.retry=void 0,this.eventSize=0,this.dataLineCount=0,this.eventFieldSizes.data=0,this.eventFieldSizes.event=0,this.eventFieldSizes.id=0,this.eventFieldSizes.retry=0}hasPendingEvent(){return this.event.data!==void 0||this.event.event!==void 0||this.event.id!==void 0||this.event.retry!==void 0}hasCurrentByte(){return this.chunkIndex<this.chunks.length&&this.pos<this.chunks[this.chunkIndex].length}currentByte(){return this.chunks[this.chunkIndex][this.pos]}consumeCurrentByte(){this.advanceCursor(),this.syncLineStartToCursor()}advanceCursor(){for(this.pos++;this.chunkIndex<this.chunks.length&&this.pos>=this.chunks[this.chunkIndex].length;)this.chunkIndex++,this.pos=0}syncLineStartToCursor(){this.lineChunkIndex=this.chunkIndex,this.linePos=this.pos,this.lineLength=0,this.dropConsumedChunks()}dropConsumedChunks(){if(this.lineChunkIndex>0){let e=this.lineChunkIndex;this.chunks.splice(0,e),this.lineChunkIndex=0,this.chunkIndex-=e}this.chunkIndex===this.chunks.length&&(this.chunks.length=0,this.chunkIndex=0,this.pos=0,this.lineChunkIndex=0,this.linePos=0)}readLine(){if(this.lineChunkIndex===this.chunkIndex)return this.chunks[this.chunkIndex].subarray(this.linePos,this.pos);let e=[],t=0;for(let n=this.lineChunkIndex;n<=this.chunkIndex;n++){let r=this.chunks[n],i=n===this.lineChunkIndex?this.linePos:0,a=n===this.chunkIndex?this.pos:r.length,o=r.subarray(i,a);t+=o.length,e.push(o)}return Buffer.concat(e,t)}peekBufferedByte(e){let t=this.lineChunkIndex,n=this.linePos;for(;t<this.chunks.length;){let r=this.chunks[t],i=r.length-n;if(e<i)return r[n+e];e-=i,t++,n=0}}discardLeadingBytes(e){for(;e>0&&this.lineChunkIndex<this.chunks.length;){let t=this.chunks[this.lineChunkIndex].length-this.linePos;e<t?(this.linePos+=e,e=0):(e-=t,this.lineChunkIndex++,this.linePos=0)}this.chunkIndex=this.lineChunkIndex,this.pos=this.linePos,this.dropConsumedChunks()}handleBOM(){let e=this.peekBufferedByte(0),t=this.peekBufferedByte(1),n=this.peekBufferedByte(2);return t===void 0?(e===s[0]||(this.checkBOM=!1),!0):n===void 0?e===s[0]&&t===s[1]||(this.checkBOM=!1,!1):(e===s[0]&&t===s[1]&&n===s[2]&&this.discardLeadingBytes(3),this.checkBOM=!1,!this.hasCurrentByte())}}}})),ei=t(((t,n)=>{var{pipeline:r}=e(`node:stream`),{fetching:i}=Nr(),{webidl:a}=un(),{EventSourceStream:o}=$r(),{parseMIMEType:s}=ln(),{createFastMessageEvent:c}=Vr(),{isNetworkError:l}=Ar(),{cloneRequest:u}=jr(),{isValidHeaderValue:d,kEnumerableProperty:f}=$(),{environmentSettingsObject:p}=dn(),{createPotentialCORSRequest:m}=Qr(),{getGlobalDispatcher:h}=dr(),{isomorphicDecode:g}=cn(),_=new TextEncoder,v=!1,y=3e3,b=2**31-1,x=0,S=1,C=2,w=`anonymous`,T=`use-credentials`,E=class extends EventTarget{#e={open:null,error:null,message:null};#t;#n=!1;#r=x;#i=null;#a=null;#o;#s;constructor(e,t={}){super(),a.util.markAsUncloneable(this);let n=`EventSource constructor`;a.argumentLengthCheck(arguments,1,n),v||(v=!0,process.emitWarning(`EventSource is experimental, expect them to change at any time.`,{code:`UNDICI-ES`})),e=a.converters.USVString(e),t=a.converters.EventSourceInitDict(t,n,`eventSourceInitDict`),this.#o=t.node.dispatcher||t.dispatcher,this.#s={lastEventId:``,reconnectionTime:t.node.reconnectionTime};let r=p,i;try{i=new URL(e,r.settingsObject.baseUrl),this.#s.origin=i.origin}catch(e){throw new DOMException(e,`SyntaxError`)}this.#t=i.href;let o=w;t.withCredentials===!0&&(o=T,this.#n=!0);let s=m(i,``,o);s.client=p.settingsObject,s.headersList.set(`Accept`,`text/event-stream`),s.cache=`no-store`,s.initiator=`other`,this.#i=s,this.#c()}get readyState(){return a.brandCheck(this,a.is.EventSource),this.#r}get url(){return a.brandCheck(this,a.is.EventSource),this.#t}get withCredentials(){return a.brandCheck(this,a.is.EventSource),this.#n}#c(){if(this.#r===C)return;this.#r=x;let e=u(this.#i);e.urlList=[...this.#i.urlList];let t={request:e,dispatcher:this.#o};t.processResponseEndOfBody=e=>{if(!l(e))return this.#l()},t.processResponse=e=>{if(l(e)){if(e.aborted){this.close(),this.dispatchEvent(new Event(`error`));return}this.#l();return}let t=e.headersList.get(`content-type`,!0),n=t===null?`failure`:s(t),i=n!==`failure`&&n.essence===`text/event-stream`;if(e.status!==200||i===!1){this.close(),this.dispatchEvent(new Event(`error`));return}this.#r=S,this.dispatchEvent(new Event(`open`)),this.#s.origin=e.urlList[e.urlList.length-1].origin;let a=new o({eventSourceSettings:this.#s,maxEventSize:this.#o.eventSourceOptions?.maxEventSize,push:e=>{this.dispatchEvent(c(e.type,e.options))}});r(e.body.stream,a,e=>{e?.aborted===!1&&(this.close(),this.dispatchEvent(new Event(`error`)))})},this.#a=i(t)}#l(){this.#r!==C&&(this.#r=x,this.dispatchEvent(new Event(`error`)),setTimeout(()=>{if(this.#r===x){if(this.#i.headersList.delete(`last-event-id`,!0),this.#s.lastEventId.length){let e=g(_.encode(this.#s.lastEventId));d(e)&&this.#i.headersList.set(`last-event-id`,e,!0)}this.#c()}},Math.min(this.#s.reconnectionTime,b))?.unref())}close(){a.brandCheck(this,a.is.EventSource),this.#r!==C&&(this.#r=C,this.#a.abort(),this.#i=null)}get onopen(){return a.brandCheck(this,a.is.EventSource),this.#e.open}set onopen(e){a.brandCheck(this,a.is.EventSource),this.#e.open&&this.removeEventListener(`open`,this.#e.open);let t=a.converters.EventHandlerNonNull(e);t===null?this.#e.open=null:(this.addEventListener(`open`,t),this.#e.open=e)}get onmessage(){return a.brandCheck(this,a.is.EventSource),this.#e.message}set onmessage(e){a.brandCheck(this,a.is.EventSource),this.#e.message&&this.removeEventListener(`message`,this.#e.message);let t=a.converters.EventHandlerNonNull(e);t===null?this.#e.message=null:(this.addEventListener(`message`,t),this.#e.message=e)}get onerror(){return a.brandCheck(this,a.is.EventSource),this.#e.error}set onerror(e){a.brandCheck(this,a.is.EventSource),this.#e.error&&this.removeEventListener(`error`,this.#e.error);let t=a.converters.EventHandlerNonNull(e);t===null?this.#e.error=null:(this.addEventListener(`error`,t),this.#e.error=e)}static{a.is.EventSource=e=>typeof e==`object`&&!!e&&#e in e}},D={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:x,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:S,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:C,writable:!1}};Object.defineProperties(E,D),Object.defineProperties(E.prototype,D),Object.defineProperties(E.prototype,{close:f,onerror:f,onmessage:f,onopen:f,readyState:f,url:f,withCredentials:f}),a.converters.EventSourceInitDict=a.dictionaryConverter([{key:`withCredentials`,converter:a.converters.boolean,defaultValue:()=>!1},{key:`dispatcher`,converter:a.converters.any,defaultValue:()=>h()},{key:`node`,converter:a.dictionaryConverter([{key:`reconnectionTime`,converter:a.converters[`unsigned long`],defaultValue:()=>y},{key:`dispatcher`,converter:a.converters.any}]),defaultValue:()=>({})}]),n.exports={EventSource:E,defaultReconnectionTime:y}})),ti=t(((e,t)=>{var n=kn(),r=hn(),i=Mn(),a=Nn(),o=Pn(),s=Fn(),c=In(),l=Bn(),u=zn(),d=Vn(),f=Un(),p=Wn(),m=Q(),h=$(),{InvalidArgumentError:g}=m,_=Qn(),v=_n(),y=rr(),{MockCallHistory:b,MockCallHistoryLog:x}=ir(),S=sr(),C=ar(),w=ur(),T=$n(),E=Hn(),{getGlobalDispatcher:D,setGlobalDispatcher:O}=dr(),k=fr(),A=pr();Object.assign(r.prototype,_),t.exports.Dispatcher=r,t.exports.Client=n,t.exports.Pool=i,t.exports.BalancedPool=a,t.exports.RoundRobinPool=o,t.exports.Agent=s,t.exports.Dispatcher1Wrapper=c,t.exports.ProxyAgent=l,t.exports.Socks5ProxyAgent=u,t.exports.EnvHttpProxyAgent=d,t.exports.RetryAgent=f,t.exports.H2CClient=p,t.exports.RetryHandler=E,t.exports.DecoratorHandler=k,t.exports.RedirectHandler=A,t.exports.interceptors={redirect:mr(),responseError:hr(),retry:gr(),dump:_r(),dns:vr(),cache:wr(),decompress:Tr(),deduplicate:Dr()},t.exports.cacheStores={MemoryCacheStore:Sr()};var j=Or();t.exports.cacheStores.SqliteCacheStore=j,t.exports.buildConnector=v,t.exports.errors=m,t.exports.util={parseHeaders:h.parseHeaders,headerNameToString:h.headerNameToString};function M(e){return(t,n,r)=>{if(typeof n==`function`&&(r=n,n=null),!t||typeof t!=`string`&&typeof t!=`object`&&!(t instanceof URL))throw new g(`invalid url`);if(n!=null&&typeof n!=`object`)throw new g(`invalid opts`);if(n&&n.path!=null){if(typeof n.path!=`string`)throw new g(`invalid opts.path`);let e=n.path;n.path.startsWith(`/`)||(e=`/${e}`),t=new URL(h.parseOrigin(t).origin+e)}else n||=typeof t==`object`?t:{},t=h.parseURL(t);let{agent:i,dispatcher:a=D(),...o}=n;if(i)throw new g(`unsupported opts.agent. Did you mean opts.client?`);return e.call(a,{...o,origin:t.origin,path:t.search?`${t.pathname}${t.search}`:t.pathname,method:n.method||(n.body?`PUT`:`GET`)},r)}}t.exports.setGlobalDispatcher=O,t.exports.getGlobalDispatcher=D;var N=Nr().fetch,P=typeof __filename<`u`?__filename:void 0;function F(e,t){if(!e||typeof e!=`object`)return;let n=typeof e.stack==`string`?e.stack:``,r=t.replace(/\\/g,`/`);if(n&&(n.includes(t)||n.includes(r)))return;let i={};if(Error.captureStackTrace(i,F),!i.stack)return;let a=i.stack.split(`
101
101
  `).slice(1).join(`
102
- `);e.stack=n?`${n}\n${a}`:i.stack}t.exports.fetch=function(e,n=void 0){return N(e,n).catch(e=>{throw P?F(e,P):e&&typeof e==`object`&&Error.captureStackTrace(e,t.exports.fetch),e})},t.exports.Headers=kr().Headers,t.exports.Response=Ar().Response,t.exports.Request=jr().Request,t.exports.FormData=pn().FormData;var{setGlobalOrigin:I,getGlobalOrigin:L}=on();t.exports.setGlobalOrigin=I,t.exports.getGlobalOrigin=L;var{CacheStorage:R}=Ir(),{kConstruct:ee}=Z();t.exports.caches=new R(ee);var{deleteCookie:z,getCookies:B,getSetCookies:te,setCookie:ne,parseCookie:V}=Br();t.exports.deleteCookie=z,t.exports.getCookies=B,t.exports.getSetCookies=te,t.exports.setCookie=ne,t.exports.parseCookie=V;var{parseMIMEType:re,serializeAMimeType:ie}=ln();t.exports.parseMIMEType=re,t.exports.serializeAMimeType=ie;var{CloseEvent:ae,ErrorEvent:H,MessageEvent:oe}=Vr(),{WebSocket:U,ping:W}=Yr();t.exports.WebSocket=U,t.exports.CloseEvent=ae,t.exports.ErrorEvent=H,t.exports.MessageEvent=oe,t.exports.ping=W,t.exports.WebSocketStream=Zr().WebSocketStream,t.exports.WebSocketError=Xr().WebSocketError,t.exports.request=M(_.request),t.exports.stream=M(_.stream),t.exports.pipeline=M(_.pipeline),t.exports.connect=M(_.connect),t.exports.upgrade=M(_.upgrade),t.exports.MockClient=y,t.exports.MockCallHistory=b,t.exports.MockCallHistoryLog=x,t.exports.MockPool=C,t.exports.MockAgent=S,t.exports.SnapshotAgent=w,t.exports.mockErrors=T;var{EventSource:G}=ei();t.exports.EventSource=G;function K(){globalThis.fetch=t.exports.fetch,globalThis.Headers=t.exports.Headers,globalThis.Response=t.exports.Response,globalThis.Request=t.exports.Request,globalThis.FormData=t.exports.FormData,globalThis.WebSocket=t.exports.WebSocket,globalThis.CloseEvent=t.exports.CloseEvent,globalThis.ErrorEvent=t.exports.ErrorEvent,globalThis.MessageEvent=t.exports.MessageEvent,globalThis.EventSource=t.exports.EventSource}t.exports.install=K}))(),ni=8,ri=new Set([`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`,`UND_ERR_SOCKET`,`UND_ERR_CONNECT_TIMEOUT`,`UND_ERR_HEADERS_TIMEOUT`,`UND_ERR_BODY_TIMEOUT`]),ii=new Map;function ai(){let e=process.env.AVENTURE_API_SOCKET_PATH,t={headersTimeout:0,bodyTimeout:0},n=ii.get(e??``)??new ti.Dispatcher1Wrapper(e?new ti.Agent({...t,connect:(t,n)=>(0,ti.buildConnector)({socketPath:e,timeout:11e4})({...t,protocol:`http:`},n)}):new ti.EnvHttpProxyAgent({...t,proxyTunnel:!0}));return ii.set(e??``,n),n}async function oi(e,t,n){let r=t.timeoutMs??g(),i=Date.now()+r,a={...t,encodedBody:t.body instanceof FormData?t.body:JSON.stringify(t.body),headers:{...t.headers,[ae]:P()??crypto.randomUUID()},unconfirmedWriteAdvice:t.method===`GET`||t.idempotent===!0?t.unconfirmedWriteAdvice:`no response arrived, so this write may or may not have been stored; read it back`+(t.readbackOperationId===void 0?``:` with ${t.readbackOperationId}`)+` before resending it`},o=t.followRollover===!0,s=(t,a={waitMs:0,deadline:i})=>si(e,t,n,r,a.deadline,a.waitMs),c=Date.now(),l=await s(a);if(!l.ok&&l.headers!==void 0&&Pt(l)===void 0){let n=J(l.status,l.problem,t),r=Date.now();n!==void 0&&r+n+(r-c)<i&&(G({component:`aventure-api-client`,event:`request_retry`,fields:{...pi(a,e.host,a.headers[ae]),retryKind:`http_refusal`,status:l.status,waitMs:Math.round(n)}}),l=await s({...a,idempotent:!1},{waitMs:n,deadline:i}))}let u=Qt(l,t,ui(e.host,`/`).origin);if(u!==void 0)return u;let d=(t[`x-aventure-respond-async`]==="default"?o:!o||t.idempotent)&&Pt(l)!==void 0;if(!o&&!d||!l.ok&&!d)return l;let f={origin:ui(e.host,`/`).origin,sentAt:c,deadline:i,returnBy:t.returnBy,holdStatusUntilSettled:t.holdStatusUntilSettled,signal:t.signal,rollsOver:o};return Ht(l,f,(e,n,r)=>s({method:`GET`,path:e,headers:{...a.headers,Accept:`application/json`},signal:t.signal,statusWaitBy:r},{waitMs:0,deadline:Date.now()+n}))}async function si(e,t,r,i,a,o=0){let s=ui(e.host,t.path,t.searchParams);if(s.origin!==ui(e.host,`/`).origin)throw TypeError(`API request destination must match the configured origin`);let c=t.headers[ae],l=pi(t,e.host,c),u={Accept:`application/json`,"User-Agent":n(),...t.headers,...M()},d=t.encodedBody;d!==void 0&&t.contentType!==void 0&&(u[`Content-Type`]=t.contentType);let f=performance.now();U({component:`aventure-api-client`,event:`request`,fields:{...l,hasBody:d!==void 0}});let p=``,h,g=`neutral`,_,v=`network`,y=e=>{let n=t.signal?.aborted?t.signal.reason:e,r=n instanceof Error&&n.name===`TimeoutError`?`deadline`:t.signal?.aborted?`caller_abort`:e instanceof SyntaxError||e instanceof RangeError?`body`:v;return U({component:`aventure-api-client`,event:`request_failed`,message:K(e),fields:{...l,status:_?.status,timeoutMs:i,failureKind:r,durationMs:Math.round(performance.now()-f),...W(e)},error:e}),r},b=()=>(h=N(s.origin,ee),p=t.unconfirmedWriteAdvice===void 0?``:`; ${t.unconfirmedWriteAdvice}`,h);try{o>0&&await xe(o,void 0,{signal:t.signal}),_=await li(s.href,t,u,d,i,a,b),g=[502,503,504].includes(_.status)?`failure`:`success`,v=`body`;let e={status:_.status,headers:Object.fromEntries(_.headers)},n={...l,status:_.status},c=_.headers.get(`location`),m=fi.has(_.status)&&c!==null;m&&await _.body?.cancel().catch(()=>G({component:`aventure-api-client`,event:`redirect_body_cleanup_failed`,message:`Redirect body cleanup failed after headers were received`,fields:n}));let h=m?``:await We(_,t.responseBytes===!0||t.responseBytes===`negotiated`&&[`text/csv`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`].includes(_.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase()??``)).catch(e=>{if(_?.ok&&e instanceof RangeError)return e;if(_?.ok||e instanceof RangeError)throw e;return y(e),`Response body read failed: ${K(e)}`});v=`schema`;let x=m||h instanceof Uint8Array||h instanceof RangeError?h:mi(h,_.headers.get(`content-type`),_.ok?r:void 0,n,p),S=x instanceof SyntaxError||x instanceof RangeError;S&&y(x);let C=Math.round(performance.now()-f);if(_.ok&&!S||m)return U({component:`aventure-api-client`,event:`response`,fields:{...n,durationMs:C}}),m?{ok:!0,redirect:!0,...e,location:c,data:void 0}:{ok:!0,...e,data:x};let w=S?x.message:x??h,T=q(pe(_.status,w,u),_.headers);T.disposition===`TERMINAL`&&(g=`success`);let E=me(T,u),D=E.code===`search_still_running`&&(t.followRollover===!0||_.headers.has(`location`));return D&&(g=`success`),(D?U:G)({component:`aventure-api-client`,event:D?`following_job`:`problem_response`,fields:{...l,durationMs:C,...he(E,u)}}),{ok:!1,...e,problem:E}}catch(e){let t=y(e);if(e instanceof H)return{ok:!1,status:503,problem:pe(503,{title:`API is ${e.reason===`capacity`?`overloaded`:`unavailable`}; retry later`})};if(v===`schema`)throw e;g!==`failure`&&!(e instanceof RangeError)&&(g=t===`caller_abort`?`neutral`:`failure`);let n=K(e),r=W(e).causeChain,i=r===void 0?``:`: ${String(r)}`;throw Error(v===`body`?`Response body read from ${m()} failed: ${n}${p}`:`request to ${m()} failed: ${n}${i}${p}`,{cause:e})}finally{h?.finish(g)}}function ci(e){for(let t=0;t<ni&&e instanceof Error;t+=1){if(`code`in e&&typeof e.code==`string`)return ri.has(e.code);if(e.name===`TimeoutError`||e.message===`socket hang up`)return!0;e=e.cause}return!1}async function li(e,t,n,r,i,a,o){if(t.method===`GET`&&r!==void 0)throw TypeError(`GET requests cannot have a body`);let s=new Headers(n).get(`X-Client-Request-Id`)??void 0,c=ai(),l=t.method===`GET`||t.idempotent===!0?2:1;for(let u=1;;u+=1){let d=a-Date.now();if(d<=0)throw Object.assign(Error(`request deadline exceeded`),{name:`TimeoutError`});let f=Date.now()+Math.min(i,d),p=AbortSignal.any([AbortSignal.timeout(Math.min(i,d)),...t.signal?[t.signal]:[]]),m;try{return u>1&&await xe(X(),void 0,{signal:p}),p.throwIfAborted(),m=o(),await fetch(e,{method:t.method,headers:Me(n,Oe(t.statusWaitBy,f)),body:r??null,signal:p,dispatcher:c,redirect:`manual`})}catch(n){if(n instanceof H)throw n;let r=p.aborted?p.reason:n;if(u>=l||t.signal?.aborted===!0||Date.now()>=a||!ci(r))throw r;m?.finish(`failure`),G({component:`aventure-api-client`,event:`request_retry`,message:K(n),fields:{...pi(t,new URL(e).host,s),retryKind:`transport`,attempt:u,...W(n)},error:n})}}}function ui(e,t,n){let r=new URL(t,e.startsWith(`http`)?e:`https://${e}`);for(let[e,t]of Object.entries(n??{}))if(Array.isArray(t))for(let n of t)r.searchParams.append(e,String(n));else t!==void 0&&r.searchParams.set(e,String(t));return r}var di=new Set([202,204,205]),fi=new Set([301,302,303,307,308]);function pi(e,t,n){let{method:r,path:i,operationId:a}=e;return{method:r,host:t,path:L(i),requestId:n,operationId:a}}function mi(e,t,n,r,i){let a=t?.includes(`json`)===!0,o=e.length===0?void 0:e;if(e.length>0&&(a||[`{`,`[`].includes(e.trimStart().slice(0,1))))try{o=JSON.parse(e)}catch{if(G({component:`aventure-api-client`,event:`response_json_parse_failed`,message:`API response declared JSON but did not parse`,fields:{...r}}),n!==void 0&&a)return SyntaxError(`API response declared JSON but did not parse${i}`)}if(n===void 0||o===void 0&&di.has(r.status))return o;let s=n.safeParse(o);if(s.success)return s.data;throw Error(`API response failed canonical schema validation${i}`,{cause:s.error})}function hi(e,t,n,r,i){let a=r(gi(e,t,n,!1));return x(a,i)?a:r(gi(e,t,n,!0))}function gi(e,t,n,r){let i=n.redirect?void 0:n.rolloverJob;if(i?.running===!0)return{ids:i.jobId===void 0?[]:[i.jobId],references:i.statusUrl===void 0?[]:[`${e}${i.statusUrl}`]};let{data:a}=n,o=[`${e}${t}`],s=yi(a)?a.sourceDocumentId:void 0;return typeof s==`string`?{ids:[s],references:[...o,`${e}/v1/research/source-documents/${s}/body`]}:{ids:r?vi(a):[],references:o}}var _i=2;function vi(e,t=0){let n=t===0&&Array.isArray(e)?e:yi(e)&&Array.isArray(e.content)?e.content:void 0;return n===void 0?!yi(e)||t>=_i?[]:Object.values(e).flatMap(e=>vi(e,t+1)):n.flatMap(e=>{if(!yi(e))return[];let t=yi(e.entity)?e.entity:e.person,n=yi(t)&&yi(t.core)?t.core.id:void 0,r=yi(e.core)?e.core.id:e.id??n;return typeof r==`string`||typeof r==`number`?[String(r)]:[]})}var yi=e=>typeof e==`object`&&!!e&&!Array.isArray(e),bi=`Idempotency-Key`,xi=`harness-create-`;function Si(e){return e===void 0?`null`:typeof e!=`object`||!e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>Si(e)).join(`,`)}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0).toSorted(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${JSON.stringify(e)}:${Si(t)}`).join(`,`)}}`}function Ci(e){return Object.keys(e).some(e=>e.toLowerCase()===`idempotency-key`)}async function wi(e,t){let n=[...t.entries()].toSorted(([e],[t])=>e<t?-1:+(e>t)),r=await Promise.all(n.map(async([e,t])=>typeof t==`string`?{field:e,kind:`s`,value:t}:{field:e,kind:`f`,name:`name`in t&&typeof t.name==`string`?t.name:``,type:t.type,bytes:new Uint8Array(await t.arrayBuffer())}));for(let t of r)e.update(`${t.field}\0`),t.kind===`s`?e.update(`s\0${t.value}`):(e.update(`f\0${t.name}\0${t.type}\0`),e.update(t.bytes)),e.update(`\0`)}async function Ti(e){if(e.operationId!==`createEntity`||Ci(e.headers)||!kt())return{...e.headers};let t=e.headers[`X-Job-Key`]?.trim();if(!t)return{...e.headers};let n=Se(`sha256`).update(`${t}\0${e.requestPath}\0`);e.wireBody instanceof FormData?await wi(n,e.wireBody):n.update(Si(e.body));let r=n.digest(`hex`).slice(0,40);return{...e.headers,[bi]:`${xi}${r}`}}async function Ei(e){let t=Ci(e.headers);return{headers:await Ti(e),idempotent:e.rolloverIdempotent||e.operationId===`createEntity`&&t}}function Di(e,t){if(t===void 0)return e;let n=re(se().paths,`get`,t);if(n===null)throw Error(`No bundled operation serves the polled job route GET ${t}`);return n.operation}function Oi(e,t,n,r,i){return ki(Di(e,t),n,r,i)}function ki(e,t,n,r){let i=e.responses[String(t)]?.content;return n===void 0?n:Ai(n,i?.[`application/json`]?.schema,r).value}function Ai(e,t,n){let r=Ri(t,n);if(r===void 0||typeof e!=`object`||!e)return{value:e,dropped:0};let i=[...r.oneOf??[],...r.anyOf??[]].filter(t=>Mi(Ri(t,n),e));if(r.properties===void 0&&i.length>0)return i.map(t=>Ai(e,t,n)).reduce((e,t)=>t.dropped<e.dropped?t:e);if(Array.isArray(e))return ji(e,r,n);let a=Ni(r,n);if(a===void 0)return{value:e,dropped:0};let o=0,s=Object.entries(e).flatMap(([e,t])=>{if(t===void 0)return[];let r=a.properties.get(e)??a.additionalProperties;if(r===void 0)return o+=1,[];let i=r===!0?{value:t,dropped:0}:Ai(t,r,n);return o+=i.dropped,[[e,i.value]]});return{value:Object.fromEntries(s),dropped:o}}function ji(e,t,n){let r=t.items??(t.allOf??[]).find(e=>e.items!==void 0)?.items,i=e.map(e=>Ai(e,r,n));return{value:i.map(e=>e.value),dropped:i.reduce((e,t)=>e+t.dropped,0)}}function Mi(e,t){return e===void 0?!1:Array.isArray(t)?e.items!==void 0||Ii(e).includes(`array`):e.type===void 0&&e.properties===void 0||Li(e)||Fi(e).length>0}function Ni(e,t){let n=new Map,r;return Pi(e,t,n,new Set,e=>{r??=e})&&n.size>0?{properties:n,additionalProperties:r}:void 0}function Pi(e,t,n,r,i){let a=e.$ref;if(a!==void 0){if(r.has(a))return!0;r.add(a)}let o=Ri(e,t);if(o===void 0)return!1;(o.additionalProperties===!0||typeof o.additionalProperties==`object`)&&i(o.additionalProperties);for(let[e,t]of Object.entries(o.properties??{}))n.has(e)||n.set(e,t);let s=Fi(o);return o.properties===void 0&&s.length===0?o.type!==void 0&&!Li(o):s.every(e=>Pi(e,t,n,r,i))}function Fi(e){return[...e.allOf??[],...e.oneOf??[],...e.anyOf??[]]}function Ii(e){return e.type===void 0?[]:[e.type].flat()}function Li(e){return e.properties!==void 0||Ii(e).includes(`object`)}function Ri(e,t){let n=A(e);return n===void 0?e:t[n]}var zi=`multipart/form-data`,Bi=`textWrite`,Vi=s({entity:s({core:s({id:o().min(1),typeRecord:u([`Product`,`Service`])})})});function Hi(e,t,n){if(n!==Bi||!kt()||e.operationId!==`createEntity`||!Object.keys(e.requestBody?.content??{}).includes(zi))return;let r=Vi.safeParse(t.data);return r.success?{entityId:r.data.entity.core.id}:void 0}var Ui=(e,t)=>`Prepare the next independent candidate now, then collect this same text job before closing the step: ${be} entities texts writes get --entity-id ${e} --write-id ${t} --data, waiting the returned Retry-After between reads. A pending or rejected text is not a finished offering.`;async function Wi(e){let{operation:t,response:n,committed:r,label:i,schemas:a,origin:o,sentAt:s,deadline:c,returnBy:l,signal:u,poll:d}=e,f=(e,n,i)=>({...C(e,[`The original request succeeded; do not send it again.`]),operationId:t.operationId,ids:n===void 0?[]:[n],references:i===void 0?[]:[i],data:r}),p=`${i} succeeded, but its background job status URL could not be followed.`,m=t.responses[String(n.status)]?.content?.[`application/json`]?.schema,h=A(m),g=(h===void 0?m:a[h])?.properties,_=n.data;if(g!==void 0&&typeof _==`object`&&_&&!Array.isArray(_))for(let[e,r]of Object.entries(g)){if(r[`x-aventure-follow-job`]!==`committed`)continue;let a=Zt(_,e);if(a==null)continue;let m=Ge.safeParse(a);if(!m.success)return f(`${i} succeeded, but its background job reference was malformed.`);let h=m.data,g=E(h.statusUrl,o);if(g===void 0)return f(p,h.jobId);let v=Hi(t,n,e),y;try{y=await Ht({ok:!0,status:202,headers:{location:g},data:h},{origin:o,sentAt:s,deadline:c,returnBy:v===void 0?l:s,signal:u,rollsOver:!0},d)}catch{return f(u?.aborted?`${i} succeeded, but waiting for its background job was canceled; poll ${g}.`:`${i} succeeded, but its background job status could not be read; poll ${g}.`,h.jobId,g)}if(!y.ok)return{...f(`${i} succeeded, but its background job failed; read the problem and do not repeat the request.`,h.jobId,y.rolloverJob?.statusUrl??g),httpStatus:y.problem.status,problem:{...y.problem,mutationNotApplied:!1}};if(y.redirect)return f(`${i} succeeded, but its background job status redirected.`,h.jobId,g);let b=y.rolloverJob?.statusUrl;if(y.rolloverJob?.running===!0||y.status===202){if(b===void 0)return f(p,h.jobId);let e=f(`${i} succeeded, but its background job is still pending; poll ${b}.`,h.jobId,b);return v===void 0?e:{...e,warnings:[...e.warnings,Ui(v.entityId,h.jobId)]}}let x=qt(i,y,!1,t);if(x!==void 0)return{...f(x.summary,h.jobId,b),httpStatus:x.httpStatus}}}var Gi=class extends Error{problem;constructor(e){let{status:t,title:n,detail:r,code:i,retryAfterSeconds:a}=e,o=r?` — ${r}`:``,s=typeof i==`string`?` [code: ${i}]`:``;super(`OAuth bearer verification ${t===429?`was rate limited`:`is unavailable`}: ${t} ${n}${o}${s}${typeof a==`number`?` [retry after ${a} seconds]`:``}`),this.problem=e,this.name=`BearerVerificationUnavailableError`}};async function Ki(e,t,n=[],a){let o=`authorizeOperations`,s=await oi(h(_()),{method:`POST`,path:Ji(o,{}),headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`},body:{operation:[...n]},operationId:o,idempotent:!0,replayRateLimit:!1,timeoutMs:a},He);if(s.ok&&s.redirect)throw new Gi(pe(s.status,`Unexpected authorization redirect`));if(!s.ok&&s.status!==401&&s.status!==403)throw new Gi(s.problem);if(!s.ok)return s.status===403?`forbidden`:null;if(!e.includes(`.`))return s.data;try{let{typ:t}=r(e);if(t!==`at+jwt`&&t!==`application/at+jwt`)return s.data}catch{return s.data}let{aud:c}=i(e);if(c===void 0)return s.data;if(t===void 0)throw Error(`OAuth bearer verification is unavailable`);let l=Array.isArray(c)?c:[c];return l.length===1&&l[0]===t.href?s.data:null}var qi={PATCH:`application/merge-patch+json`,POST:`application/json`,PUT:`application/json`};function Ji(e,t){let n=I(se().paths,e);if(!n)throw Error(`OpenAPI operationId not found: ${e}`);return k(n.template,F(n.operation,t,e),e)}function Yi(e){let t=e.pathParams??{},{paths:n}=se();try{if(e.operationId!==void 0){let r=I(n,e.operationId);return r===null?C(`OpenAPI operationId not found: ${e.operationId}`):b(`Resolved ${e.operationId}`,{...r,path:Ji(e.operationId,t)})}if(e.method===void 0||e.path===void 0)return C(`Pass operationId or method+path.`);let r=O(e.method),i=e.path;n[i]?.[r]===void 0&&i.includes(`{`)&&(i=Object.entries(n).find(([t,n])=>{let i=n[r];return i!==void 0&&(i.parameters??[]).reduce((e,t)=>{let n=t[`x-aventure-legacy-name`]?.name;return n===void 0?e:e.replaceAll(`{${t.name}}`,`{${n}}`)},t)===e.path})?.[0]??e.path);let a=n[i]?.[r],o=k(i,a===void 0?t:F(a,t,e.path),e.path),s=re(n,r,o);return s===null?C(`OpenAPI operation not found for ${e.method} ${L(o)}`):(a===void 0&&F(s.operation,t,e.path),b(`Resolved ${s.operation.operationId}`,{...s,path:o}))}catch(e){return C(e instanceof Error?e.message:String(e))}}async function Xi(e){let t=Date.now(),n=D(),r=t+g(),{paths:i,components:a}=se(),o=re(i,O(e.method),e.path);if(!o)return C(`OpenAPI operation not found for ${e.method} ${L(e.path)}`,[`Use a path in this package's OpenAPI contract; undocumented routes are not supported.`]);let s=o.operation,c=R(s.requestBody?.content),l=oe(c,e.contentType);if(!l.ok||l.data===null)return C(l.summary,l.warnings);let u=Pe(s,e.headers);if(!u.ok||u.data===null)return C(u.summary,u.warnings);let d=e.requesterScope??`write`,f=e.auth===`auto`?(s.security?.length??0)>0?`bearer`:`none`:e.auth,_=ne();if(d===`read`&&_===void 0&&(f===`write`||f===`bearer`))return C(`MCP transport credential is read-only; refused an authenticated upstream call.`,[`Resolved upstream auth=${f} for ${e.method} ${e.path}.`,`Pass auth='read' explicitly for POST read endpoints, or sign in with an account that permits the call.`]);let x=B(e.body);if(!x.ok)return C(x.summary,x.warnings);if(ie(l.data,a.schemas)&&x.data!==void 0&&!Array.isArray(x.data))return C(`${s.operationId} requires a JSON array body.`);let E=s.operationId;if(e.responseFormat===`xlsx`&&!we(s))return C(`This operation does not offer XLSX; use --csv.`);let k=e.responseFormat===`csv`||e.responseFormat===`xlsx`,A=!k&&e.responseBytes===!0&&te(s),M=A?`*/*`:Te(e.responseFormat??`auto`,s),N=await T();if(N!==void 0)return de(`Auth`,N);let P=e.preparedAuth===void 0?_===void 0?ve(f,s,e.searchParams,x.data):p(`none`):b(`reused prepared auth`,e.preparedAuth);if(!P.ok||!P.data)return C(P.summary,P.warnings);let F=e.preparedAuth===void 0&&_!==void 0?{...P.data,credential:v.authToken,headers:{Authorization:`Bearer ${_}`}}:P.data;e.onAuthPrepared?.(F);let I=at({operation:s,searchParams:ye(s,e.searchParams,x.data,F.headers.Authorization),clientInfo:e.clientInfo});if(!I.ok)return C(I.summary,I.warnings);let ee=I.data??void 0,ae=ui(`https://placeholder.invalid`,e.path,ee),H=`${ae.pathname}${ae.search}`,U=It(s,e.method,H),W=h(P.data.env),G=h({...W,host:m()}).host,K={method:e.method,endpoint:H,operationId:E},q=await z(s,x.data,e.contentType,{deadline:r,signal:e.signal,defaultContentType:qi[e.method]});if(!q.ok||q.data===null)return C(q.summary,q.warnings,{httpStatus:q.httpStatus});if(e.signal?.aborted||Date.now()>=r)return C(`Request canceled or invocation deadline exceeded before upload.`);let fe=Vt(s,Math.min(r,n??r),V({method:e.method,path:o.template,operation:s,includeBinary:!0}),e.method),pe={...F.headers,...Et(e.clientInfo)},me=Ie(s,u.data,U),{headers:he,idempotent:ge}=await Ei({operationId:E,requestPath:H,body:x.data,wireBody:q.data.body,rolloverIdempotent:fe.idempotent,headers:{...me,...pe,Accept:M}}),J={method:e.method,path:H,headers:he,body:q.data.body,contentType:q.data.contentType,operationId:E,readbackOperationId:s[`x-aventure-mutation-readback`]?.readOperationId,...fe,idempotent:ge,"x-aventure-respond-async":s[`x-aventure-respond-async`],timeoutMs:Math.max(1,r-Date.now()),returnBy:n,signal:e.signal,replayRefusal:e.replayRefusal};e.onDispatch?.();let Y=A?await oi(W,{...J,responseBytes:!0}):k?await oi(W,{...J,responseBytes:`negotiated`},S):await oi(W,J,S),X=E??e.method,{pending:_e,jobFailure:be}=Kt(X,Y,J.followRollover,s,e.pendingResult!==void 0);if(!Y.ok)return be??de(`${X} failed`,Y.problem,[`endpoint=${H}`],K);if(e.responseFormat===`xlsx`&&(!(Y.data instanceof Uint8Array)||Y.headers[`content-type`]?.split(`;`)[0]?.trim().toLowerCase()!==`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`))return C(`This operation did not return XLSX; use --csv.`);let xe={...K,httpStatus:Y.status};if(Y.data instanceof Uint8Array)return k?b(`${X} succeeded`,Y.data,xe):ce(b(`${X} succeeded`,Y.data));let Se=Jt(s,Y),Ce=y(Y.data),Ee=M===`text/plain`&&typeof Y.data==`string`?Y.data:{...xe,...c.length>1&&l.data!==void 0?{contentType:l.data.contentType}:{},...Y.redirect?{location:Y.location}:{},summary:s.summary,...Se===void 0?{}:{statusDescription:Se},...Y.headers[`x-next-cursor`]?{nextCursor:Y.headers[`x-next-cursor`]}:{},response:Oi(s,Y.redirect?void 0:Y.rolloverJob?.answeredPath,Y.status,Y.data,a.schemas)},De=!Y.redirect&&await Wi({operation:s,response:Y,committed:Ee,label:X,schemas:a.schemas,origin:new URL(W.host).origin,sentAt:Date.now(),deadline:r,returnBy:n,signal:e.signal,poll:(n,i,a)=>oi(W,{method:`GET`,path:n,timeoutMs:Math.min(i,r-t),headers:pe,statusWaitBy:a,signal:e.signal},S)});if(De)return De;if(be!==void 0)return Y.redirect||Y.rolloverJob?.running===!0?be:{...be,data:Ee};let Oe=hi(G,H,Y,e=>b(Xt(X,Y,s),Ee,{...xe,format:Y.redirect||Y.rolloverJob||M!==`text/plain`?`json`:`text`,count:w(Y.data,Ce),page:Ce,filters:j(s,ee),...ue(Y.headers),...e}),e.responseFormat===`json`?le:void 0);return Yt(s,Y)?{...Oe,warnings:[...Oe.warnings,Oe.summary]}:_e&&!Y.redirect&&e.pendingResult!==void 0?e.pendingResult(Oe,Y):Oe}export{Ki as a,Ye as c,Xi as i,He as l,Ji as n,oi as o,Yi as r,Lt as s,Gi as t,Le as u};
102
+ `);e.stack=n?`${n}\n${a}`:i.stack}t.exports.fetch=function(e,n=void 0){return N(e,n).catch(e=>{throw P?F(e,P):e&&typeof e==`object`&&Error.captureStackTrace(e,t.exports.fetch),e})},t.exports.Headers=kr().Headers,t.exports.Response=Ar().Response,t.exports.Request=jr().Request,t.exports.FormData=pn().FormData;var{setGlobalOrigin:I,getGlobalOrigin:L}=on();t.exports.setGlobalOrigin=I,t.exports.getGlobalOrigin=L;var{CacheStorage:R}=Ir(),{kConstruct:ee}=Z();t.exports.caches=new R(ee);var{deleteCookie:z,getCookies:B,getSetCookies:te,setCookie:ne,parseCookie:V}=Br();t.exports.deleteCookie=z,t.exports.getCookies=B,t.exports.getSetCookies=te,t.exports.setCookie=ne,t.exports.parseCookie=V;var{parseMIMEType:re,serializeAMimeType:ie}=ln();t.exports.parseMIMEType=re,t.exports.serializeAMimeType=ie;var{CloseEvent:ae,ErrorEvent:H,MessageEvent:oe}=Vr(),{WebSocket:U,ping:W}=Yr();t.exports.WebSocket=U,t.exports.CloseEvent=ae,t.exports.ErrorEvent=H,t.exports.MessageEvent=oe,t.exports.ping=W,t.exports.WebSocketStream=Zr().WebSocketStream,t.exports.WebSocketError=Xr().WebSocketError,t.exports.request=M(_.request),t.exports.stream=M(_.stream),t.exports.pipeline=M(_.pipeline),t.exports.connect=M(_.connect),t.exports.upgrade=M(_.upgrade),t.exports.MockClient=y,t.exports.MockCallHistory=b,t.exports.MockCallHistoryLog=x,t.exports.MockPool=C,t.exports.MockAgent=S,t.exports.SnapshotAgent=w,t.exports.mockErrors=T;var{EventSource:G}=ei();t.exports.EventSource=G;function K(){globalThis.fetch=t.exports.fetch,globalThis.Headers=t.exports.Headers,globalThis.Response=t.exports.Response,globalThis.Request=t.exports.Request,globalThis.FormData=t.exports.FormData,globalThis.WebSocket=t.exports.WebSocket,globalThis.CloseEvent=t.exports.CloseEvent,globalThis.ErrorEvent=t.exports.ErrorEvent,globalThis.MessageEvent=t.exports.MessageEvent,globalThis.EventSource=t.exports.EventSource}t.exports.install=K}))(),ni=8,ri=new Set([`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`,`UND_ERR_SOCKET`,`UND_ERR_CONNECT_TIMEOUT`,`UND_ERR_HEADERS_TIMEOUT`,`UND_ERR_BODY_TIMEOUT`]),ii=new Map;function ai(){let e=process.env.AVENTURE_API_SOCKET_PATH,t={headersTimeout:0,bodyTimeout:0},n=ii.get(e??``)??new ti.Dispatcher1Wrapper(e?new ti.Agent({...t,connect:(t,n)=>(0,ti.buildConnector)({socketPath:e,timeout:11e4})({...t,protocol:`http:`},n)}):new ti.EnvHttpProxyAgent({...t,proxyTunnel:!0}));return ii.set(e??``,n),n}async function oi(e,t,n){let r=t.timeoutMs??g(),i=Date.now()+r,a={...t,encodedBody:t.body instanceof FormData?t.body:JSON.stringify(t.body),headers:{...t.headers,[ae]:P()??crypto.randomUUID()},unconfirmedWriteAdvice:t.method===`GET`||t.idempotent===!0?t.unconfirmedWriteAdvice:`no response arrived, so this write may or may not have been stored; read it back`+(t.readbackOperationId===void 0?``:` with ${t.readbackOperationId}`)+` before resending it`},o=t.followRollover===!0,s=(t,a={waitMs:0,deadline:i})=>si(e,t,n,r,a.deadline,a.waitMs),c=Date.now(),l=await s(a);if(!l.ok&&l.headers!==void 0&&Pt(l)===void 0){let n=J(l.status,l.problem,t),r=Date.now();n!==void 0&&r+n+(r-c)<i&&(G({component:`aventure-api-client`,event:`request_retry`,fields:{...pi(a,e.host,a.headers[ae]),retryKind:`http_refusal`,status:l.status,waitMs:Math.round(n)}}),l=await s({...a,idempotent:!1},{waitMs:n,deadline:i}))}let u=Qt(l,t,ui(e.host,`/`).origin);if(u!==void 0)return u;let d=(t[`x-aventure-respond-async`]==="default"?o:!o||t.idempotent)&&Pt(l)!==void 0;if(!o&&!d||!l.ok&&!d)return l;let f={origin:ui(e.host,`/`).origin,sentAt:c,deadline:i,returnBy:t.returnBy,holdStatusUntilSettled:t.holdStatusUntilSettled,signal:t.signal,rollsOver:o};return Ht(l,f,(e,n,r)=>s({method:`GET`,path:e,headers:{...a.headers,Accept:`application/json`},signal:t.signal,statusWaitBy:r},{waitMs:0,deadline:Date.now()+n}))}async function si(e,t,r,i,a,o=0){let s=ui(e.host,t.path,t.searchParams);if(s.origin!==ui(e.host,`/`).origin)throw TypeError(`API request destination must match the configured origin`);let c=t.headers[ae],l=pi(t,e.host,c),u={Accept:`application/json`,"User-Agent":n(),...t.headers,...M()},d=t.encodedBody;d!==void 0&&t.contentType!==void 0&&(u[`Content-Type`]=t.contentType);let f=performance.now();U({component:`aventure-api-client`,event:`request`,fields:{...l,hasBody:d!==void 0}});let p=``,h,g=`neutral`,_,v=`network`,y=e=>{let n=t.signal?.aborted?t.signal.reason:e,r=n instanceof Error&&n.name===`TimeoutError`?`deadline`:t.signal?.aborted?`caller_abort`:e instanceof SyntaxError||e instanceof RangeError?`body`:v;return U({component:`aventure-api-client`,event:`request_failed`,message:K(e),fields:{...l,status:_?.status,timeoutMs:i,failureKind:r,durationMs:Math.round(performance.now()-f),...W(e)},error:e}),r},b=()=>(h=N(s.origin,ee),p=t.unconfirmedWriteAdvice===void 0?``:`; ${t.unconfirmedWriteAdvice}`,h);try{o>0&&await xe(o,void 0,{signal:t.signal}),_=await li(s.href,t,u,d,i,a,b),g=[502,503,504].includes(_.status)?`failure`:`success`,v=`body`;let e={status:_.status,headers:Object.fromEntries(_.headers)},n={...l,status:_.status},c=_.headers.get(`location`),m=fi.has(_.status)&&c!==null;m&&await _.body?.cancel().catch(()=>G({component:`aventure-api-client`,event:`redirect_body_cleanup_failed`,message:`Redirect body cleanup failed after headers were received`,fields:n}));let h=m?``:await We(_,t.responseBytes===!0||t.responseBytes===`negotiated`&&[`text/csv`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`].includes(_.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase()??``)).catch(e=>{if(_?.ok&&e instanceof RangeError)return e;if(_?.ok||e instanceof RangeError)throw e;return y(e),`Response body read failed: ${K(e)}`});v=`schema`;let x=m||h instanceof Uint8Array||h instanceof RangeError?h:mi(h,_.headers.get(`content-type`),_.ok?r:void 0,n,p),S=x instanceof SyntaxError||x instanceof RangeError;S&&y(x);let C=Math.round(performance.now()-f);if(_.ok&&!S||m)return U({component:`aventure-api-client`,event:`response`,fields:{...n,durationMs:C}}),m?{ok:!0,redirect:!0,...e,location:c,data:void 0}:{ok:!0,...e,data:x};let w=S?x.message:x??h,T=q(pe(_.status,w,u),_.headers);T.disposition===`TERMINAL`&&(g=`success`);let E=me(T,u),D=E.code===`search_still_running`&&(t.followRollover===!0||_.headers.has(`location`));return D&&(g=`success`),(D?U:G)({component:`aventure-api-client`,event:D?`following_job`:`problem_response`,fields:{...l,durationMs:C,...he(E,u)}}),{ok:!1,...e,problem:E}}catch(e){let t=y(e);if(e instanceof H)return{ok:!1,status:503,problem:pe(503,{title:`API is ${e.reason===`capacity`?`overloaded`:`unavailable`}; retry later`})};if(v===`schema`)throw e;g!==`failure`&&!(e instanceof RangeError)&&(g=t===`caller_abort`?`neutral`:`failure`);let n=K(e),r=W(e).causeChain,i=r===void 0?``:`: ${String(r)}`;throw Error(v===`body`?`Response body read from ${m()} failed: ${n}${p}`:`request to ${m()} failed: ${n}${i}${p}`,{cause:e})}finally{h?.finish(g)}}function ci(e){for(let t=0;t<ni&&e instanceof Error;t+=1){if(`code`in e&&typeof e.code==`string`)return ri.has(e.code);if(e.name===`TimeoutError`||e.message===`socket hang up`)return!0;e=e.cause}return!1}async function li(e,t,n,r,i,a,o){if(t.method===`GET`&&r!==void 0)throw TypeError(`GET requests cannot have a body`);let s=new Headers(n).get(`X-Client-Request-Id`)??void 0,c=ai(),l=t.method===`GET`||t.idempotent===!0?2:1;for(let u=1;;u+=1){let d=a-Date.now();if(d<=0)throw Object.assign(Error(`request deadline exceeded`),{name:`TimeoutError`});let f=Date.now()+Math.min(i,d),p=AbortSignal.any([AbortSignal.timeout(Math.min(i,d)),...t.signal?[t.signal]:[]]),m;try{return u>1&&await xe(X(),void 0,{signal:p}),p.throwIfAborted(),m=o(),await fetch(e,{method:t.method,headers:Me(n,Oe(t.statusWaitBy,f)),body:r??null,signal:p,dispatcher:c,redirect:`manual`})}catch(n){if(n instanceof H)throw n;let r=p.aborted?p.reason:n;if(u>=l||t.signal?.aborted===!0||Date.now()>=a||!ci(r))throw r;m?.finish(`failure`),G({component:`aventure-api-client`,event:`request_retry`,message:K(n),fields:{...pi(t,new URL(e).host,s),retryKind:`transport`,attempt:u,...W(n)},error:n})}}}function ui(e,t,n){let r=new URL(t,e.startsWith(`http`)?e:`https://${e}`);for(let[e,t]of Object.entries(n??{}))if(Array.isArray(t))for(let n of t)r.searchParams.append(e,String(n));else t!==void 0&&r.searchParams.set(e,String(t));return r}var di=new Set([202,204,205]),fi=new Set([301,302,303,307,308]);function pi(e,t,n){let{method:r,path:i,operationId:a}=e;return{method:r,host:t,path:L(i),requestId:n,operationId:a}}function mi(e,t,n,r,i){let a=t?.includes(`json`)===!0,o=e.length===0?void 0:e;if(e.length>0&&(a||[`{`,`[`].includes(e.trimStart().slice(0,1))))try{o=JSON.parse(e)}catch{if(G({component:`aventure-api-client`,event:`response_json_parse_failed`,message:`API response declared JSON but did not parse`,fields:{...r}}),n!==void 0&&a)return SyntaxError(`API response declared JSON but did not parse${i}`)}if(n===void 0||o===void 0&&di.has(r.status))return o;let s=n.safeParse(o);if(s.success)return s.data;throw Error(`API response failed canonical schema validation${i}`,{cause:s.error})}function hi(e,t,n,r,i){let a=r(gi(e,t,n,!1));return x(a,i)?a:r(gi(e,t,n,!0))}function gi(e,t,n,r){let i=n.redirect?void 0:n.rolloverJob;if(i?.running===!0)return{ids:i.jobId===void 0?[]:[i.jobId],references:i.statusUrl===void 0?[]:[`${e}${i.statusUrl}`]};let{data:a}=n,o=[`${e}${t}`],s=yi(a)?a.sourceDocumentId:void 0;return typeof s==`string`?{ids:[s],references:[...o,`${e}/v1/research/source-documents/${s}/body`]}:{ids:r?vi(a):[],references:o}}var _i=2;function vi(e,t=0){let n=t===0&&Array.isArray(e)?e:yi(e)&&Array.isArray(e.content)?e.content:void 0;return n===void 0?!yi(e)||t>=_i?[]:Object.values(e).flatMap(e=>vi(e,t+1)):n.flatMap(e=>{if(!yi(e))return[];let t=yi(e.entity)?e.entity:e.person,n=yi(t)&&yi(t.core)?t.core.id:void 0,r=yi(e.core)?e.core.id:e.id??n;return typeof r==`string`||typeof r==`number`?[String(r)]:[]})}var yi=e=>typeof e==`object`&&!!e&&!Array.isArray(e),bi=`Idempotency-Key`,xi=`harness-create-`;function Si(e){return e===void 0?`null`:typeof e!=`object`||!e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>Si(e)).join(`,`)}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0).toSorted(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${JSON.stringify(e)}:${Si(t)}`).join(`,`)}}`}function Ci(e){return Object.keys(e).some(e=>e.toLowerCase()===`idempotency-key`)}async function wi(e,t){let n=[...t.entries()].toSorted(([e],[t])=>e<t?-1:+(e>t)),r=await Promise.all(n.map(async([e,t])=>typeof t==`string`?{field:e,kind:`s`,value:t}:{field:e,kind:`f`,name:`name`in t&&typeof t.name==`string`?t.name:``,type:t.type,bytes:new Uint8Array(await t.arrayBuffer())}));for(let t of r)e.update(`${t.field}\0`),t.kind===`s`?e.update(`s\0${t.value}`):(e.update(`f\0${t.name}\0${t.type}\0`),e.update(t.bytes)),e.update(`\0`)}async function Ti(e){if(e.operationId!==`createEntity`||Ci(e.headers)||!kt())return{...e.headers};let t=e.headers[`X-Job-Key`]?.trim();if(!t)return{...e.headers};let n=Se(`sha256`).update(`${t}\0${e.requestPath}\0`);e.wireBody instanceof FormData?await wi(n,e.wireBody):n.update(Si(e.body));let r=n.digest(`hex`).slice(0,40);return{...e.headers,[bi]:`${xi}${r}`}}async function Ei(e){let t=Ci(e.headers);return{headers:await Ti(e),idempotent:e.rolloverIdempotent||e.operationId===`createEntity`&&t}}function Di(e,t){if(t===void 0)return e;let n=re(se().paths,`get`,t);if(n===null)throw Error(`No bundled operation serves the polled job route GET ${t}`);return n.operation}function Oi(e,t,n,r,i){return ki(Di(e,t),n,r,i)}function ki(e,t,n,r){let i=e.responses[String(t)]?.content;return n===void 0?n:Ai(n,i?.[`application/json`]?.schema,r).value}function Ai(e,t,n){let r=Ri(t,n);if(r===void 0||typeof e!=`object`||!e)return{value:e,dropped:0};let i=[...r.oneOf??[],...r.anyOf??[]].filter(t=>Mi(Ri(t,n),e));if(r.properties===void 0&&i.length>0)return i.map(t=>Ai(e,t,n)).reduce((e,t)=>t.dropped<e.dropped?t:e);if(Array.isArray(e))return ji(e,r,n);let a=Ni(r,n);if(a===void 0)return{value:e,dropped:0};let o=0,s=Object.entries(e).flatMap(([e,t])=>{if(t===void 0)return[];let r=a.properties.get(e)??a.additionalProperties;if(r===void 0)return o+=1,[];let i=r===!0?{value:t,dropped:0}:Ai(t,r,n);return o+=i.dropped,[[e,i.value]]});return{value:Object.fromEntries(s),dropped:o}}function ji(e,t,n){let r=t.items??(t.allOf??[]).find(e=>e.items!==void 0)?.items,i=e.map(e=>Ai(e,r,n));return{value:i.map(e=>e.value),dropped:i.reduce((e,t)=>e+t.dropped,0)}}function Mi(e,t){return e===void 0?!1:Array.isArray(t)?e.items!==void 0||Ii(e).includes(`array`):e.type===void 0&&e.properties===void 0||Li(e)||Fi(e).length>0}function Ni(e,t){let n=new Map,r;return Pi(e,t,n,new Set,e=>{r??=e})&&n.size>0?{properties:n,additionalProperties:r}:void 0}function Pi(e,t,n,r,i){let a=e.$ref;if(a!==void 0){if(r.has(a))return!0;r.add(a)}let o=Ri(e,t);if(o===void 0)return!1;(o.additionalProperties===!0||typeof o.additionalProperties==`object`)&&i(o.additionalProperties);for(let[e,t]of Object.entries(o.properties??{}))n.has(e)||n.set(e,t);let s=Fi(o);return o.properties===void 0&&s.length===0?o.type!==void 0&&!Li(o):s.every(e=>Pi(e,t,n,r,i))}function Fi(e){return[...e.allOf??[],...e.oneOf??[],...e.anyOf??[]]}function Ii(e){return e.type===void 0?[]:[e.type].flat()}function Li(e){return e.properties!==void 0||Ii(e).includes(`object`)}function Ri(e,t){let n=A(e);return n===void 0?e:t[n]}var zi=`multipart/form-data`,Bi=`textWrite`,Vi=s({entity:s({core:s({id:o().min(1),typeRecord:u([`Product`,`Service`])})})});function Hi(e,t,n){if(n!==Bi||!kt()||e.operationId!==`createEntity`||!Object.keys(e.requestBody?.content??{}).includes(zi))return;let r=Vi.safeParse(t.data);return r.success?{entityId:r.data.entity.core.id}:void 0}var Ui=(e,t)=>`Prepare the next independent candidate now, then collect this same text job before closing the step: ${be} entities texts writes get --entity-id ${e} --write-id ${t} --data, waiting the returned Retry-After between reads. A pending or rejected text is not a finished offering.`;async function Wi(e){let{operation:t,response:n,committed:r,label:i,schemas:a,origin:o,sentAt:s,deadline:c,returnBy:l,signal:u,poll:d}=e,f=(e,n,i)=>({...C(e,[`The original request succeeded; do not send it again.`]),operationId:t.operationId,ids:n===void 0?[]:[n],references:i===void 0?[]:[i],data:r}),p=`${i} succeeded, but its background job status URL could not be followed.`,m=t.responses[String(n.status)]?.content?.[`application/json`]?.schema,h=A(m),g=(h===void 0?m:a[h])?.properties,_=n.data;if(g!==void 0&&typeof _==`object`&&_&&!Array.isArray(_))for(let[e,r]of Object.entries(g)){if(r[`x-aventure-follow-job`]!==`committed`)continue;let a=Zt(_,e);if(a==null)continue;let m=Ge.safeParse(a);if(!m.success)return f(`${i} succeeded, but its background job reference was malformed.`);let h=m.data,g=E(h.statusUrl,o);if(g===void 0)return f(p,h.jobId);let v=Hi(t,n,e),y;try{y=await Ht({ok:!0,status:202,headers:{location:g},data:h},{origin:o,sentAt:s,deadline:c,returnBy:v===void 0?l:s,signal:u,rollsOver:!0},d)}catch{return f(u?.aborted?`${i} succeeded, but waiting for its background job was canceled; poll ${g}.`:`${i} succeeded, but its background job status could not be read; poll ${g}.`,h.jobId,g)}if(!y.ok)return{...f(`${i} succeeded, but its background job failed; read the problem and do not repeat the request.`,h.jobId,y.rolloverJob?.statusUrl??g),httpStatus:y.problem.status,problem:{...y.problem,mutationNotApplied:!1}};if(y.redirect)return f(`${i} succeeded, but its background job status redirected.`,h.jobId,g);let b=y.rolloverJob?.statusUrl;if(y.rolloverJob?.running===!0||y.status===202){if(b===void 0)return f(p,h.jobId);let e=f(`${i} succeeded, but its background job is still pending; poll ${b}.`,h.jobId,b);return v===void 0?e:{...e,warnings:[...e.warnings,Ui(v.entityId,h.jobId)]}}let x=qt(i,y,!1,t);if(x!==void 0)return{...f(x.summary,h.jobId,b),httpStatus:x.httpStatus}}}var Gi=class extends Error{problem;constructor(e){let{status:t,title:n,detail:r,code:i,retryAfterSeconds:a}=e,o=r?` — ${r}`:``,s=typeof i==`string`?` [code: ${i}]`:``;super(`OAuth bearer verification ${t===429?`was rate limited`:`is unavailable`}: ${t} ${n}${o}${s}${typeof a==`number`?` [retry after ${a} seconds]`:``}`),this.problem=e,this.name=`BearerVerificationUnavailableError`}};async function Ki(e,t,n=[],a){let o=`authorizeOperations`,s=await oi(h(_()),{method:`POST`,path:Ji(o,{}),headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`},body:{operation:[...n]},operationId:o,idempotent:!0,replayRateLimit:!1,timeoutMs:a},He);if(s.ok&&s.redirect)throw new Gi(pe(s.status,`Unexpected authorization redirect`));if(!s.ok&&s.status!==401&&s.status!==403)throw new Gi(s.problem);if(!s.ok)return s.status===403?`forbidden`:null;if(!e.includes(`.`))return s.data;try{let{typ:t}=r(e);if(t!==`at+jwt`&&t!==`application/at+jwt`)return s.data}catch{return s.data}let{aud:c}=i(e);if(c===void 0)return s.data;if(t===void 0)throw Error(`OAuth bearer verification is unavailable`);let l=Array.isArray(c)?c:[c];return l.length===1&&l[0]===t.href?s.data:null}var qi={PATCH:`application/merge-patch+json`,POST:`application/json`,PUT:`application/json`};function Ji(e,t){let n=I(se().paths,e);if(!n)throw Error(`OpenAPI operationId not found: ${e}`);return k(n.template,F(n.operation,t,e),e)}function Yi(e){let t=e.pathParams??{},{paths:n}=se();try{if(e.operationId!==void 0){let r=I(n,e.operationId);return r===null?C(`OpenAPI operationId not found: ${e.operationId}`):b(`Resolved ${e.operationId}`,{...r,path:Ji(e.operationId,t)})}if(e.method===void 0||e.path===void 0)return C(`Pass operationId or method+path.`);let r=O(e.method),i=e.path;n[i]?.[r]===void 0&&i.includes(`{`)&&(i=Object.entries(n).find(([t,n])=>{let i=n[r];return i!==void 0&&(i.parameters??[]).reduce((e,t)=>{let n=t[`x-aventure-legacy-name`]?.name;return n===void 0?e:e.replaceAll(`{${t.name}}`,`{${n}}`)},t)===e.path})?.[0]??e.path);let a=n[i]?.[r],o=k(i,a===void 0?t:F(a,t,e.path),e.path),s=re(n,r,o);return s===null?C(`OpenAPI operation not found for ${e.method} ${L(o)}`):(a===void 0&&F(s.operation,t,e.path),b(`Resolved ${s.operation.operationId}`,{...s,path:o}))}catch(e){return C(e instanceof Error?e.message:String(e))}}async function Xi(e){let{paths:t,components:n}=se(),r=Date.now(),i=D(),a=r+g(),o=re(t,O(e.method),e.path);if(!o)return C(`OpenAPI operation not found for ${e.method} ${L(e.path)}`,[`Use a path in this package's OpenAPI contract; undocumented routes are not supported.`]);let s=o.operation,c=R(s.requestBody?.content),l=oe(c,e.contentType);if(!l.ok||l.data===null)return C(l.summary,l.warnings);let u=Pe(s,e.headers);if(!u.ok||u.data===null)return C(u.summary,u.warnings);let d=e.requesterScope??`write`,f=e.auth===`auto`?(s.security?.length??0)>0?`bearer`:`none`:e.auth,_=ne();if(d===`read`&&_===void 0&&(f===`write`||f===`bearer`))return C(`MCP transport credential is read-only; refused an authenticated upstream call.`,[`Resolved upstream auth=${f} for ${e.method} ${e.path}.`,`Pass auth='read' explicitly for POST read endpoints, or sign in with an account that permits the call.`]);let x=B(e.body);if(!x.ok)return C(x.summary,x.warnings);if(ie(l.data,n.schemas)&&x.data!==void 0&&!Array.isArray(x.data))return C(`${s.operationId} requires a JSON array body.`);let E=s.operationId;if(e.responseFormat===`xlsx`&&!we(s))return C(`This operation does not offer XLSX; use --csv.`);let k=e.responseFormat===`csv`||e.responseFormat===`xlsx`,A=!k&&e.responseBytes===!0&&te(s),M=A?`*/*`:Te(e.responseFormat??`auto`,s),N=await T();if(N!==void 0)return de(`Auth`,N);let P=e.preparedAuth===void 0?_===void 0?ve(f,s,e.searchParams,x.data):p(`none`):b(`reused prepared auth`,e.preparedAuth);if(!P.ok||!P.data)return C(P.summary,P.warnings);let F=e.preparedAuth===void 0&&_!==void 0?{...P.data,credential:v.authToken,headers:{Authorization:`Bearer ${_}`}}:P.data;e.onAuthPrepared?.(F);let I=at({operation:s,searchParams:ye(s,e.searchParams,x.data,F.headers.Authorization),clientInfo:e.clientInfo});if(!I.ok)return C(I.summary,I.warnings);let ee=I.data??void 0,ae=ui(`https://placeholder.invalid`,e.path,ee),H=`${ae.pathname}${ae.search}`,U=It(s,e.method,H),W=h(P.data.env),G=h({...W,host:m()}).host,K={method:e.method,endpoint:H,operationId:E},q=await z(s,x.data,e.contentType,{deadline:a,signal:e.signal,defaultContentType:qi[e.method]});if(!q.ok||q.data===null)return C(q.summary,q.warnings,{httpStatus:q.httpStatus});if(e.signal?.aborted||Date.now()>=a)return C(`Request canceled or invocation deadline exceeded before upload.`);let fe=Vt(s,Math.min(a,i??a),V({method:e.method,path:o.template,operation:s,includeBinary:!0}),e.method),pe={...F.headers,...Et(e.clientInfo)},me=Ie(s,u.data,U),{headers:he,idempotent:ge}=await Ei({operationId:E,requestPath:H,body:x.data,wireBody:q.data.body,rolloverIdempotent:fe.idempotent,headers:{...me,...pe,Accept:M}}),J={method:e.method,path:H,headers:he,body:q.data.body,contentType:q.data.contentType,operationId:E,readbackOperationId:s[`x-aventure-mutation-readback`]?.readOperationId,...fe,idempotent:ge,"x-aventure-respond-async":s[`x-aventure-respond-async`],timeoutMs:Math.max(1,a-Date.now()),returnBy:i,signal:e.signal,replayRefusal:e.replayRefusal};e.onDispatch?.();let Y=A?await oi(W,{...J,responseBytes:!0}):k?await oi(W,{...J,responseBytes:`negotiated`},S):await oi(W,J,S),X=E??e.method,{pending:_e,jobFailure:be}=Kt(X,Y,J.followRollover,s,e.pendingResult!==void 0);if(!Y.ok)return be??de(`${X} failed`,Y.problem,[`endpoint=${H}`],K);if(e.responseFormat===`xlsx`&&(!(Y.data instanceof Uint8Array)||Y.headers[`content-type`]?.split(`;`)[0]?.trim().toLowerCase()!==`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`))return C(`This operation did not return XLSX; use --csv.`);let xe={...K,httpStatus:Y.status};if(Y.data instanceof Uint8Array)return k?b(`${X} succeeded`,Y.data,xe):ce(b(`${X} succeeded`,Y.data));let Se=Jt(s,Y),Ce=y(Y.data),Ee=M===`text/plain`&&typeof Y.data==`string`?Y.data:{...xe,...c.length>1&&l.data!==void 0?{contentType:l.data.contentType}:{},...Y.redirect?{location:Y.location}:{},summary:s.summary,...Se===void 0?{}:{statusDescription:Se},...Y.headers[`x-next-cursor`]?{nextCursor:Y.headers[`x-next-cursor`]}:{},response:Oi(s,Y.redirect?void 0:Y.rolloverJob?.answeredPath,Y.status,Y.data,n.schemas)},De=!Y.redirect&&await Wi({operation:s,response:Y,committed:Ee,label:X,schemas:n.schemas,origin:new URL(W.host).origin,sentAt:Date.now(),deadline:a,returnBy:i,signal:e.signal,poll:(t,n,i)=>oi(W,{method:`GET`,path:t,timeoutMs:Math.min(n,a-r),headers:pe,statusWaitBy:i,signal:e.signal},S)});if(De)return De;if(be!==void 0)return Y.redirect||Y.rolloverJob?.running===!0?be:{...be,data:Ee};let Oe=hi(G,H,Y,e=>b(Xt(X,Y,s),Ee,{...xe,format:Y.redirect||Y.rolloverJob||M!==`text/plain`?`json`:`text`,count:w(Y.data,Ce),page:Ce,filters:j(s,ee),...ue(Y.headers),...e}),e.responseFormat===`json`?le:void 0);return Yt(s,Y)?{...Oe,warnings:[...Oe.warnings,Oe.summary]}:_e&&!Y.redirect&&e.pendingResult!==void 0?e.pendingResult(Oe,Y):Oe}export{Ki as a,Ye as c,Xi as i,He as l,Ji as n,oi as o,Yi as r,Lt as s,Gi as t,Le as u};
@@ -1 +1 @@
1
- export{t as BearerVerificationUnavailableError,n as buildOpenApiPath,r as resolveOpenApiOperationSelector,i as runOpenApiCall,a as verifyUserBearerToken}from"./openapi-call-BC15WKDc.js";
1
+ export{t as BearerVerificationUnavailableError,n as buildOpenApiPath,r as resolveOpenApiOperationSelector,i as runOpenApiCall,a as verifyUserBearerToken}from"./openapi-call-BI8CGnE_.js";