@aventurevc/aventure-cli 0.8.386 → 0.8.387
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aventure-cli/index.js +1 -1
- package/dist/aventure-cli/unified-operations.json +1 -1
- package/dist/chunks/{api-key-credential-verification-CJ5CCGAA.js → api-key-credential-verification-C_DQtQyx.js} +1 -1
- package/dist/chunks/{api-key-credential-verification-TNvdeeGh.js → api-key-credential-verification-DC-YG5wa.js} +1 -1
- package/dist/chunks/{api-key-login-C70ptWkf.js → api-key-login-DSWEmjPA.js} +1 -1
- package/dist/chunks/{auth-status-check-oJLDd2a7.js → auth-status-check-Cwf6uUZP.js} +1 -1
- package/dist/chunks/{auth-status-check-W8rkgIvv.js → auth-status-check-DcY55e4Q.js} +1 -1
- package/dist/chunks/{auth-status-render-BIHZs1Fl.js → auth-status-render-DlSjZ6kk.js} +1 -1
- package/dist/chunks/{aventure-cli-CgIcnt5d.js → aventure-cli-SEyW_1AB.js} +5 -5
- package/dist/chunks/{builtin-auth-8D5ET0Cp.js → builtin-auth-IPP_Zmbj.js} +4 -4
- package/dist/chunks/{builtin-run-wait-bdVye6Ce.js → builtin-run-wait-5yr1WK3I.js} +1 -1
- package/dist/chunks/{logout-Du693hU1.js → logout-Dxt8vao3.js} +1 -1
- package/dist/chunks/logout-GwrTE5av.js +1 -0
- package/dist/chunks/oauth-bearer-credential-BiDojkqU.js +1 -0
- package/dist/chunks/{oauth-bearer-credential-DlyXyoGr.js → oauth-bearer-credential-CxuQ4uM5.js} +1 -1
- package/dist/chunks/{oauth-login-D7bKxIzU.js → oauth-login-155QGdTQ.js} +1 -1
- package/dist/chunks/{oauth-login-CJo685tl.js → oauth-login-BDOwNja7.js} +1 -1
- package/dist/chunks/{openapi-call-DrJ9I2I1.js → openapi-call-DRowSHyQ.js} +1 -1
- package/dist/chunks/{openapi-call-BN_q73Gl.js → openapi-call-Gchy3s8a.js} +1 -1
- package/dist/chunks/{operations-Dger9pq7.js → operations-DbanGAPY.js} +1 -1
- package/dist/chunks/operations-catalog-D4YIaQHB.js +1 -0
- package/dist/chunks/{operations-catalog-BV65bfY8.js → operations-catalog-D_8difUe.js} +1 -1
- package/dist/chunks/{parse-error-hint-tpmLXK21.js → parse-error-hint-0Xc2T5On.js} +1 -1
- package/dist/chunks/{startup-auth-DIefBEfE.js → startup-auth-BuGIFRmd.js} +1 -1
- package/dist/chunks/{startup-auth-DVq1dO3o.js → startup-auth-DfEgkGG8.js} +1 -1
- package/package.json +3 -3
- package/dist/chunks/logout-oTmMJssP.js +0 -1
- package/dist/chunks/oauth-bearer-credential-DvY2H2LR.js +0 -1
- package/dist/chunks/operations-catalog-BfuHbIDu.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{enableCompileCache as e}from"node:module";import{fileURLToPath as t}from"node:url";e();var{Command:n,CommanderError:r}=await import(`../chunks/commander-D8IVfzyC.js`),{readRuntimePackage:i}=await import(`../chunks/package-DcUsOdSE.js`),{locateRuntimeManifest:a}=await import(`../chunks/runtime-identity-BXcpCMqz.js`),o=process.argv.slice(2);try{if(a(),o.length===1&&(o[0]===`--version`||o[0]===`-V`))await new n().exitOverride().version(i(t(import.meta.url)).version).parseAsync();else{let{logWarn:e,setStderrLogging:t}=await import(`../chunks/logging-CNg4ihxv.js`),{cliMachineOutputSelected:n}=await import(`../chunks/output-mode-U1V43dYf.js`),{commandAuthMaterializationMode:r,materializeCommandCredential:a}=await import(`../chunks/startup-auth-
|
|
2
|
+
import{enableCompileCache as e}from"node:module";import{fileURLToPath as t}from"node:url";e();var{Command:n,CommanderError:r}=await import(`../chunks/commander-D8IVfzyC.js`),{readRuntimePackage:i}=await import(`../chunks/package-DcUsOdSE.js`),{locateRuntimeManifest:a}=await import(`../chunks/runtime-identity-BXcpCMqz.js`),o=process.argv.slice(2);try{if(a(),o.length===1&&(o[0]===`--version`||o[0]===`-V`))await new n().exitOverride().version(i(t(import.meta.url)).version).parseAsync();else{let{logWarn:e,setStderrLogging:t}=await import(`../chunks/logging-CNg4ihxv.js`),{cliMachineOutputSelected:n}=await import(`../chunks/output-mode-U1V43dYf.js`),{commandAuthMaterializationMode:r,materializeCommandCredential:a}=await import(`../chunks/startup-auth-DfEgkGG8.js`),{GENERATED_OPENAPI_COMMAND_SPECS:s}=await import(`../chunks/openapi-commands-CHYNuWml.js`),{withRenamedCommandAliases:c}=await import(`../chunks/deprecated-command-BBCr1BHb.js`);if(n(o)&&t(!1),o.includes(`--all-fields`)){let{setTextAllFields:e}=await import(`../chunks/text-field-BDYE-wQt.js`);e(!0)}let l=r(o,c(s));if(l===`stored`||l===`optional`)try{await a(l)}catch(t){e({component:i().bin[0],event:`optional_auth_materialization_failed`,message:`saved credential unavailable; continuing with credential-optional command`,error:t})}await import(`../chunks/aventure-cli-SEyW_1AB.js`)}}catch(e){if(!(e instanceof r))throw e;e.code!==`commander.version`&&process.stderr.write(`${e.message}\n`),process.exitCode=e.exitCode}export{};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
3
|
"generatedFrom": "MCP_GENERATION_CONTRACT",
|
|
4
|
-
"generatedAt": "2026-11-
|
|
4
|
+
"generatedAt": "2026-11-07T13:54:21.399Z",
|
|
5
5
|
"totalOperations": 132,
|
|
6
6
|
"note": "1:1 projection of MCP_GENERATION_CONTRACT written by the CLI build ([MCP1b.1-EXC1]).",
|
|
7
7
|
"operations": [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as e}from"./env-DGAe95Xm.js";import{n as t,s as n}from"./openapi-call-
|
|
1
|
+
import{f as e}from"./env-DGAe95Xm.js";import{n as t,s as n}from"./openapi-call-DRowSHyQ.js";import{a as r}from"./api-target-vxev2RKl.js";import{a as i,i as a,o,s}from"./api-key-credential-v7YT_b1y.js";import{n as c,t as l}from"./credential-redaction-Cl6Eny3X.js";async function u(e){if(e.activation===`revoking`)return{lookup:await a(e.host),verification:null};let t=await d(e.credential.secret);try{if(t.state===`verified`&&e.activation===`active`){let n=await o(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`,{state:`found`,stored:e});return n.state===`saved`?{lookup:{state:`found`,stored:n.stored},verification:t}:{lookup:n.current,verification:null}}}catch(n){t={state:`unavailable`,summary:`${t.summary}, but the cached metadata could not be updated — ${l(n,[e.credential.secret])}`}}let n;try{n=await a(e.host)}catch(t){return{lookup:{state:`unavailable`,cause:`storage`,summary:l(t,[e.credential.secret])},verification:null}}return{lookup:n,verification:n.state===`found`&&i(n.stored,e)?t:null}}async function d(i){let a=r(e()),o;try{o=await n(a,{method:`GET`,path:t(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${i}`}},s)}catch(e){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${l(e,[i])}`}}return o.ok&&o.redirect?{state:`unavailable`,summary:`identity verification returned unexpected redirect ${o.status}`}:o.ok?o.data.status===`ACTIVE`?{state:`verified`,summary:`API key verified by aVenture sign-in`,apiKey:o.data}:{state:`invalid`,summary:`API key is not active`}:{state:o.problem.type!==`about:blank`&&o.problem.status===401?`invalid`:`unavailable`,summary:`identity verification: ${c(o.problem,[i])}`}}export{d as n,u as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{t as refreshStoredApiKeyCredential}from"./api-key-credential-verification-
|
|
1
|
+
export{t as refreshStoredApiKeyCredential}from"./api-key-credential-verification-C_DQtQyx.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e}from"./package-DEeHDoOT.js";import{A as t,E as n,S as r,_ as i,g as a,i as o,n as s}from"./iso-DzqMxtky.js";import{f as c}from"./env-DGAe95Xm.js";import{c as l,r as u}from"./result-envelope-BMqcRDpc.js";import{z as d}from"./tool-policy-DG8pafmI.js";import{s as f,u as p}from"./openapi-call-DrJ9I2I1.js";import{i as m}from"./response-problem-Dr3Yy1lJ.js";import{a as h,r as g,t as ee}from"./api-target-vxev2RKl.js";import{n as _,o as v,r as te,t as ne}from"./api-key-credential-v7YT_b1y.js";import{n as re,t as y}from"./credential-redaction-Cl6Eny3X.js";import{c as b,l as x,n as S,u as C}from"./credential-store-xkwn77zF.js";import{n as w}from"./api-key-credential-verification-CJ5CCGAA.js";import{n as T}from"./contract-SAu4Y_Kd.js";import{t as E}from"./openapi-composites-IdxI7cAF.js";import{n as ie}from"./logout-Du693hU1.js";import{stderr as D,stdin as ae}from"node:process";import{TextDecoder as oe,inspect as se}from"node:util";import{hostname as ce,platform as le}from"node:os";import{setTimeout as ue}from"node:timers/promises";import{webcrypto as O}from"node:crypto";var k=o([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),A=o([`RSA_OAEP_256_A256_GCM_V1`]),de=i({clientLabel:r().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:k.nullish(),encryptionAlgorithm:A.nullish(),encryptionPublicKey:r().min(344).max(12e3).nullish()}),fe=32;async function pe(){let e=await O.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await O.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function me(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=j(n,`wrapped key`,128,1024),s=j(r,`nonce`,12,12),c=j(i,`ciphertext`,1,65536),l=j(a,`authentication tag`,16,16),u;try{u=await O.subtle.decrypt({name:`RSA-OAEP`},e,o)}catch{throw Error(`broker credential key could not be decrypted`)}let d=new Uint8Array(u);try{if(d.byteLength!==fe)throw Error(`broker credential used an invalid AES-256 key`);let e=await O.subtle.importKey(`raw`,d,{name:`AES-GCM`},!1,[`decrypt`]),t=new Uint8Array(c.byteLength+l.byteLength);t.set(c),t.set(l,c.byteLength);let n;try{n=await O.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new oe(`utf-8`,{fatal:!0}).decode(n);if(r.trim().length===0)throw Error(`broker returned a blank credential`);return r}finally{d.fill(0)}}function j(e,t,n,r){let i=e.replace(/=+$/u,``),a=Uint8Array.from(Buffer.from(e,`base64`)),o=Buffer.from(a).toString(`base64`).replace(/=+$/u,``);if(i.length===0||o!==i||a.byteLength<n||a.byteLength>r)throw Error(`broker returned an invalid ${t}`);return a}var M=o([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),N=o([`Denied by user`,`Authorization request expired`,`CLI authorization expired before acknowledgement`,`Credential issuance recovery revoked an unrecoverable key`,`Revoked by user`,`Clerk create response validation failed`,`Credential issuance failed`,`Credential issuance could not be recovered`,`API-key quota reached`,`Credential issuance lost its database claim`,`Credential delivery encryption failed`,`Credential issuance finalization was lost`]),P=i({approvedAt:s({offset:!0}).nullish(),clientLabel:r(),clientPlatform:k,comparisonCode:r(),consumedAt:s({offset:!0}).nullish(),createdAt:s({offset:!0}),expiresAt:s({offset:!0}),id:n(),intervalSeconds:a().int().min(1),keyReadyAt:s({offset:!0}).nullish(),status:M,terminalAt:s({offset:!0}).nullish(),terminalReason:N.nullish(),updatedAt:s({offset:!0})}),F=i({algorithm:A,authenticationTag:r(),ciphertext:r(),nonce:r(),wrappedKey:r()}),I=i({delivery:F.nullish(),expiresAt:s({offset:!0}),status:M,terminalReason:N.nullish()}),L=i({comparisonCode:r(),expiresAt:s({offset:!0}),id:n(),intervalSeconds:a().int().min(1),pollSecret:r(),verificationUrl:r()}),R=T(E,`start`),z=T(E,`poll`),B=T(E,`acknowledge`),V=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${re(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=ve(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},H=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${y(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function he(e){let t=await f(h(c()),{method:R.method,path:d(R.path,{},R.operationId),headers:{},contentType:`application/json`,body:e},L);if(t.ok&&t.redirect)throw new V(`start`,W(t.status));if(!t.ok)throw new V(`start`,t.problem);return ye(t.data)}async function ge(e,t){let n=p(z.operationId),r=await f(h(c()),{method:z.method,path:d(z.path,{cliAuthorizationId:e},z.operationId),headers:{[n]:t}},I);if(r.ok&&r.redirect)throw new V(`poll`,W(r.status),[t]);if(!r.ok)throw new V(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:_e(r.headers[`retry-after`])}}async function U(e,t){let n=p(B.operationId),r;try{r=await f(h(c()),{method:B.method,path:d(B.path,{cliAuthorizationId:e},B.operationId),headers:{[n]:t}},P)}catch(e){throw new H(`acknowledge`,e,[t])}if(r.ok&&r.redirect)throw new V(`acknowledge`,W(r.status),[t]);if(!r.ok)throw new V(`acknowledge`,r.problem,[t]);return r.data}function _e(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function ve(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function W(e){return{status:e,title:`Unexpected redirect`,type:`about:blank`,code:void 0,detail:`CLI authorization endpoint returned an unexpected redirect`}}function ye(e){let{verificationUrl:t,pollSecret:n,...r}=e,i={...e},a=()=>({...r,verificationUrl:`<redacted>`,pollSecret:`<redacted>`});return Object.defineProperties(i,{verificationUrl:{enumerable:!1,get:()=>t},pollSecret:{enumerable:!1,get:()=>n},toJSON:{enumerable:!1,value:a},toString:{enumerable:!1,value:()=>`CliAuthorizationStart(${JSON.stringify(a())})`},[se.custom]:{enumerable:!1,value:a}})}var G=`RSA_OAEP_256_A256_GCM_V1`,be=1,xe=30,K=e().bin[0],q=`The local record remains pending and unavailable to ordinary commands. Re-run \`${K} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Se(e){if(!ae.isTTY)return u(`${K} auth login --key requires an interactive TTY on stdin`,[`For non-interactive automation, inject AUTH_TOKEN through the environment.`]);let n,r;try{let e=c().host;n=g(e),r=ee(e)}catch(e){return u(`auth login --key: invalid environment configuration — ${y(e)}`)}for(;;){let e;try{e=await te(n)}catch(e){return u(`auth login --key: credential storage could not be inspected — ${y(e)}`)}if(e.state===`unavailable`)return u(`auth login --key: ${e.summary}`,[`Make the OS keyring or the CLI config directory writable, or use AUTH_TOKEN from the environment.`]);if(e.state===`missing`){let t=S(e.keyringFailure);t!==null&&D.write(t);break}let t=await Ce(e.stored);if(t!==null)return t}let i;try{i=await pe()}catch(e){return u(`auth login --key: ephemeral encryption key could not be created — ${y(e)}`)}let a=de.safeParse({clientLabel:e.clientLabel?.trim()||(ce().trim()||K).slice(0,120),clientPlatform:Ee(),encryptionAlgorithm:G,encryptionPublicKey:i.publicKey});if(!a.success)return u(`auth login --key: ${t(a.error)}`);let o;try{o=await he(a.data)}catch(e){return u(`auth login --key: could not start browser authorization — ${y(e)}`)}let s;try{s=C(o,r)}catch(e){return u(`auth login --key: unsafe browser authorization URL rejected — ${y(e)}`)}let l=await b(o,r,{noBrowser:e.noBrowser});if(!x(l,o,s))return u(`auth login --key: browser authorization requires an interactive terminal for manual handoff`,[`Automatic browser opening did not complete, and the approval URL was withheld because stderr is not an interactive terminal. Retry from an interactive terminal.`],{references:[s]});let d;try{d=await Te(o)}catch(e){return u(`auth login --key: authorization did not complete — ${y(e)}`,[],{references:[s]})}if(d.algorithm!==G)return u(`auth login --key: broker selected an unsupported encryption algorithm`);let f;try{f=await me(i.privateKey,d)}catch(e){return u(`auth login --key: encrypted credential could not be opened — ${y(e)}`)}let p=await w(f);if(p.state!==`verified`)return u(`auth login --key: decrypted credential was neither stored nor acknowledged — ${p.summary}`);let m;try{let e=await v(n,{apiKey:p.apiKey,secret:f},`pending`,{state:`missing`});if(e.state===`changed`)return u(`auth login --key: local credential changed; delivery was not stored or acknowledged. Re-run auth status.`);m=e.stored}catch(e){return u(`auth login --key: credential could not be durably stored — ${y(e)}`)}let h;try{h=await we(o)}catch(e){return Q(m,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${y(e,[o.pollSecret])}`,q)}if(h.status!==`CONSUMED`)return Q(m,!0,`auth login --key: broker returned ${h.status} after acknowledgment`,q);let _=await w(f);return _.state!==`verified`||!$(_.apiKey,m.credential.apiKey)?Q(m,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${_.summary}`,q):await J(m,_.apiKey,`acknowledgment`)}async function Ce(e){let t=e.activation===`revoking`?{state:`invalid`,summary:`Local revocation is pending`}:await w(e.credential.secret);if(e.activation===`active`)return t.state===`verified`?l(`API key is already stored and its authenticated identity was verified.`,Z(e,!0),{ids:[e.credential.apiKey.id]}):Q(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${K} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&$(t.apiKey,e.credential.apiKey))return await J(e,t.apiKey,`recovery`);if(t.state===`unavailable`||t.state===`verified`&&!e.credential.apiKey.expiresAt)return Q(e,t.state===`verified`,`auth login --key: the stored pending credential acknowledgment could not be verified — ${t.summary}`,t.state===`verified`?`The stored expiry is missing. Both records were preserved; inspect the existing key in your account before deciding how to recover it.`:`The stored record and the remote key were both preserved. Re-run \`${K} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);try{if(e.activation===`pending`){let t=await v(e.host,e.credential,`revoking`,{state:`found`,stored:e});if(t.state===`changed`)return null;e=t.stored}let t=await ie(e);if(t.outcome===`unconfirmed`)return Q(e,!1,`auth login --key: credential revocation remains pending`,`Remote revocation was not confirmed — ${t.summary}. Retry auth login --key when the API is reachable.`);if((await _(e)).state===`changed`)return null;D.write(t.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
|
|
1
|
+
import{a as e}from"./package-DEeHDoOT.js";import{A as t,E as n,S as r,_ as i,g as a,i as o,n as s}from"./iso-DzqMxtky.js";import{f as c}from"./env-DGAe95Xm.js";import{c as l,r as u}from"./result-envelope-BMqcRDpc.js";import{z as d}from"./tool-policy-DG8pafmI.js";import{s as f,u as p}from"./openapi-call-DRowSHyQ.js";import{i as m}from"./response-problem-Dr3Yy1lJ.js";import{a as h,r as g,t as ee}from"./api-target-vxev2RKl.js";import{n as _,o as v,r as te,t as ne}from"./api-key-credential-v7YT_b1y.js";import{n as re,t as y}from"./credential-redaction-Cl6Eny3X.js";import{c as b,l as x,n as S,u as C}from"./credential-store-xkwn77zF.js";import{n as w}from"./api-key-credential-verification-C_DQtQyx.js";import{n as T}from"./contract-SAu4Y_Kd.js";import{t as E}from"./openapi-composites-IdxI7cAF.js";import{n as ie}from"./logout-Dxt8vao3.js";import{stderr as D,stdin as ae}from"node:process";import{TextDecoder as oe,inspect as se}from"node:util";import{hostname as ce,platform as le}from"node:os";import{setTimeout as ue}from"node:timers/promises";import{webcrypto as O}from"node:crypto";var k=o([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),A=o([`RSA_OAEP_256_A256_GCM_V1`]),de=i({clientLabel:r().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:k.nullish(),encryptionAlgorithm:A.nullish(),encryptionPublicKey:r().min(344).max(12e3).nullish()}),fe=32;async function pe(){let e=await O.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await O.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function me(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=j(n,`wrapped key`,128,1024),s=j(r,`nonce`,12,12),c=j(i,`ciphertext`,1,65536),l=j(a,`authentication tag`,16,16),u;try{u=await O.subtle.decrypt({name:`RSA-OAEP`},e,o)}catch{throw Error(`broker credential key could not be decrypted`)}let d=new Uint8Array(u);try{if(d.byteLength!==fe)throw Error(`broker credential used an invalid AES-256 key`);let e=await O.subtle.importKey(`raw`,d,{name:`AES-GCM`},!1,[`decrypt`]),t=new Uint8Array(c.byteLength+l.byteLength);t.set(c),t.set(l,c.byteLength);let n;try{n=await O.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new oe(`utf-8`,{fatal:!0}).decode(n);if(r.trim().length===0)throw Error(`broker returned a blank credential`);return r}finally{d.fill(0)}}function j(e,t,n,r){let i=e.replace(/=+$/u,``),a=Uint8Array.from(Buffer.from(e,`base64`)),o=Buffer.from(a).toString(`base64`).replace(/=+$/u,``);if(i.length===0||o!==i||a.byteLength<n||a.byteLength>r)throw Error(`broker returned an invalid ${t}`);return a}var M=o([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),N=o([`Denied by user`,`Authorization request expired`,`CLI authorization expired before acknowledgement`,`Credential issuance recovery revoked an unrecoverable key`,`Revoked by user`,`Clerk create response validation failed`,`Credential issuance failed`,`Credential issuance could not be recovered`,`API-key quota reached`,`Credential issuance lost its database claim`,`Credential delivery encryption failed`,`Credential issuance finalization was lost`]),P=i({approvedAt:s({offset:!0}).nullish(),clientLabel:r(),clientPlatform:k,comparisonCode:r(),consumedAt:s({offset:!0}).nullish(),createdAt:s({offset:!0}),expiresAt:s({offset:!0}),id:n(),intervalSeconds:a().int().min(1),keyReadyAt:s({offset:!0}).nullish(),status:M,terminalAt:s({offset:!0}).nullish(),terminalReason:N.nullish(),updatedAt:s({offset:!0})}),F=i({algorithm:A,authenticationTag:r(),ciphertext:r(),nonce:r(),wrappedKey:r()}),I=i({delivery:F.nullish(),expiresAt:s({offset:!0}),status:M,terminalReason:N.nullish()}),L=i({comparisonCode:r(),expiresAt:s({offset:!0}),id:n(),intervalSeconds:a().int().min(1),pollSecret:r(),verificationUrl:r()}),R=T(E,`start`),z=T(E,`poll`),B=T(E,`acknowledge`),V=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${re(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=ve(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},H=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${y(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function he(e){let t=await f(h(c()),{method:R.method,path:d(R.path,{},R.operationId),headers:{},contentType:`application/json`,body:e},L);if(t.ok&&t.redirect)throw new V(`start`,W(t.status));if(!t.ok)throw new V(`start`,t.problem);return ye(t.data)}async function ge(e,t){let n=p(z.operationId),r=await f(h(c()),{method:z.method,path:d(z.path,{cliAuthorizationId:e},z.operationId),headers:{[n]:t}},I);if(r.ok&&r.redirect)throw new V(`poll`,W(r.status),[t]);if(!r.ok)throw new V(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:_e(r.headers[`retry-after`])}}async function U(e,t){let n=p(B.operationId),r;try{r=await f(h(c()),{method:B.method,path:d(B.path,{cliAuthorizationId:e},B.operationId),headers:{[n]:t}},P)}catch(e){throw new H(`acknowledge`,e,[t])}if(r.ok&&r.redirect)throw new V(`acknowledge`,W(r.status),[t]);if(!r.ok)throw new V(`acknowledge`,r.problem,[t]);return r.data}function _e(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function ve(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function W(e){return{status:e,title:`Unexpected redirect`,type:`about:blank`,code:void 0,detail:`CLI authorization endpoint returned an unexpected redirect`}}function ye(e){let{verificationUrl:t,pollSecret:n,...r}=e,i={...e},a=()=>({...r,verificationUrl:`<redacted>`,pollSecret:`<redacted>`});return Object.defineProperties(i,{verificationUrl:{enumerable:!1,get:()=>t},pollSecret:{enumerable:!1,get:()=>n},toJSON:{enumerable:!1,value:a},toString:{enumerable:!1,value:()=>`CliAuthorizationStart(${JSON.stringify(a())})`},[se.custom]:{enumerable:!1,value:a}})}var G=`RSA_OAEP_256_A256_GCM_V1`,be=1,xe=30,K=e().bin[0],q=`The local record remains pending and unavailable to ordinary commands. Re-run \`${K} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Se(e){if(!ae.isTTY)return u(`${K} auth login --key requires an interactive TTY on stdin`,[`For non-interactive automation, inject AUTH_TOKEN through the environment.`]);let n,r;try{let e=c().host;n=g(e),r=ee(e)}catch(e){return u(`auth login --key: invalid environment configuration — ${y(e)}`)}for(;;){let e;try{e=await te(n)}catch(e){return u(`auth login --key: credential storage could not be inspected — ${y(e)}`)}if(e.state===`unavailable`)return u(`auth login --key: ${e.summary}`,[`Make the OS keyring or the CLI config directory writable, or use AUTH_TOKEN from the environment.`]);if(e.state===`missing`){let t=S(e.keyringFailure);t!==null&&D.write(t);break}let t=await Ce(e.stored);if(t!==null)return t}let i;try{i=await pe()}catch(e){return u(`auth login --key: ephemeral encryption key could not be created — ${y(e)}`)}let a=de.safeParse({clientLabel:e.clientLabel?.trim()||(ce().trim()||K).slice(0,120),clientPlatform:Ee(),encryptionAlgorithm:G,encryptionPublicKey:i.publicKey});if(!a.success)return u(`auth login --key: ${t(a.error)}`);let o;try{o=await he(a.data)}catch(e){return u(`auth login --key: could not start browser authorization — ${y(e)}`)}let s;try{s=C(o,r)}catch(e){return u(`auth login --key: unsafe browser authorization URL rejected — ${y(e)}`)}let l=await b(o,r,{noBrowser:e.noBrowser});if(!x(l,o,s))return u(`auth login --key: browser authorization requires an interactive terminal for manual handoff`,[`Automatic browser opening did not complete, and the approval URL was withheld because stderr is not an interactive terminal. Retry from an interactive terminal.`],{references:[s]});let d;try{d=await Te(o)}catch(e){return u(`auth login --key: authorization did not complete — ${y(e)}`,[],{references:[s]})}if(d.algorithm!==G)return u(`auth login --key: broker selected an unsupported encryption algorithm`);let f;try{f=await me(i.privateKey,d)}catch(e){return u(`auth login --key: encrypted credential could not be opened — ${y(e)}`)}let p=await w(f);if(p.state!==`verified`)return u(`auth login --key: decrypted credential was neither stored nor acknowledged — ${p.summary}`);let m;try{let e=await v(n,{apiKey:p.apiKey,secret:f},`pending`,{state:`missing`});if(e.state===`changed`)return u(`auth login --key: local credential changed; delivery was not stored or acknowledged. Re-run auth status.`);m=e.stored}catch(e){return u(`auth login --key: credential could not be durably stored — ${y(e)}`)}let h;try{h=await we(o)}catch(e){return Q(m,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${y(e,[o.pollSecret])}`,q)}if(h.status!==`CONSUMED`)return Q(m,!0,`auth login --key: broker returned ${h.status} after acknowledgment`,q);let _=await w(f);return _.state!==`verified`||!$(_.apiKey,m.credential.apiKey)?Q(m,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${_.summary}`,q):await J(m,_.apiKey,`acknowledgment`)}async function Ce(e){let t=e.activation===`revoking`?{state:`invalid`,summary:`Local revocation is pending`}:await w(e.credential.secret);if(e.activation===`active`)return t.state===`verified`?l(`API key is already stored and its authenticated identity was verified.`,Z(e,!0),{ids:[e.credential.apiKey.id]}):Q(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${K} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&$(t.apiKey,e.credential.apiKey))return await J(e,t.apiKey,`recovery`);if(t.state===`unavailable`||t.state===`verified`&&!e.credential.apiKey.expiresAt)return Q(e,t.state===`verified`,`auth login --key: the stored pending credential acknowledgment could not be verified — ${t.summary}`,t.state===`verified`?`The stored expiry is missing. Both records were preserved; inspect the existing key in your account before deciding how to recover it.`:`The stored record and the remote key were both preserved. Re-run \`${K} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);try{if(e.activation===`pending`){let t=await v(e.host,e.credential,`revoking`,{state:`found`,stored:e});if(t.state===`changed`)return null;e=t.stored}let t=await ie(e);if(t.outcome===`unconfirmed`)return Q(e,!1,`auth login --key: credential revocation remains pending`,`Remote revocation was not confirmed — ${t.summary}. Retry auth login --key when the API is reachable.`);if((await _(e)).state===`changed`)return null;D.write(t.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
|
|
2
2
|
`:`Cleared a stale pending CLI credential whose remote key can no longer authenticate; starting a fresh browser authorization.
|
|
3
3
|
`)}catch(t){return Q(e,!1,`auth login --key: stale pending credential could not be removed — ${y(t,[e.credential.secret])}`)}return null}async function J(e,t,n){try{let r=await v(e.host,{apiKey:t,secret:e.credential.secret},`active`,{state:`found`,stored:e});return r.state===`changed`?u(`auth login --key: local credential changed ${n===`recovery`?`during recovery`:`after acknowledgment`}; current state preserved. Re-run auth status.`):l(n===`recovery`?`Recovered pending CLI credential: broker acknowledgment had succeeded.`:`API key stored; authenticated identity and broker acknowledgment verified.`,Z(r.stored,!0),{ids:[r.stored.credential.apiKey.id]})}catch(t){return Q(e,!0,`auth login --key: ${n===`recovery`?`credential is valid but could not be promoted locally`:`remote acknowledgment succeeded, but local activation could not be confirmed`} — ${y(t,[e.credential.secret])}`,q)}}async function we(e){let t=new Date(e.expiresAt).getTime(),n=Y(e.intervalSeconds);for(;;)try{return await U(e.id,e.pollSecret)}catch(e){if(e instanceof V){if(!e.retryable)throw e;n=Y(e.retryAfterSeconds??n)}else if(!(e instanceof H))throw e;if(Date.now()>=t)throw e;D.write(`Broker acknowledgment was interrupted; retrying.
|
|
4
4
|
`),await X(n,t)}}async function Te(e){let t=new Date(e.expiresAt).getTime(),n=Y(e.intervalSeconds),r;for(D.write(`Waiting for browser approval...
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e}from"./package-DEeHDoOT.js";import{t}from"./credential-redaction-Cl6Eny3X.js";import{n,t as r}from"./openapi-commands-B2dIDk9o.js";var i=[{name:`cli-version`,purpose:`running CLI against the latest published release`},{name:`api-schemas`,purpose:`the installed @aventurevc/api-schemas contracts resolve`},{name:`api-host`,purpose:`the selected API host answers GET /info`},{name:`auth`,purpose:`a credential materialized for the next command, never its secret`},{name:`catalog`,purpose:`this CLI knows every operation the API serves`}];function a(e,t,n){return{name:e,status:t,message:n}}async function o(e){let t=l(),n=await u(e),[r,i]=await Promise.all([d(e),t===void 0?null:f(t)]);return{cliVersion:n.check,apiSchemas:r,catalog:m(i,n.upgradeAvailable,e)}}function s(e,t,n){return e.ok?a(`api-host`,`pass`,`GET /info answered at ${t}.`):a(`api-host`,`fail`,e.httpStatus===401?`Replace or unset the credential ${t} rejected, or run \`${n} auth login\`, then rerun \`${n} auth status\` — GET /info returned ${e.summary}.`:`Point the CLI at a reachable API host with \`--environment <name>\` or API_URL, then rerun \`${n} auth status\` — GET /info at ${t} returned ${e.summary}.`)}function c(e,t,n){let r=[e.cliVersion,e.apiSchemas,t,n,e.catalog];return{ok:r.every(e=>e.status!==`fail`),check:r}}function l(){return r.find(e=>e.intent===`status`&&e.resource===`status`)}async function u(t){let{runUpdate:n}=await import(`./builtin-update-DJT_3I5O.js`),r=e(),i=n(r,`check`);if(!i.ok||i.data===null)return{check:a(`cli-version`,`skip`,`Could not compare ${r.version} against the registry (${i.summary}); rerun \`${t} update\` with registry access.`),upgradeAvailable:null};let{targetPackage:o,currentVersion:s,latestVersion:c,upgradeAvailable:l}=i.data;return{check:l?a(`cli-version`,`fail`,`Upgrade ${o} from ${s} to ${c}: run \`${t} update\`.`):a(`cli-version`,`pass`,`${o} ${s} matches the latest published release.`),upgradeAvailable:l}}async function d(e){try{let{EntityDetailSchema:e}=await import(`./detail-BJehaxuo.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return a(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(n){return a(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${t(n)}.`)}}async function f(e){let{runOpenApiCall:n}=await import(`./openapi-call-
|
|
1
|
+
import{a as e}from"./package-DEeHDoOT.js";import{t}from"./credential-redaction-Cl6Eny3X.js";import{n,t as r}from"./openapi-commands-B2dIDk9o.js";var i=[{name:`cli-version`,purpose:`running CLI against the latest published release`},{name:`api-schemas`,purpose:`the installed @aventurevc/api-schemas contracts resolve`},{name:`api-host`,purpose:`the selected API host answers GET /info`},{name:`auth`,purpose:`a credential materialized for the next command, never its secret`},{name:`catalog`,purpose:`this CLI knows every operation the API serves`}];function a(e,t,n){return{name:e,status:t,message:n}}async function o(e){let t=l(),n=await u(e),[r,i]=await Promise.all([d(e),t===void 0?null:f(t)]);return{cliVersion:n.check,apiSchemas:r,catalog:m(i,n.upgradeAvailable,e)}}function s(e,t,n){return e.ok?a(`api-host`,`pass`,`GET /info answered at ${t}.`):a(`api-host`,`fail`,e.httpStatus===401?`Replace or unset the credential ${t} rejected, or run \`${n} auth login\`, then rerun \`${n} auth status\` — GET /info returned ${e.summary}.`:`Point the CLI at a reachable API host with \`--environment <name>\` or API_URL, then rerun \`${n} auth status\` — GET /info at ${t} returned ${e.summary}.`)}function c(e,t,n){let r=[e.cliVersion,e.apiSchemas,t,n,e.catalog];return{ok:r.every(e=>e.status!==`fail`),check:r}}function l(){return r.find(e=>e.intent===`status`&&e.resource===`status`)}async function u(t){let{runUpdate:n}=await import(`./builtin-update-DJT_3I5O.js`),r=e(),i=n(r,`check`);if(!i.ok||i.data===null)return{check:a(`cli-version`,`skip`,`Could not compare ${r.version} against the registry (${i.summary}); rerun \`${t} update\` with registry access.`),upgradeAvailable:null};let{targetPackage:o,currentVersion:s,latestVersion:c,upgradeAvailable:l}=i.data;return{check:l?a(`cli-version`,`fail`,`Upgrade ${o} from ${s} to ${c}: run \`${t} update\`.`):a(`cli-version`,`pass`,`${o} ${s} matches the latest published release.`),upgradeAvailable:l}}async function d(e){try{let{EntityDetailSchema:e}=await import(`./detail-BJehaxuo.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return a(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(n){return a(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${t(n)}.`)}}async function f(e){let{runOpenApiCall:n}=await import(`./openapi-call-Gchy3s8a.js`),r=`${e.method} ${e.path}`;try{let t=await n({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`});if(!t.ok)return{unread:`${r} returned ${t.summary}`};let i=p(t.data);return i===null?{unread:`${r} carried no operationFingerprint`}:{fingerprint:i}}catch(e){return{unread:`${r} failed: ${t(e)}`}}}function p(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)return null;let{response:t}=e;if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t.operationFingerprint;return typeof n==`string`&&n.length>0?n:null}function m(e,t,i){let o=r.length;if(e===null)return a(`catalog`,`skip`,`The public catalog omits deployment-status metadata and holds ${o} operations.`);if(`unread`in e)return a(`catalog`,`skip`,`Could not read the served operation fingerprint (${e.unread}), so drift is unproven; this catalog holds ${o} operations at ${n}.`);let s=e.fingerprint;if(s===`de32de01d813865c`)return a(`catalog`,`pass`,`${o} generated operations match the set the API serves (${n}).`);let c=`This catalog describes a different operation set than the API serves (${n} vs ${s})`;return t===!0?a(`catalog`,`fail`,`${c}: run \`${i} update\`.`):a(`catalog`,`skip`,t===!1?`${c}, and this CLI is already the latest published release: either the deployed API is older than this CLI, or a newer CLI has not been published yet.`:`${c}, and the registry did not answer, so it is unknown whether a newer release describes it: rerun \`${i} update\` with registry access.`)}export{o as a,a as i,s as n,c as r,i as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{n as apiHostCheck,r as authStatusReport,i as checkResult,a as environmentChecks}from"./auth-status-check-
|
|
1
|
+
export{n as apiHostCheck,r as authStatusReport,i as checkResult,a as environmentChecks}from"./auth-status-check-Cwf6uUZP.js";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{f as e,t}from"./env-DGAe95Xm.js";import{a as n}from"./auth-resolver-CRpJNNB2.js";import{i as r,l as i}from"./openapi-call-
|
|
1
|
+
import{f as e,t}from"./env-DGAe95Xm.js";import{a as n}from"./auth-resolver-CRpJNNB2.js";import{i as r,l as i}from"./openapi-call-DRowSHyQ.js";import{a,i as o}from"./response-problem-Dr3Yy1lJ.js";import{t as s}from"./api-key-credential-v7YT_b1y.js";import{t as c}from"./credential-redaction-Cl6Eny3X.js";import{t as l}from"./api-key-bearer-credential-DpuLoYkG.js";import{a as u,f as d,l as f,s as p}from"./oauth-credential-D5ioBfGK.js";import{t as m}from"./oauth-bearer-credential-CxuQ4uM5.js";async function h(){return null}async function g(e){let t=null,n=e=>{t=e};try{await m(e,n),await l(n)}catch(e){return{materialized:t,failure:c(e)}}return{materialized:t,failure:null}}async function _(e,t,n,i){if(i.failure!==null)return{scope:e,selected:null,identity:null,authorization:null,error:i.failure};let a=null,o=null,s,l=e=>{s=e,o=v(e.credential,i.materialized)};try{let t=await r({method:`POST`,path:`/v1/auth/me/permissions`,body:{operation:[]},auth:e,requesterScope:e,responseFormat:`json`,onAuthPrepared:l});if(!t.ok)throw Error([t.summary,...t.warnings].join(` — `));if(o===null)throw Error(`Live permission probe did not prepare a credential`);if(a=S(t.data),e===`read`)return{scope:e,selected:o,identity:null,authorization:a,error:null};if(s===void 0)throw Error(`Live permission probe did not retain its prepared credential`);let n=await h(e,s);return{scope:e,selected:o,identity:n,authorization:a,error:null}}catch(r){return{scope:e,selected:o,identity:null,authorization:a,error:c(r,y(t,n,s))}}}function v(e,t){if(e===null)return null;let r=t??n().source;if(r===null)throw Error(`Prepared credential has no local provenance`);return{credential:e,source:r}}function y(t,n,r){return[e().userBearerToken,...a(r?.headers??{}),...t.state===`found`?d(t.stored.credential.tokens):[],n.state===`found`?n.stored.credential.secret:void 0]}function b(e,t,n=null){let r=t.state===`found`?t.stored:void 0,i=r?.credential.apiKey.expiresAt??null;return{host:e,present:r!==void 0,provider:r?.provider??null,activation:r===void 0?null:s(r.activation),apiKeyId:r?.credential.apiKey.id??null,subject:r?.credential.apiKey.subject??null,scope:r?.credential.apiKey.scopes??[],name:r===void 0?null:o(r.credential.apiKey.name,[r.credential.secret]),status:r?.credential.apiKey.status??null,expiresAt:i,metadataSource:r===void 0?null:n?.state===`verified`?`clerk`:`store-cache`,live:n===null?null:{state:n.state,summary:n.summary},expiresInDay:w(i),storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function x(e,t){let n=t.state===`found`?t.stored:void 0;return{host:e,present:n!==void 0,provider:n?.provider??null,expiresAt:n?.credential.expiresAt??null,expired:n===void 0?null:u(n.credential),renewable:n===void 0?null:n.credential.tokens.refresh_token!==void 0,identity:n===void 0?null:f(n.credential),client:n?.credential.client??null,storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function S(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)throw Error(`permission probe returned no JSON response`);let t=i.safeParse(e.response);if(!t.success)throw t.error;return t.data}var C=864e5;function w(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/C)}var T=7;function E(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,T)}\u2026${e.slice(-4)}`}var D=13,O=14;function k(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.apiKey.host}`+(e.apiVersion===null?` (api build unavailable)`:` (api ${e.apiVersion})`),``,...N(e.oauth,e.cliName,e.refresh),...F(e.apiKey,e.oauth,e.cliName,e.apiKeyPhase),``,j(`Providers`,R(e.providers)),j(`Environment`,z(e.resolved)),j(`Selected`,B(e.resolved,e.refresh,e.cliName)),...A(e.live)].join(`
|
|
2
2
|
`)}function A(e){if(e===null)return[];let t=M(`local credential provenance was captured before verification`);if(e.error!==null)return[``,j(`Live probe`,`${e.scope} permission probe failed`),t,M(e.error)];if(e.authorization===null)return[];let n=e.authorization.permissionGrant,r=e.identity;return[``,j(`Live probe`,`${e.scope} permission probe succeeded`),t,M(`operation access ${e.authorization.operationAccess}; ${n.role.length} role; ${n.permission.length} permission`),...r===null?[M(e.scope===`read`?`identity not requested for a read-scope credential`:`identity unavailable in this build`)]:[j(`Live account`,r.nameFull??r.email??r.clerkUserId??r.id)],M(`no API operation was executed or individually authorized`)]}function j(e,t){return` ${e.padEnd(D)}${t}`}function M(e){return` ${``.padEnd(D)}${e}`}function N(e,t,n){switch(e.state){case`found`:{let{credential:r,provider:i}=e.stored,a=f(r);return[j(`OAuth`,`${a.email??a.subject??`unknown identity`} via ${i}`),M(P(r,t,n))]}case`missing`:return[j(`OAuth`,`none stored`),...e.keyringFailure===void 0?[]:[M(`OS keyring unusable — login stores to file: ${e.keyringFailure}`)]];case`unavailable`:return[j(`OAuth`,`storage unavailable: ${e.summary}`)];case`invalid`:return[j(`OAuth`,`stored credential invalid: ${e.summary}`)];default:throw Error(`Unsupported OAuth credential state`)}}function P(e,t,n){return u(e)?e.tokens.refresh_token===void 0?`access token expired — run \`${t} auth login\``:n.failure===null?n.materialized===`api-key`?`access token expired and renewal failed; the API key is in use — \`${t} auth login\` renews OAuth`:`access token expired — not renewed while AUTH_TOKEN is set in the environment`:`access token expired — ${n.failure}`:`access token valid until ${e.expiresAt}`}function F(e,t,n,r){if(!e.present){if(t.state===`found`)return[];let r=e.storageFailure??(t.state===`unavailable`?t.summary:null);return r===null?[j(`Signed in`,`no \u2014 run \`${n} auth login\``),...e.error===null?[]:[M(`stored credential invalid: ${e.error}`)]]:[j(`Signed in`,`credential storage unavailable`),M(r)]}return[j(t.state===`found`?`API key`:`Signed in`,r===`revoking`?`no — API-key revocation pending`:e.subject??`unknown subject`),M(`via ${e.provider??`unknown store`}`),j(`Key`,`${e.name??`unnamed`} ${E(e.apiKeyId)}`),...I(e,n,r),j(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function I(e,t,n){if(n===`revoking`)return[j(`Key state`,`revocation pending; unavailable to ordinary commands`),M(`run \`${t} auth login --key\` to resume cleanup; it cannot reactivate this key`)];let r=e.live,i=e.expiresInDay,a=e.expiresAt;if(r?.state===`invalid`)return[j(`Key state`,`rejected by aVenture sign-in \u2014 ${r.summary}`),M(`run \`${t} auth logout\`, then \`${t} auth login --key\``)];let o=r?.state===`verified`;return[j(`Key state`,o?`${e.status??`unknown`}, verified by aVenture sign-in now`:`${e.status??`unknown`} when stored`),...a===null||i===null?[M(`no expiry recorded`)]:[M(L(a,i,o?`expires`:`cached expiry`))],...o?[]:[M(r===null?"aVenture sign-in owns the live verdict — `auth status` re-checks it":`aVenture sign-in could not be reached \u2014 ${r.summary}`)]]}function L(e,t,n){let r=e.slice(0,10);return new Date(e).getTime()<=Date.now()?`${n} ${r} passed ${Math.abs(t)}d ago`:t<=O?`${n} ${r}, ${t}d away`:`${n} ${r}`}function R(e){if(e.state===`unavailable`)return`unavailable: ${e.summary}`;let t=e.catalog.oauthClient;return[e.catalog.clerkPublishableKey?`browser sign-in`:`no browser sign-in`,t?`oauth ${p(t).host} client ${t.clientId}`:`no OAuth CLI client`].join(`; `)}function z(e){return`${t.authToken}=${e.present?e.source??`resolved`:`unset`}`}function B(e,n,r){return e.present||n.materialized===`env`?`${t.authToken} from the environment`:n.materialized===`oauth`?`saved OAuth access token`:n.materialized===`api-key`?`saved API key`:`none \u2014 sign in with \`${r} auth login\``}export{b as apiKeyCredentialDiagnostics,_ as inspectLiveAuth,x as oauthCredentialDiagnostics,g as refreshCliCredentials,k as renderAuthStatus};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{a as e,n as t,o as n,r,t as i}from"./commander-DEj7N1b9.js";import{a}from"./package-DEeHDoOT.js";import{a as o,c as s,r as c}from"./env-DGAe95Xm.js";import{c as l,p as u,r as d}from"./result-envelope-BMqcRDpc.js";import{L as f,R as p,o as m,t as h,u as g,y as _}from"./tool-policy-DG8pafmI.js";import{i as v}from"./logging-DYzy2g8p.js";import{r as y,t as b}from"./cli-help-policy-DCn_wXe1.js";import{a as x,c as S,d as ee,f as te,i as C,l as w,m as ne,n as re,p as ie,r as ae,s as oe,t as se,u as ce}from"./startup-auth-DIefBEfE.js";import{t as T}from"./openapi-commands-B2dIDk9o.js";import{g as le,m as ue}from"./help-catalog-PSifyPm6.js";import{n as de,t as fe}from"./operations-metadata-CzOMH0PS.js";import{a as E,i as pe,t as D}from"./output-mode-DIt-t4Fu.js";import{S as me,_ as O,a as he,b as k,c as ge,d as _e,f as ve,g as ye,h as be,i as xe,l as Se,m as A,n as j,o as Ce,p as we,r as Te,s as Ee,t as De,u as Oe,v as M,x as ke,y as N}from"./generated-option-order-DYmytWyF.js";import{n as Ae,t as je}from"./deprecated-command-bF9Q8_F6.js";import{a as Me,i as Ne,n as Pe,r as Fe}from"./payload-operand-guard-Cne4mq9F.js";import{fileURLToPath as Ie}from"node:url";import{readFile as Le}from"node:fs/promises";async function Re(e){let t;try{t=e===`-`?await ze():await Le(e,`utf8`)}catch(t){return d(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return l(`No input provided`,null);let e=JSON.parse(t);return l(`Input parsed`,e)}catch(e){return d(`Input is not valid JSON: ${e.message}`)}}async function ze(){if(process.stdin.isTTY)throw Error(`--from-file - requires JSON on stdin, but stdin is a TTY`);process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}var P=`--content-type`;function Be(e,n,r){let i=e=>!r?.has(e)&&(r?.add(e),!0),a=n.requestBody??[];if(a.length>1&&i(P)){let n=a.map(({contentType:e})=>e);e.addOption(new t(`${P} <media-type>`,`Select the request body encoding, never an uploaded file's media type; omit for ${n[0]}.`).choices(n).argParser(He(a)))}if(z(n)&&i(`--from-file`)){let r=a[0];if(r===void 0)throw Error(`${n.operationId} has no request body`);e.addOption(new t(`--from-file <path>`,he(r,r.requiredPath)).argParser(F(`--from-file`)))}let o=Ce(a).filter(e=>i(I(e.variant[0].parameter)));for(let n of o.toSorted((e,t)=>j(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:r,parameter:i}=n.variant[0],o=new t(xe(n),a.length>1?Te(n):ge(r,i));a.length===1&&i.envName!==void 0&&o.env(i.envName);let s=a.length===1?Ee(r,i.optionKey):[];s.length>0&&o.conflicts(s),a.length>1?o.argParser(Ve):M(i.name)||i.schemaType===`array`?o.argParser(Ue):o.argParser(F(i.flag)),e.addOption(o),o.envVar!==void 0&&e.on(`optionEnv:${o.name()}`,()=>{let t=e.opts()[i.optionKey];typeof t==`string`&&t.trim()&&e.setOptionValueWithSource(i.optionKey,t.trim(),`env`)})}nt(e,n,o)}function Ve(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function He(e){return(t,r)=>{if(r!==void 0)throw new n(`${P} was already given; pass it once.`);let i=_(e,t);if(!i.ok)throw new n(i.summary);return t}}function Ue(e,t){return[...t??[],e]}function F(e){let t=e.split(/\s+/u)[0]??e;return(e,r)=>{if(r!==void 0)throw new n(`${t} was already given; pass it once.`);return e}}async function We(e,t){let n=w(e,t),r=_(e.requestBody??[],n);if(!r.ok||r.data===null)return d(r.summary,r.warnings);let i=r.data;if(i===void 0)return l(`No body`,void 0);let a=Ge(e,i,t);if(a!==null)return d(a);let o=A(e.operationId,i,t);if(!o.ok)return d(o.summary,o.warnings);t=o.data;let s=Ke(i,t);if(s!==null)return d(s);let c=await Xe(t);if(!c.ok)return d(c.summary,c.warnings);let u=be(e.requestBody??[],i,c.data);if(u!==null)return d(u);let f=Ye(e.operationId,i,c.data);if(!f.ok)return f;let p=ye(e.operationId,i,c.data);if(p!==null)return d(p);let m=Ze(e.operationId,i,t);if(!m.ok)return m;if(c.data===void 0&&m.data===void 0)return i.required?d(tt(e.operationId,i)):l(`No body`,void 0);let h=$e(e.operationId,i,c.data,m.data);if(!h.ok||h.data===void 0)return h;if(i.schemaType===`array`&&!Array.isArray(h.data))return d(`${e.operationId} requires a JSON array body.`);if(i.parameter.length>0&&!N(h.data)){let t=i.kind===`multipart`?` keyed by multipart part name`:` body`;return d(`${e.operationId} requires a JSON object${t}.`)}let g=Je(i,h.data);if(g.length>0)return d(`${e.operationId} requires body option(s): ${g.join(`, `)}`);let v=h.data,y=N(v)?k(i).filter(e=>!O(v,e)):[];return y.length>0?d(qe(e.operationId,i,y)):h}function Ge(e,t,n){let r=new Set(t.parameter.map(({optionKey:e})=>e));for(let i of e.requestBody??[])if(i!==t)for(let t of i.parameter){if(r.has(t.optionKey)||n[t.optionKey]===void 0)continue;let i=(e.requestBody??[]).filter(e=>e.parameter.some(({optionKey:e})=>e===t.optionKey)).map(({contentType:e})=>e);return`${I(t)} requires ${P} ${i.join(` or `)}.`}return null}function Ke(e,t){for(let n of e.cliConflicts??[]){let e=n.filter(e=>t[e]!==void 0);if(e.length>1)return`Options ${e.join(`, `)} cannot be used together.`}return null}function qe(e,t,n){let r=`${e} requires JSON body path(s): ${n.join(`, `)}`;return t.kind===`multipart`?`${r}. ${n.includes(`body`)?`For multipart --from-file, wrap the endpoint JSON under top-level "body".`:`For multipart --from-file, put the missing nested path(s) inside top-level "body".`}`:r}function Je(e,t){return N(t)?e.parameter.filter(e=>e.required&&!O(t,e.name)).map(I):[]}function Ye(e,t,n){let r=me(t,n);return r===null?l(`Body file paths validated`,null):d(`${e} --from-file contains ${r.message}`)}async function Xe(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return l(`No body file`,void 0);let n=await Re(t);if(!n.ok)return d(n.summary,n.warnings);let r=u.safeParse(n.data);return r.success?l(`Input parsed`,r.data):d(`Input is not valid JSON value: ${r.error.message}`)}function Ze(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=ke(e,n[e.optionKey]);if(!a.ok||a.data===null)return d(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=Qe(t,n,r,e,o);if(!s.ok)return d(s.summary,s.warnings);i=!0}if(!i)return l(`No direct body options`,void 0);let a=_e(e,t,n,r);return a===null?l(`Direct body options parsed`,r):a}function Qe(e,t,n,r,i){let a=Se(e,t,r);if(a===null){let e=et(r,i);return e.ok?ve(n,r.name,e.data,r.schemaType===`array`):d(e.summary,e.warnings)}let o=Oe(e,t,r,a);if(o!==null)return d(o);let s=r.schemaType===`array`,c=s?r.itemSchemaType:r.schemaType;for(let[e,t]of a.rows){let i=[];for(let e of t){let t=R(r,c,e);if(!t.ok)return d(t.summary,t.warnings);i.push(t.data)}for(let t of s?[i]:i){let i=we(n,r.name,e,t);if(!i.ok)return i}}return l(`Body value assigned`,null)}var I=e=>e.flag.split(` `)[0]??e.name;function $e(e,t,n,r){if(n===void 0)return l(`Direct body parsed`,r);if(r===void 0)return l(`Input parsed`,n);if(N(n)&&N(r))try{return l(`Input parsed`,L(t,n,r))}catch(t){return d(`${e} ${t instanceof Error?t.message:String(t)}`)}return d(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function L(e,t,n,r=``){let i={...t};for(let[t,a]of Object.entries(n)){let n=i[t],o=`${r}${t}`;if(N(n)&&N(a))i[t]=L(e,n,a,`${o}.`);else if(n===void 0||n===a)i[t]=a;else throw Error(`sets JSON key '${o}' both in --from-file and with ${e.parameter.find(({name:e})=>e===o)?.flag.split(` `)[0]??`body options`} — set it in one place${Array.isArray(n)?`: move the per-item fields inside the matching '${o}[]' object(s) in the file body`:ue.test(o)?`; keep multi-line text in the --from-file body`:``}.`)}return i}function et(e,t){if(typeof t==`boolean`)return l(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return R(e,e.schemaType,t??``);let n=[],r=M(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=R(e,r,i);if(!t.ok)return t;n.push(t.data)}return l(`Body value parsed`,n)}function R(e,t,n){if(n===`null`&&e.nullable&&t===e.schemaType)return l(`Body value parsed`,null);let r=e.name;if(t===`boolean`)return n===`true`?l(`Body value parsed`,!0):n===`false`?l(`Body value parsed`,!1):d(`${r} must be true or false.`);if(t===`number`||t===`integer`){let e=n.trim(),i=Number(e);return e===``||!Number.isFinite(i)?d(`${r} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?d(`${r} must be an integer.`):l(`Body value parsed`,i)}return l(`Body value parsed`,n)}function tt(e,t){let n=t.parameter.filter(e=>e.required);if(n.length>0&&t.requiredPath.every(e=>n.some(({name:t})=>t===e||t.startsWith(`${e}.`))))return`${e} requires body option(s): ${n.map(I).join(`, `)}`;let r=k(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(I).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function nt(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:P,location:`body`}),z(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),De(e.options,r)}function z(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function rt(e,t,n=a().bin[0]){e.helpCommand(!1);let r=e.commands.find(e=>e.name()===`help`)??e.command(`help`);r.summary(`Show full documentation for a command, search the catalog, or ask a question`).description("Show a command's full documentation offline. Select it by command path,\noperationId, or `<METHOD> <path>`; `<command> --help` prints only its usage.\n`help catalog [query...]` searches or lists every operation;\n`help ask <question>` answers a platform question.").argument(`[command...]`,"command path, operationId, or METHOD and path, e.g. `help entities get`"),r.addOption(new it(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()}),D(r),r.action(async function(r){let i=r.flatMap(e=>e.split(/\s+/u).filter(Boolean)),{emit:a}=await import(`./output-XyvDx9ok.js`),o=this.optsWithGlobals();if(o.help&&i.length===0){this.outputHelp();return}let s=G(e,i),c=t.find(t=>s!==void 0&&G(e,t.cliPath)===s);if(o.help||s!==void 0&&c===void 0){s===void 0&&this.error(`unknown command '${i.join(` `)}' (run \`${n} --help\` for the command tree)`),s.outputHelp();return}let u=c===void 0?await st(i,t):l(`Resolved by command path`,{operationId:c.operationId});if(u.ok&&u.data?.command!==void 0&&this.error(`unknown command '${i.join(` `)}' (run \`${n} --help\` for the command tree)`),!u.ok||u.data===null){a({mode:E(o)},u);return}let{writeShowResult:d}=await import(`./operations-catalog-BfuHbIDu.js`);d({...o,...u.data},t,E(o,`text`),n)}),ot(e,t,n)}var it=class extends t{helpCommand;constructor(e){super(`-h, --help`,`display help for command`),this.helpCommand=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.helpCommand.parent?.args??[],n=t.findIndex(e=>e===this.helpCommand.name()||this.helpCommand.aliases().includes(e)),r=n<0?void 0:t[n+1];return r===void 0||r.startsWith(`-`)?!0:!this.helpCommand.commands.some(e=>e.name()===r||e.aliases().includes(r))}},B=2,V=6,at={formatHelp(e,t){let n=n=>r.prototype.formatHelp.call(this,e,Object.assign(Object.create(t),n));if(t.visibleCommands(e).length===0)return n({});let i=t.padWidth(e,t),a={padWidth:()=>i,visibleOptions:()=>[],showGlobalOptions:!1},o=n({...a,visibleCommands:()=>[]}),s=n({padWidth:()=>i,visibleCommands:()=>[]}).slice(o.length);return n(a)+s},visibleCommands(e){let t=r.prototype.visibleCommands.call(this,e);return e.parent===null?t.filter(e=>S[e.name()]?.listed!==!1):t},subcommandTerm(e){let t=r.prototype.subcommandTerm.call(this,e);return e.commands.length>0&&e.registeredArguments.length===0?`${t} <command>`:t},formatItem(e,t,n,i){let a=i.helpWidth??80,o=a-t-4;return n===``||o>=i.minWidthToWrap?r.prototype.formatItem.call(i,e,t,n,i):`${` `.repeat(B)}${e}\n${H(n,a,i)}`}};function H(e,t,n){return n.boxWrap(e,t-V).replace(/^/gmu,` `.repeat(V))}function ot(e,t,n){for(let r of t){let i=G(e,r.cliPath);i!==void 0&&i.addHelpText(`after`,()=>{let e=i.createHelp(),a=i.configureOutput().getOutHelpWidth?.();e.prepareContext(a===void 0?{}:{helpWidth:a});let o=e.helpWidth??80,s=le(r.operationId,t,n),c=U(de(r.header),o,e),l=U(fe(r.errorResponse),o,e);return`\n${[...s,...c,...l].join(`
|
|
2
|
-
`)}\n`})}}function U(e,t,n){let[r,...i]=e;return r===void 0?[]:[``,r,...i.map(e=>H(e.trimStart(),t,n).replace(/^ +/u,` `.repeat(B)))]}var W='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';async function st(e,t){let[n=``,...r]=e.join(` `).trim().split(/\s+/u),[i,...a]=t.filter(e=>e.path===n);if(r.length===0&&i!==void 0)return a.length===0?l(`Resolved by route`,{operationId:i.operationId}):d(`${n} is served by ${[i,...a].map(({method:e})=>e).join(`, `)}; name the method, as in \`help ${i.method} ${n}\`.`,[W]);let o=f.find(e=>e===n.toLowerCase());if(o===void 0||r.length===0){let n=e.join(` `).trim();return l(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let s=p(o),c=r.join(``),u=t.find(e=>e.method===s&&e.path===c);if(u!==void 0)return l(`Resolved by route template`,{operationId:u.operationId});let{resolveOpenApiOperationSelector:m}=await import(`./openapi-call-
|
|
3
|
-
`)),!s)return;let b=ie(n);for(let e of n.parameters)mt(v,e,a||e===b);Be(v,n),g(n.intent)&&!v.options.some(e=>e.long===`--execute`)&&v.addOption(new t(`--execute`).hideHelp()),D(v),v.hook(`preAction`,e=>te(e,n)),n.explain===!0&&v.option(`--explain`,`Print the search strategy and parsed constraints before the results`),b!==void 0&&v.argument(`[text...]`,b.description||`Same as ${ce(b.flag)}.`),v.action(async function(){let{emit:e,emitSearchExplanation:t}=await import(`./output-XyvDx9ok.js`),r=Object.assign(this.optsWithGlobals(),{environment:this.opts().environment}),i=E(r),a=r;if(b!==void 0){let t=ne(b,this.args,r);if(!t.ok)return e({mode:i},{...t,notDispatched:!0});if(t.data===null)return e({mode:i},t);a=t.data}let o=ee(n,a);if(o.length>0){let t=`missing required options: ${o.join(`, `)}`;return e({mode:i},d(t,[],{notDispatched:!0}))}let s=await ht(n,a,i),c=ct(n,a,s);if(c!==null)return e({mode:i},c);r.explain===!0&&s.ok&&t(i,s.data),s.ok&&s.data instanceof Uint8Array&&i!==`csv`&&i!==`xlsx`?process.stdout.write(s.data):e({mode:i},s)})}function pt(e,t,n,r){let i=e.commands.find(e=>e.name()===t);if(i!==void 0)return i;let a=S[n],o=e.command(t,r?{hidden:!0}:{}).helpCommand(!1);return a!==void 0&&o.summary(a.summary).description(a.summary),o}function mt(e,n,r=!1){let i=n.description||`${n.name} ${n.location} parameter`,a=n.defaultValue===void 0?void 0:typeof n.defaultValue==`string`||typeof n.defaultValue==`boolean`?n.defaultValue:[...n.defaultValue];if(n.legacyFlag!==void 0){let o=new t(n.flag,i);a!==void 0&&o.default(a);let s=new t(n.legacyFlag,i).conflicts(n.optionKey);e.addOption(o).addOption(s),e.hook(`preAction`,e=>{let t=e.opts(),i=t[n.optionKey],a=t[s.attributeName()];a===void 0?!r&&n.required&&i===void 0&&e.error(`error: required option '${o.flags}' not specified`,{code:`commander.missingMandatoryOptionValue`}):(i===void 0||e.getOptionValueSource(n.optionKey)==="default")&&e.setOptionValueWithSource(n.optionKey,a,`cli`)})}else a===void 0?n.required&&!r?e.requiredOption(n.flag,i):e.option(n.flag,i):e.option(n.flag,i,a)}async function ht(e,t,n){let{buildOpenApiPath:r,runOpenApiCall:i}=await import(`./openapi-call-
|
|
1
|
+
import{a as e,n as t,o as n,r,t as i}from"./commander-DEj7N1b9.js";import{a}from"./package-DEeHDoOT.js";import{a as o,c as s,r as c}from"./env-DGAe95Xm.js";import{c as l,p as u,r as d}from"./result-envelope-BMqcRDpc.js";import{L as f,R as p,o as m,t as h,u as g,y as _}from"./tool-policy-DG8pafmI.js";import{i as v}from"./logging-DYzy2g8p.js";import{r as y,t as b}from"./cli-help-policy-DCn_wXe1.js";import{a as x,c as S,d as ee,f as te,i as C,l as w,m as ne,n as re,p as ie,r as ae,s as oe,t as se,u as ce}from"./startup-auth-BuGIFRmd.js";import{t as T}from"./openapi-commands-B2dIDk9o.js";import{g as le,m as ue}from"./help-catalog-PSifyPm6.js";import{n as de,t as fe}from"./operations-metadata-CzOMH0PS.js";import{a as E,i as pe,t as D}from"./output-mode-DIt-t4Fu.js";import{S as me,_ as O,a as he,b as k,c as ge,d as _e,f as ve,g as ye,h as be,i as xe,l as Se,m as A,n as j,o as Ce,p as we,r as Te,s as Ee,t as De,u as Oe,v as M,x as ke,y as N}from"./generated-option-order-DYmytWyF.js";import{n as Ae,t as je}from"./deprecated-command-bF9Q8_F6.js";import{a as Me,i as Ne,n as Pe,r as Fe}from"./payload-operand-guard-Cne4mq9F.js";import{fileURLToPath as Ie}from"node:url";import{readFile as Le}from"node:fs/promises";async function Re(e){let t;try{t=e===`-`?await ze():await Le(e,`utf8`)}catch(t){return d(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return l(`No input provided`,null);let e=JSON.parse(t);return l(`Input parsed`,e)}catch(e){return d(`Input is not valid JSON: ${e.message}`)}}async function ze(){if(process.stdin.isTTY)throw Error(`--from-file - requires JSON on stdin, but stdin is a TTY`);process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}var P=`--content-type`;function Be(e,n,r){let i=e=>!r?.has(e)&&(r?.add(e),!0),a=n.requestBody??[];if(a.length>1&&i(P)){let n=a.map(({contentType:e})=>e);e.addOption(new t(`${P} <media-type>`,`Select the request body encoding, never an uploaded file's media type; omit for ${n[0]}.`).choices(n).argParser(He(a)))}if(z(n)&&i(`--from-file`)){let r=a[0];if(r===void 0)throw Error(`${n.operationId} has no request body`);e.addOption(new t(`--from-file <path>`,he(r,r.requiredPath)).argParser(F(`--from-file`)))}let o=Ce(a).filter(e=>i(I(e.variant[0].parameter)));for(let n of o.toSorted((e,t)=>j(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:r,parameter:i}=n.variant[0],o=new t(xe(n),a.length>1?Te(n):ge(r,i));a.length===1&&i.envName!==void 0&&o.env(i.envName);let s=a.length===1?Ee(r,i.optionKey):[];s.length>0&&o.conflicts(s),a.length>1?o.argParser(Ve):M(i.name)||i.schemaType===`array`?o.argParser(Ue):o.argParser(F(i.flag)),e.addOption(o),o.envVar!==void 0&&e.on(`optionEnv:${o.name()}`,()=>{let t=e.opts()[i.optionKey];typeof t==`string`&&t.trim()&&e.setOptionValueWithSource(i.optionKey,t.trim(),`env`)})}nt(e,n,o)}function Ve(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function He(e){return(t,r)=>{if(r!==void 0)throw new n(`${P} was already given; pass it once.`);let i=_(e,t);if(!i.ok)throw new n(i.summary);return t}}function Ue(e,t){return[...t??[],e]}function F(e){let t=e.split(/\s+/u)[0]??e;return(e,r)=>{if(r!==void 0)throw new n(`${t} was already given; pass it once.`);return e}}async function We(e,t){let n=w(e,t),r=_(e.requestBody??[],n);if(!r.ok||r.data===null)return d(r.summary,r.warnings);let i=r.data;if(i===void 0)return l(`No body`,void 0);let a=Ge(e,i,t);if(a!==null)return d(a);let o=A(e.operationId,i,t);if(!o.ok)return d(o.summary,o.warnings);t=o.data;let s=Ke(i,t);if(s!==null)return d(s);let c=await Xe(t);if(!c.ok)return d(c.summary,c.warnings);let u=be(e.requestBody??[],i,c.data);if(u!==null)return d(u);let f=Ye(e.operationId,i,c.data);if(!f.ok)return f;let p=ye(e.operationId,i,c.data);if(p!==null)return d(p);let m=Ze(e.operationId,i,t);if(!m.ok)return m;if(c.data===void 0&&m.data===void 0)return i.required?d(tt(e.operationId,i)):l(`No body`,void 0);let h=$e(e.operationId,i,c.data,m.data);if(!h.ok||h.data===void 0)return h;if(i.schemaType===`array`&&!Array.isArray(h.data))return d(`${e.operationId} requires a JSON array body.`);if(i.parameter.length>0&&!N(h.data)){let t=i.kind===`multipart`?` keyed by multipart part name`:` body`;return d(`${e.operationId} requires a JSON object${t}.`)}let g=Je(i,h.data);if(g.length>0)return d(`${e.operationId} requires body option(s): ${g.join(`, `)}`);let v=h.data,y=N(v)?k(i).filter(e=>!O(v,e)):[];return y.length>0?d(qe(e.operationId,i,y)):h}function Ge(e,t,n){let r=new Set(t.parameter.map(({optionKey:e})=>e));for(let i of e.requestBody??[])if(i!==t)for(let t of i.parameter){if(r.has(t.optionKey)||n[t.optionKey]===void 0)continue;let i=(e.requestBody??[]).filter(e=>e.parameter.some(({optionKey:e})=>e===t.optionKey)).map(({contentType:e})=>e);return`${I(t)} requires ${P} ${i.join(` or `)}.`}return null}function Ke(e,t){for(let n of e.cliConflicts??[]){let e=n.filter(e=>t[e]!==void 0);if(e.length>1)return`Options ${e.join(`, `)} cannot be used together.`}return null}function qe(e,t,n){let r=`${e} requires JSON body path(s): ${n.join(`, `)}`;return t.kind===`multipart`?`${r}. ${n.includes(`body`)?`For multipart --from-file, wrap the endpoint JSON under top-level "body".`:`For multipart --from-file, put the missing nested path(s) inside top-level "body".`}`:r}function Je(e,t){return N(t)?e.parameter.filter(e=>e.required&&!O(t,e.name)).map(I):[]}function Ye(e,t,n){let r=me(t,n);return r===null?l(`Body file paths validated`,null):d(`${e} --from-file contains ${r.message}`)}async function Xe(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return l(`No body file`,void 0);let n=await Re(t);if(!n.ok)return d(n.summary,n.warnings);let r=u.safeParse(n.data);return r.success?l(`Input parsed`,r.data):d(`Input is not valid JSON value: ${r.error.message}`)}function Ze(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=ke(e,n[e.optionKey]);if(!a.ok||a.data===null)return d(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=Qe(t,n,r,e,o);if(!s.ok)return d(s.summary,s.warnings);i=!0}if(!i)return l(`No direct body options`,void 0);let a=_e(e,t,n,r);return a===null?l(`Direct body options parsed`,r):a}function Qe(e,t,n,r,i){let a=Se(e,t,r);if(a===null){let e=et(r,i);return e.ok?ve(n,r.name,e.data,r.schemaType===`array`):d(e.summary,e.warnings)}let o=Oe(e,t,r,a);if(o!==null)return d(o);let s=r.schemaType===`array`,c=s?r.itemSchemaType:r.schemaType;for(let[e,t]of a.rows){let i=[];for(let e of t){let t=R(r,c,e);if(!t.ok)return d(t.summary,t.warnings);i.push(t.data)}for(let t of s?[i]:i){let i=we(n,r.name,e,t);if(!i.ok)return i}}return l(`Body value assigned`,null)}var I=e=>e.flag.split(` `)[0]??e.name;function $e(e,t,n,r){if(n===void 0)return l(`Direct body parsed`,r);if(r===void 0)return l(`Input parsed`,n);if(N(n)&&N(r))try{return l(`Input parsed`,L(t,n,r))}catch(t){return d(`${e} ${t instanceof Error?t.message:String(t)}`)}return d(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function L(e,t,n,r=``){let i={...t};for(let[t,a]of Object.entries(n)){let n=i[t],o=`${r}${t}`;if(N(n)&&N(a))i[t]=L(e,n,a,`${o}.`);else if(n===void 0||n===a)i[t]=a;else throw Error(`sets JSON key '${o}' both in --from-file and with ${e.parameter.find(({name:e})=>e===o)?.flag.split(` `)[0]??`body options`} — set it in one place${Array.isArray(n)?`: move the per-item fields inside the matching '${o}[]' object(s) in the file body`:ue.test(o)?`; keep multi-line text in the --from-file body`:``}.`)}return i}function et(e,t){if(typeof t==`boolean`)return l(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return R(e,e.schemaType,t??``);let n=[],r=M(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=R(e,r,i);if(!t.ok)return t;n.push(t.data)}return l(`Body value parsed`,n)}function R(e,t,n){if(n===`null`&&e.nullable&&t===e.schemaType)return l(`Body value parsed`,null);let r=e.name;if(t===`boolean`)return n===`true`?l(`Body value parsed`,!0):n===`false`?l(`Body value parsed`,!1):d(`${r} must be true or false.`);if(t===`number`||t===`integer`){let e=n.trim(),i=Number(e);return e===``||!Number.isFinite(i)?d(`${r} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?d(`${r} must be an integer.`):l(`Body value parsed`,i)}return l(`Body value parsed`,n)}function tt(e,t){let n=t.parameter.filter(e=>e.required);if(n.length>0&&t.requiredPath.every(e=>n.some(({name:t})=>t===e||t.startsWith(`${e}.`))))return`${e} requires body option(s): ${n.map(I).join(`, `)}`;let r=k(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(I).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function nt(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:P,location:`body`}),z(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),De(e.options,r)}function z(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function rt(e,t,n=a().bin[0]){e.helpCommand(!1);let r=e.commands.find(e=>e.name()===`help`)??e.command(`help`);r.summary(`Show full documentation for a command, search the catalog, or ask a question`).description("Show a command's full documentation offline. Select it by command path,\noperationId, or `<METHOD> <path>`; `<command> --help` prints only its usage.\n`help catalog [query...]` searches or lists every operation;\n`help ask <question>` answers a platform question.").argument(`[command...]`,"command path, operationId, or METHOD and path, e.g. `help entities get`"),r.addOption(new it(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()}),D(r),r.action(async function(r){let i=r.flatMap(e=>e.split(/\s+/u).filter(Boolean)),{emit:a}=await import(`./output-XyvDx9ok.js`),o=this.optsWithGlobals();if(o.help&&i.length===0){this.outputHelp();return}let s=G(e,i),c=t.find(t=>s!==void 0&&G(e,t.cliPath)===s);if(o.help||s!==void 0&&c===void 0){s===void 0&&this.error(`unknown command '${i.join(` `)}' (run \`${n} --help\` for the command tree)`),s.outputHelp();return}let u=c===void 0?await st(i,t):l(`Resolved by command path`,{operationId:c.operationId});if(u.ok&&u.data?.command!==void 0&&this.error(`unknown command '${i.join(` `)}' (run \`${n} --help\` for the command tree)`),!u.ok||u.data===null){a({mode:E(o)},u);return}let{writeShowResult:d}=await import(`./operations-catalog-D4YIaQHB.js`);d({...o,...u.data},t,E(o,`text`),n)}),ot(e,t,n)}var it=class extends t{helpCommand;constructor(e){super(`-h, --help`,`display help for command`),this.helpCommand=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.helpCommand.parent?.args??[],n=t.findIndex(e=>e===this.helpCommand.name()||this.helpCommand.aliases().includes(e)),r=n<0?void 0:t[n+1];return r===void 0||r.startsWith(`-`)?!0:!this.helpCommand.commands.some(e=>e.name()===r||e.aliases().includes(r))}},B=2,V=6,at={formatHelp(e,t){let n=n=>r.prototype.formatHelp.call(this,e,Object.assign(Object.create(t),n));if(t.visibleCommands(e).length===0)return n({});let i=t.padWidth(e,t),a={padWidth:()=>i,visibleOptions:()=>[],showGlobalOptions:!1},o=n({...a,visibleCommands:()=>[]}),s=n({padWidth:()=>i,visibleCommands:()=>[]}).slice(o.length);return n(a)+s},visibleCommands(e){let t=r.prototype.visibleCommands.call(this,e);return e.parent===null?t.filter(e=>S[e.name()]?.listed!==!1):t},subcommandTerm(e){let t=r.prototype.subcommandTerm.call(this,e);return e.commands.length>0&&e.registeredArguments.length===0?`${t} <command>`:t},formatItem(e,t,n,i){let a=i.helpWidth??80,o=a-t-4;return n===``||o>=i.minWidthToWrap?r.prototype.formatItem.call(i,e,t,n,i):`${` `.repeat(B)}${e}\n${H(n,a,i)}`}};function H(e,t,n){return n.boxWrap(e,t-V).replace(/^/gmu,` `.repeat(V))}function ot(e,t,n){for(let r of t){let i=G(e,r.cliPath);i!==void 0&&i.addHelpText(`after`,()=>{let e=i.createHelp(),a=i.configureOutput().getOutHelpWidth?.();e.prepareContext(a===void 0?{}:{helpWidth:a});let o=e.helpWidth??80,s=le(r.operationId,t,n),c=U(de(r.header),o,e),l=U(fe(r.errorResponse),o,e);return`\n${[...s,...c,...l].join(`
|
|
2
|
+
`)}\n`})}}function U(e,t,n){let[r,...i]=e;return r===void 0?[]:[``,r,...i.map(e=>H(e.trimStart(),t,n).replace(/^ +/u,` `.repeat(B)))]}var W='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';async function st(e,t){let[n=``,...r]=e.join(` `).trim().split(/\s+/u),[i,...a]=t.filter(e=>e.path===n);if(r.length===0&&i!==void 0)return a.length===0?l(`Resolved by route`,{operationId:i.operationId}):d(`${n} is served by ${[i,...a].map(({method:e})=>e).join(`, `)}; name the method, as in \`help ${i.method} ${n}\`.`,[W]);let o=f.find(e=>e===n.toLowerCase());if(o===void 0||r.length===0){let n=e.join(` `).trim();return l(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let s=p(o),c=r.join(``),u=t.find(e=>e.method===s&&e.path===c);if(u!==void 0)return l(`Resolved by route template`,{operationId:u.operationId});let{resolveOpenApiOperationSelector:m}=await import(`./openapi-call-Gchy3s8a.js`),h=m({method:s,path:c});return!h.ok||h.data===null?d(h.summary,[...h.warnings,W]):l(`Resolved by method and path`,{operationId:h.data.operation.operationId})}function G(e,t){let n=e;for(let e of t){let t=n.commands.find(t=>t.name()===e||t.aliases().includes(e));if(t===void 0)return;n=t}return n}function ct(e,t,n){if(e.cliPath[0]!==`lookup`||!lt(n))return null;let r=[...(e.requestBody??[]).flatMap(e=>e.parameter),...e.parameters,{name:`fromFile`,optionKey:`fromFile`}],i=r.filter(({optionKey:e},t)=>r.findIndex(t=>t.optionKey===e)===t).filter(({optionKey:e})=>t[e]!==void 0).map(({name:e,optionKey:n})=>`${e}=${String(t[n])}`),a=`no record for ${i.length===0?`the given input`:i.join(`, `)}`;return n.ok?d(a):d(a,[],{httpStatus:n.httpStatus,problem:n.problem})}function lt(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}function ut(t,n,r,i){let a=dt(t,r),o=a instanceof e?[]:a,s=o[0],c=i.bin[0],l=[{selected:s===`auth`,register:async()=>{let{registerBuiltinAuthCommands:e}=await import(`./builtin-auth-IPP_Zmbj.js`);e(n,c)}},{selected:s===`agents`,register:async()=>{let{registerBuiltinAgentSetupCommand:e}=await import(`./builtin-agent-setup-B2Xvqera.js`);e(n,c)}},{selected:s===`update`,register:async()=>{let{registerBuiltinUpdateCommand:e}=await import(`./builtin-update-DJT_3I5O.js`);e(n,i)}},{selected:s===`batch`,register:async()=>{let{registerBuiltinBatchCommand:e}=await import(`./builtin-batch-DdGyCjlR.js`);e(n,r,c)}},{selected:s===`research`||s===`research-runs`||s===`data-engineering`,register:async()=>{let{registerBuiltinRunWaitCommand:e}=await import(`./builtin-run-wait-5yr1WK3I.js`);await e(n)}},{selected:s===`completion`,register:async()=>{let{registerCompletionCommand:e}=await import(`./completion-CnY6V98Y.js`);e(n,r,c)}},{selected:s===`help`,register:async()=>{let{registerHelpCatalogCommand:e}=await import(`./operations-DbanGAPY.js`);e(n,r,c)}},{selected:s===`command-catalog`,register:async()=>{let{registerRetiredCommandCatalog:e}=await import(`./operations-DbanGAPY.js`);e(n,r,c)}}],u=s===void 0||s===`help`||s===`completion`||s===`command-catalog`||!l.some(e=>e.selected)&&!r.some(e=>e.cliPath[0]===s),d=1;for(;d<o.length&&r.some(e=>o.slice(0,d+1).every((t,n)=>e.cliPath[n]===t));)d++;let f=o.slice(0,d),p=u?r:r.filter(e=>f.slice(0,e.cliPath.length).every((t,n)=>e.cliPath[n]===t)),m=new Set,h=async(e=!1)=>{for(let t of l)(e||u||t.selected)&&!m.has(t)&&(await t.register(),m.add(t))};return{generated:p,fullTree:u,rootHelp:t.length>0&&t.every(e=>e===`--help`||e===`-h`),registerBuiltin:h,async completeTree(e){e(n,r.filter(e=>!p.includes(e))),await h(!0)}}}function dt(t,n){try{return new i().parseOptions([...C(t,n).commandArgv]).operands}catch(t){if(!(t instanceof e))throw t;return t}}var K=new Set(T.map(e=>e.cliPath.join(` `)));function q(e,t){e.showHelpAfterError(!1).exitOverride(t(e)),e.commands.length===0?e.hook(`preAction`,Pe):e.registeredArguments.length===0&&!K.has(Me(e).join(` `))&&e.addHelpOption(new Ne(e));for(let n of e.commands)q(n,t)}function J(e){return b[y(e,S)??`cli`]}function Y(e,t,n,{rootHelp:r=!1}={}){let i=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:J(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec),a=new Set(i.filter(e=>se(e.cliPath[0])).map(e=>e.cliPath[0]??``)),o=new Set,s=new Set;for(let{cliPath:e,deprecated:t}of i)for(let n=1;n<e.length;n++){let r=e.slice(0,n).join(` `);o.add(r),t!==!0&&s.add(r)}for(let t of i)ft(e,t,a,s,o.has(t.cliPath.join(` `)),n,!r||t.cliPath.length===1)}function ft(e,n,r,i,a,o,s){let c=n.cliPath,l=e,u=``,f=!r.has(c[0]??``);for(let e of c.slice(0,-1)){u=u===``?e:`${u} ${e}`;let t=f&&u===e||!i.has(u);l=pt(l,e,u,t)}let p=c.at(-1)??n.operationId,_=n.deprecated===!0&&i.has(c.join(` `)),v=l.commands.find(e=>e.name()===p)??l.command(p,n.deprecated===!0&&!_?{hidden:!0}:{}),y=n.requestBody?.flatMap(({parameter:e})=>e)??[];if(v.summary((_?S[c.join(` `)]?.summary:void 0)??(n.summary||n.operationId)).description([`${n.method} ${n.path}.`,n.summary||n.description,`Full documentation: ${o} help ${n.cliPath.join(` `)}`,n.requestBody?.[0]?.kind===`json`||[...n.parameters,...y].some(e=>m(e.schemaType,e.itemSchemaType))?h:``].filter(Boolean).join(`
|
|
3
|
+
`)),!s)return;let b=ie(n);for(let e of n.parameters)mt(v,e,a||e===b);Be(v,n),g(n.intent)&&!v.options.some(e=>e.long===`--execute`)&&v.addOption(new t(`--execute`).hideHelp()),D(v),v.hook(`preAction`,e=>te(e,n)),n.explain===!0&&v.option(`--explain`,`Print the search strategy and parsed constraints before the results`),b!==void 0&&v.argument(`[text...]`,b.description||`Same as ${ce(b.flag)}.`),v.action(async function(){let{emit:e,emitSearchExplanation:t}=await import(`./output-XyvDx9ok.js`),r=Object.assign(this.optsWithGlobals(),{environment:this.opts().environment}),i=E(r),a=r;if(b!==void 0){let t=ne(b,this.args,r);if(!t.ok)return e({mode:i},{...t,notDispatched:!0});if(t.data===null)return e({mode:i},t);a=t.data}let o=ee(n,a);if(o.length>0){let t=`missing required options: ${o.join(`, `)}`;return e({mode:i},d(t,[],{notDispatched:!0}))}let s=await ht(n,a,i),c=ct(n,a,s);if(c!==null)return e({mode:i},c);r.explain===!0&&s.ok&&t(i,s.data),s.ok&&s.data instanceof Uint8Array&&i!==`csv`&&i!==`xlsx`?process.stdout.write(s.data):e({mode:i},s)})}function pt(e,t,n,r){let i=e.commands.find(e=>e.name()===t);if(i!==void 0)return i;let a=S[n],o=e.command(t,r?{hidden:!0}:{}).helpCommand(!1);return a!==void 0&&o.summary(a.summary).description(a.summary),o}function mt(e,n,r=!1){let i=n.description||`${n.name} ${n.location} parameter`,a=n.defaultValue===void 0?void 0:typeof n.defaultValue==`string`||typeof n.defaultValue==`boolean`?n.defaultValue:[...n.defaultValue];if(n.legacyFlag!==void 0){let o=new t(n.flag,i);a!==void 0&&o.default(a);let s=new t(n.legacyFlag,i).conflicts(n.optionKey);e.addOption(o).addOption(s),e.hook(`preAction`,e=>{let t=e.opts(),i=t[n.optionKey],a=t[s.attributeName()];a===void 0?!r&&n.required&&i===void 0&&e.error(`error: required option '${o.flags}' not specified`,{code:`commander.missingMandatoryOptionValue`}):(i===void 0||e.getOptionValueSource(n.optionKey)==="default")&&e.setOptionValueWithSource(n.optionKey,a,`cli`)})}else a===void 0?n.required&&!r?e.requiredOption(n.flag,i):e.option(n.flag,i):e.option(n.flag,i,a)}async function ht(e,t,n){let{buildOpenApiPath:r,runOpenApiCall:i}=await import(`./openapi-call-Gchy3s8a.js`),{pendingResult:a}=await import(`./output-XyvDx9ok.js`),o=await We(e,t);if(!o.ok)return{...o,notDispatched:!0};let s=!1,c=Object.fromEntries(e.parameters.filter(e=>e.location===`path`).map(e=>{let n=t[e.optionKey];if(Array.isArray(n))return[e.name,n.at(0)??``];if(n===void 0)throw Error(`Missing required option ${e.optionKey}`);return[e.name,String(n)]})),l=Object.fromEntries(e.parameters.filter(e=>e.location===`query`).flatMap(e=>{let n=t[e.optionKey];if(n===void 0||Array.isArray(n)&&n.length===0)return[];let r=Array.isArray(n)||typeof n==`boolean`?n:String(n);return[[e.name,r]]})),u=Object.fromEntries(e.parameters.filter(e=>e.location===`header`).flatMap(e=>{let n=t[e.optionKey];return n===void 0||Array.isArray(n)&&n.length===0?[]:[[e.name,Array.isArray(n)?n.join(`,`):String(n)]]})),d=await i({method:e.method,path:r(e.operationId,c),searchParams:l,headers:u,body:o.data,contentType:w(e,t),auth:e.auth,responseFormat:pe(n),responseBytes:e.binaryResponse===!0,pendingResult:a,onDispatch:()=>{s=!0}});return je(e,d.ok||s?d:{...d,notDispatched:!0})}async function gt(e,n){let r=n.bin[0],i=Ae(T),a=re(e,i),l=a===`required`?i:oe(i),u=new Fe;u.enablePositionalOptions(!x(e)&&C(e,i).positionalOptions).name(r).usage(`[--environment <environment>] <command> [subcommand] [options]`).configureHelp(at).summary(`CLI for the aVenture API: companies, people, and news, with the funding, publications, and classifications attached to them`).description(`The aVenture research API from your terminal. Three records — companies,
|
|
4
4
|
people, and news — carry everything else: funding, publications, and tags.
|
|
5
5
|
|
|
6
6
|
Mutations execute directly; --execute is a deprecated no-op.
|
|
7
|
-
The aVenture MCP server runs these same operations through the same API client.`).addOption(new t(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${c})`).choices([...s()])).showHelpAfterError(`(run \`${r} --help\` for usage)`),(x(e)||e.every(e=>e.startsWith(`-`)))&&u.version(n.version);let d=ut(e,u,l,n);Y(u,d.generated,r,{rootHelp:d.rootHelp}),await d.registerBuiltin(),rt(u,l,r);for(let e of u.commands)e.helpGroup()||e.helpGroup(J(e.name()).heading);let f;if(q(u,e=>t=>{throw f=(async()=>{!d.fullTree&&![`commander.helpDisplayed`,`commander.version`].includes(t.code)&&await d.completeTree((e,t)=>Y(e,t,r));let{commandExitHandler:n}=await import(`./parse-error-hint-
|
|
7
|
+
The aVenture MCP server runs these same operations through the same API client.`).addOption(new t(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${c})`).choices([...s()])).showHelpAfterError(`(run \`${r} --help\` for usage)`),(x(e)||e.every(e=>e.startsWith(`-`)))&&u.version(n.version);let d=ut(e,u,l,n);Y(u,d.generated,r,{rootHelp:d.rootHelp}),await d.registerBuiltin(),rt(u,l,r);for(let e of u.commands)e.helpGroup()||e.helpGroup(J(e.name()).heading);let f;if(q(u,e=>t=>{throw f=(async()=>{!d.fullTree&&![`commander.helpDisplayed`,`commander.version`].includes(t.code)&&await d.completeTree((e,t)=>Y(e,t,r));let{commandExitHandler:n}=await import(`./parse-error-hint-0Xc2T5On.js`);try{n(e)(t)}catch(e){if(e!==t)throw e}})(),t}),a===`required`){let e=[u];for(;e.length>0;){let t=e.pop();t!==void 0&&(e.push(...t.commands),t.hook(`preAction`,async(e,t)=>{e===t&&await ae(`required`)}))}}let p=new Set(u.commands.filter(e=>[`entities`,`people`,`news`].includes(e.name())).flatMap(e=>e.commands.map(e=>e.name())));return u.addHelpText(`after`,[``,`Record subcommands under entities, people, and news:`,...[[`search`,` search Find many of that record from a plain-English query or a filter`],[`lookup`,` lookup Find one news article; companies and people use the root lookup`],[`get`,` get Read one record`],[`list`,` list Read many records`],[`create`,` create, update, delete Write; each needs a credential that permits it`]].flatMap(([e,t])=>p.has(e)?[t]:[]),``,`Authentication (every command that calls aVenture needs a credential):`,` Create one at ${o}/sign-up, then run: ${r} auth login`,` AUTH_TOKEN aVenture API key, for CI and other non-interactive shells`,` Check what this shell holds with: ${r} auth status\n`,`Output modes (per command):`,` --text compact lines, the terminal default; --json the full envelope`,` --csv Print CSV rows or preserve server CSV bytes.`,` --xlsx Write server XLSX bytes with --to-file; use --csv otherwise.`,` --data response data as JSON, the default when piped or non-TTY`,` --data-full uncapped, for bounded programs, never LLM agents`,` --all-fields --text plus the detail fields it hides by default
|
|
8
8
|
`,`Exit codes:`,` 0 envelope.ok === true
|
|
9
9
|
1 envelope.ok === false
|
|
10
10
|
`,`Examples:`,` $ ${r} auth login`,` $ ${r} lookup --name Stripe --url https://stripe.com`,` $ ${r} search "fintech companies in Austin"\n`,`Run \`${r} <command> --help\` for its subcommands and options,`,`or \`${r} help <command>\` for its full documentation.`].join(`
|
|
11
|
-
`)),{program:u,exitPreparation:()=>f}}var X=a(Ie(import.meta.url)),Z=X.bin[0];async function Q(e,t){process.exitCode=1;let n=e instanceof Error?e:Error(String(e)),r={...d(`${Z} ${t}: ${n.message}`,[n.name||`Error`]),counts:{exitCode:1}};v({component:Z,event:`fatal`,message:n.message,error:n}),process.stderr.write(`${Z} fatal (${t}): ${n.stack??n.message}\n`);try{let{BearerVerificationUnavailableError:e}=await import(`./openapi-call-
|
|
11
|
+
`)),{program:u,exitPreparation:()=>f}}var X=a(Ie(import.meta.url)),Z=X.bin[0];async function Q(e,t){process.exitCode=1;let n=e instanceof Error?e:Error(String(e)),r={...d(`${Z} ${t}: ${n.message}`,[n.name||`Error`]),counts:{exitCode:1}};v({component:Z,event:`fatal`,message:n.message,error:n}),process.stderr.write(`${Z} fatal (${t}): ${n.stack??n.message}\n`);try{let{BearerVerificationUnavailableError:e}=await import(`./openapi-call-Gchy3s8a.js`),{emitJson:t}=await import(`./output-XyvDx9ok.js`),i=n instanceof e?{httpStatus:n.problem.status,problem:n.problem}:{};r={...r,...i},t(r)}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${Z} fatal reporting failed: ${t}\n`),process.stdout.write(`${JSON.stringify(r)}\n`)}}var _t=e=>{if(e.code!==`EPIPE`)throw e;process.exit(0)};for(let e of[process.stdout,process.stderr])e.on(`error`,_t);process.on(`uncaughtException`,e=>Q(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>Q(e,`unhandledRejection`));var $=await gt(process.argv.slice(2),X);try{await $.program.parseAsync()}catch(t){await $.exitPreparation(),t instanceof e?process.exitCode=t.exitCode:await Q(t,`parseAsync`)}export{};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{n as e}from"./commander-DEj7N1b9.js";import{a as t}from"./package-DEeHDoOT.js";import{a as n,f as r,t as i}from"./env-DGAe95Xm.js";import{c as a,r as o}from"./result-envelope-BMqcRDpc.js";import{r as s}from"./api-target-vxev2RKl.js";import{t as c}from"./credential-redaction-Cl6Eny3X.js";import{n as l}from"./contract-SAu4Y_Kd.js";import{t as u}from"./openapi-composites-IdxI7cAF.js";import{t as d}from"./auth-status-check-
|
|
1
|
+
import{n as e}from"./commander-DEj7N1b9.js";import{a as t}from"./package-DEeHDoOT.js";import{a as n,f as r,t as i}from"./env-DGAe95Xm.js";import{c as a,r as o}from"./result-envelope-BMqcRDpc.js";import{r as s}from"./api-target-vxev2RKl.js";import{t as c}from"./credential-redaction-Cl6Eny3X.js";import{n as l}from"./contract-SAu4Y_Kd.js";import{t as u}from"./openapi-composites-IdxI7cAF.js";import{t as d}from"./auth-status-check-Cwf6uUZP.js";import{t as f}from"./output-D8SD_tSW.js";import{a as p,t as m}from"./output-mode-DIt-t4Fu.js";var h=l(u,`oauth`),g=[l(u,`start`),l(u,`poll`),l(u,`acknowledge`)],_=l(u,`revoke`);function v(n,r=t().bin[0]){let a=S(n),s=[`${h.description} Default method: OAuth in your browser.`,`With --key: ${g.map(({description:e})=>e).join(` `)}`].join(`
|
|
2
2
|
`);m(x(a,[h,...g],s)).action(y),m(x(a,[_],_.description)).action(b),m(a.command(`status`).summary(`Keep saved credentials current and report them`).description([`Runs the same credential materialization every command runs, then reports:`,` - auth: whether AUTH_TOKEN was already set in this shell's environment`,` - oauth: the saved OAuth identity and access-token expiry for the selected API host;`,` an expired token is renewed with its refresh token and a token the sign-in service rejects is retired`,` - api-key: the saved aVenture API key, re-verified with aVenture sign-in and its cached metadata updated`,` - selected: the credential the next command sends`,` - providers: GET /v1/auth/providers (browser sign-in and the CLI OAuth client)`,` - api: running CLI package version plus GET /info build metadata`," - check: `{ name, status, message }` for each environment check:",...d.map(e=>` ${e.name}: ${e.purpose}`),``,`Exit code is 0 only when no check failed; a skipped check (no registry reachable) does not`,`fail the run. Each failing message names the command that fixes it.`,`Saved credentials are sent only to the selected API host and aVenture sign-in, never printed.`,`--verify read|write additionally runs a live permission probe for that scope; it does not`,`execute or authorize an arbitrary API operation.`].join(`
|
|
3
3
|
`)).addOption(new e(`--verify <scope>`,`verify one permission-probe scope`).choices([`read`,`write`]))).action(async function(e){C(this),f({mode:p(e)},await w(r,e.verify))}),a.command(`token`).summary(`Print the bearer token the next command sends`).description([`Runs the same credential materialization every command runs, then prints the selected`,`bearer token alone on stdout: ${i.authToken} when set, otherwise the saved OAuth`,`access token (renewed when expired) or the saved aVenture API key.`,`Use it where another client needs this CLI's sign-in, such as an MCP client's header helper.`].join(`
|
|
4
|
-
`)).action(async function(){let{refreshCliCredentials:e}=await import(`./auth-status-render-
|
|
5
|
-
`))}function C(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function w(e,n){let{resolveAuthStatus:l}=await import(`./auth-resolver-DNfIzKg-.js`),{apiHostCheck:u,authStatusReport:d,checkResult:f,environmentChecks:p}=await import(`./auth-status-check-
|
|
6
|
-
`)}async function E(e){let{refreshStoredApiKeyCredential:t}=await import(`./api-key-credential-verification-
|
|
4
|
+
`)).action(async function(){let{refreshCliCredentials:e}=await import(`./auth-status-render-DlSjZ6kk.js`);C(this);let t=await e(r),n=process.env[i.authToken]?.trim();t.failure===null&&n!==void 0&&n.length>0?process.stdout.write(`${n}\n`):f({mode:`text`},t.failure===null?M(`auth token: no credentials resolved`,null,r,{oauth:!0,apiKey:!0}):o(`auth token: ${t.failure}`))})}async function y(e){C(this);let t=p(e),n=e.key===!0?await(await import(`./api-key-login-DSWEmjPA.js`)).loginApiKeyCredential({noBrowser:!e.browser,clientLabel:e.clientLabel}):await(await import(`./oauth-login-155QGdTQ.js`)).loginOAuthCredential({noBrowser:!e.browser});f({mode:t},n)}async function b(e){let{logoutCliCredentials:t}=await import(`./logout-GwrTE5av.js`);C(this),f({mode:p(e)},await t({forgetLocal:e.forgetLocal===!0}))}function x(e,t,n){let[r]=t,i=e.command(r.command.slice(r.command.indexOf(` `)+1)).summary(r.summary).description(n),a=new Set;for(let e of t)for(let t of[...e.bodyOption,...e.localOption])a.has(t.flag)||(a.add(t.flag),`required`in t&&t.required?i.requiredOption(t.flag,t.description):i.option(t.flag,t.description));return i}function S(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Sign in, sign out, and check credentials`).description([`\`${h.command}\`: ${h.summary}; \`--key\` ${g[0].summary.toLowerCase()}.`,`\`${_.command}\`: ${_.summary}.`,"`auth status` reports credential provenance, sign-in providers, CLI/API build metadata, and environment checks.","`auth token` prints the bearer token the next command sends."].join(`
|
|
5
|
+
`))}function C(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function w(e,n){let{resolveAuthStatus:l}=await import(`./auth-resolver-DNfIzKg-.js`),{apiHostCheck:u,authStatusReport:d,checkResult:f,environmentChecks:p}=await import(`./auth-status-check-DcY55e4Q.js`),{inspectOAuthCredentialStorage:m}=await import(`./oauth-credential-CYLRKH91.js`),{apiKeyCredentialDiagnostics:h,inspectLiveAuth:g,oauthCredentialDiagnostics:_,refreshCliCredentials:v,renderAuthStatus:y}=await import(`./auth-status-render-DlSjZ6kk.js`),b;try{b=s(r().host)}catch(e){return o(`auth status: invalid API host — ${c(e)}`)}let x=l(),S=v(e),[C,w,O]=await Promise.all([j(`/info`,`GET /info`),D(),p(e)]),A=await S,[N,P]=await Promise.all([m(b),E(b)]),F=n===void 0?null:await g(n,N,P.inspection,A),I=t().version,L=h(b,P.inspection,P.verification),R=F!==null||x.present||N.state===`found`||P.inspection.state===`found`&&P.inspection.stored.activation===`active`,z=A.failure??F?.error??(R?null:`no credentials resolved`),B=d(O,u(C,b,e),z===null?f(`auth`,`pass`,`credential=${A.materialized??x.source??`none`}`):f(`auth`,`fail`,z)),V=`${y({cliName:e,cliVersion:I,apiVersion:C.ok?await k(C.data):null,oauth:N,apiKey:L,apiKeyPhase:P.inspection.state===`found`?P.inspection.stored.activation:null,providers:w,resolved:x,refresh:A,live:F})}\n${T(B.check)}`,H={cli:{version:I},api:C.ok?C.data??null:null,auth:{[i.authToken]:x},selected:A.materialized,oauth:_(b,N),apiKey:L,providers:w,live:F,check:B.check,...C.ok?{}:{apiError:C.summary}};if(A.failure!==null)return{...o(`auth status: ${A.failure} | ${V}`,[A.failure]),data:H};if(!C.ok&&C.httpStatus===401)return{...o(`auth status: the API rejected the selected credential (401) | ${V}`,[`Replace or unset ${i.authToken}, or run \`${e} auth login\`.`]),data:H};if(F!==null&&F.error!==null)return{...o(`auth status: ${F.scope} permission probe failed — ${F.error}`,[F.error]),data:H};if(!R)return M(`auth status: no credentials resolved | ${V}`,H,e,{oauth:N.state===`missing`,apiKey:P.inspection.state===`missing`});let U=B.check.filter(e=>e.status===`fail`);return U.length===0?a(V,H):{...o(`auth status: ${U.map(e=>e.name).join(`, `)} failed | ${V}`,U.map(e=>e.message)),data:H}}function T(e){return[`Checks`,...e.map(e=>` ${e.name} ${e.status} — ${e.message}`)].join(`
|
|
6
|
+
`)}async function E(e){let{refreshStoredApiKeyCredential:t}=await import(`./api-key-credential-verification-DC-YG5wa.js`),n=await O(e);if(n.state!==`found`)return{inspection:n,verification:null};let{lookup:r,verification:i}=await t(n.stored);return{inspection:r,verification:i}}async function D(){try{let{fetchAuthProviderCatalog:e}=await import(`./oauth-login-155QGdTQ.js`);return{state:`found`,catalog:await e()}}catch(e){return{state:`unavailable`,summary:c(e)}}}async function O(e){try{let{inspectApiKeyCredentialStorage:t}=await import(`./api-key-credential-CvGuNqg7.js`);return await t(e)}catch(e){return{state:`invalid`,summary:c(e)}}}async function k(e){let{SystemBuildSchema:t}=await import(`./system-build-DFy8edPI.js`);if(!A(e))return null;let n=t.safeParse(Reflect.get(e,`response`));if(!n.success)return null;let r=n.data.build.version?.trim();return r&&r.length>0?r:null}function A(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function j(e,t){let{runOpenApiCall:n}=await import(`./openapi-call-Gchy3s8a.js`);return await n({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>o(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}function M(e,t,r,a){return{...o(e,[...a.apiKey?[`For an API key (works over SSH), run \`${r} auth login --key\`.`]:[],...a.oauth?[`For OAuth, run \`${r} auth login\`; without a browser it prints a device code.`]:[],`For non-interactive use, set ${i.authToken} to an aVenture API key (create one at ${n}/settings/api-keys).`]),data:t}}export{v as registerBuiltinAuthCommands};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as e,r as t}from"./result-envelope-BMqcRDpc.js";import{t as n}from"./output-D8SD_tSW.js";import{a as r,t as i}from"./output-mode-DIt-t4Fu.js";var a=5e3,o=6e4,s=3e4,c=86400,l={noun:`research runs`,summary:`Wait for research runs to finish, then report each outcome`,description:"Polls `research runs get` with backoff until the run is completed, failed, or stopped, then prints its status, error, failure class, and last event time, plus spend when available in this distribution; a timeout reports the last event time so a stalled run shows. Exits nonzero when the run failed or stopped, or when --timeout passes first.",getOperationId:`getResearchRun`,defaultTimeoutSeconds:1800,schema:async()=>(await import(`./run-detail-Dr1rg-iE.js`)).HarnessRunDetailSchema,progress:({run:e,lastEventAt:t})=>e.status===`completed`||e.status===`failed`||e.status===`stopped`?void 0:`${e.status}, last event ${t??`none`}`,outcome:m};async function u(e){let t=t=>e.commands.find(e=>e.name()===t),n=e=>t(e)?.commands.find(e=>e.name()===`runs`),r=n(`research`);r!==void 0&&d(r,l);let i=n(`data-engineering`);if(i!==void 0){let{dataEngineeringRuns:e}=await import(`./private-run-read-DM_02z6l.js`);e!==void 0&&d(i,e)}}function d(e,t){let a=e.command(`wait`).summary(t.summary).description(`${t.description} Several --run-id values wait for every run in one process; data then lists each outcome in order, and the exit is nonzero unless every run succeeded.`).requiredOption(`--run-id <uuid...>`,`Run id; repeat or list several to wait for all`).option(`--timeout <seconds>`,`Total seconds to wait; a run still in flight then exits nonzero as still running`,String(t.defaultTimeoutSeconds));i(a),a.action(async function(){let e=this.optsWithGlobals(),i=await Promise.all(e.runId.map(n=>p(t,{runId:n,timeout:e.timeout}))),a=i.length===1&&i[0]!==void 0?i[0]:f(i);n({mode:r(e)},a)})}function f(t){let n=t.filter(e=>e.ok).length;return{...e(`${n} of ${t.length} runs succeeded: ${t.map(e=>e.summary).join(`; `)}`,t.map(e=>e.data),{warnings:t.flatMap(e=>e.warnings)}),ok:n===t.length}}async function p(e,n){let{setTimeout:r}=await import(`node:timers/promises`),{buildOpenApiPath:i}=await import(`./openapi-call-
|
|
1
|
+
import{c as e,r as t}from"./result-envelope-BMqcRDpc.js";import{t as n}from"./output-D8SD_tSW.js";import{a as r,t as i}from"./output-mode-DIt-t4Fu.js";var a=5e3,o=6e4,s=3e4,c=86400,l={noun:`research runs`,summary:`Wait for research runs to finish, then report each outcome`,description:"Polls `research runs get` with backoff until the run is completed, failed, or stopped, then prints its status, error, failure class, and last event time, plus spend when available in this distribution; a timeout reports the last event time so a stalled run shows. Exits nonzero when the run failed or stopped, or when --timeout passes first.",getOperationId:`getResearchRun`,defaultTimeoutSeconds:1800,schema:async()=>(await import(`./run-detail-Dr1rg-iE.js`)).HarnessRunDetailSchema,progress:({run:e,lastEventAt:t})=>e.status===`completed`||e.status===`failed`||e.status===`stopped`?void 0:`${e.status}, last event ${t??`none`}`,outcome:m};async function u(e){let t=t=>e.commands.find(e=>e.name()===t),n=e=>t(e)?.commands.find(e=>e.name()===`runs`),r=n(`research`);r!==void 0&&d(r,l);let i=n(`data-engineering`);if(i!==void 0){let{dataEngineeringRuns:e}=await import(`./private-run-read-DM_02z6l.js`);e!==void 0&&d(i,e)}}function d(e,t){let a=e.command(`wait`).summary(t.summary).description(`${t.description} Several --run-id values wait for every run in one process; data then lists each outcome in order, and the exit is nonzero unless every run succeeded.`).requiredOption(`--run-id <uuid...>`,`Run id; repeat or list several to wait for all`).option(`--timeout <seconds>`,`Total seconds to wait; a run still in flight then exits nonzero as still running`,String(t.defaultTimeoutSeconds));i(a),a.action(async function(){let e=this.optsWithGlobals(),i=await Promise.all(e.runId.map(n=>p(t,{runId:n,timeout:e.timeout}))),a=i.length===1&&i[0]!==void 0?i[0]:f(i);n({mode:r(e)},a)})}function f(t){let n=t.filter(e=>e.ok).length;return{...e(`${n} of ${t.length} runs succeeded: ${t.map(e=>e.summary).join(`; `)}`,t.map(e=>e.data),{warnings:t.flatMap(e=>e.warnings)}),ok:n===t.length}}async function p(e,n){let{setTimeout:r}=await import(`node:timers/promises`),{buildOpenApiPath:i}=await import(`./openapi-call-Gchy3s8a.js`),{parseBoundedInt:s}=await import(`./batch-io-D3B-dxmh.js`),l=s(`--timeout`,n.timeout,1,c);if(!l.ok||l.data===null)return t(l.summary);let u=Date.now()+l.data*1e3,d=i(e.getOperationId,{runId:n.runId}),f=a,p=`not read yet`,m=(r=`after ${l.data}s`)=>t(`Run ${n.runId} is still ${p} ${r}`,[`Wait longer with --timeout, or read it with \`${e.noun} get --run-id ${n.runId}\`.`]);for(;;){if(u-Date.now()<=0)return m();let t=0,n=await h(d,u,await e.schema());if(n.kind===`deadline`)return m();if(n.kind===`refused`)return n.envelope;if(n.kind===`detail`){let t=e.progress(n.detail);if(t===void 0)return await e.outcome(n.detail,u);p=t}else p=`unread (${n.reason})`,t=(n.retryAfterSeconds??0)*1e3;let i=u-Date.now();if(i<=0||t>=i)return m(i<=0?`after ${l.data}s`:`and the API asks for ${t/1e3}s, past the ${l.data}s --timeout`);let s=Math.max(t,a+Math.random()*(f-a)),c=Math.min(u,Date.now()+s),g=c-Date.now();for(;g>0;)await r(g),g=c-Date.now();f=Math.min(f*2,o)}}async function m(t,n){let{readResearchRunSpend:r}=await import(`./private-run-read-DM_02z6l.js`),{run:i}=t,a=await r?.({runId:i.id,deadline:n})??{costUsd:null},o={runId:i.id,status:i.status,error:i.error??null,failureClass:i.failureClass??null,publicUrl:t.publicUrl??null,finishedAt:i.finishedAt??null,lastEventAt:t.lastEventAt??null,...a.costUsd===null?{}:{costUsd:a.costUsd}},s={warnings:a.warning===void 0?[]:[a.warning]},c=a.costUsd===null?``:`; spend $${a.costUsd.toFixed(4)}`;if(i.status===`completed`)return e(`Run ${i.id} completed${c}`,o,s);let l=i.failureClass?` (${i.failureClass})`:``,u=i.error?`: ${i.error}`:``;return{...e(`Run ${i.id} ${i.status}${l}${c}${u}`,o,s),ok:!1}}async function h(e,n,r){let{runOpenApiCall:i}=await import(`./openapi-call-Gchy3s8a.js`),{isTransientRefusal:a,isTransportFailure:o}=await import(`./request-replay-DGlQLFjp.js`),{retrySeconds:c}=await import(`./response-problem-BbI2mj-6.js`),l=n-Date.now();if(l<=0)return{kind:`deadline`};let u=AbortSignal.timeout(Math.min(s,l)),d;try{d=await i({method:`GET`,path:e,auth:`auto`,responseFormat:`json`,signal:u})}catch(e){if(o(e)||u.aborted&&e instanceof Error&&e.cause instanceof Error&&e.cause.name===`AbortError`&&e.cause.cause===u.reason)return{kind:`transient`,reason:String(e)};throw e}if(!d.ok){let{problem:n}=d;if(n!==void 0&&a(n.status,n)){let e=c(n.retryAfterSeconds);return{kind:`transient`,reason:d.summary,...e===void 0?{}:{retryAfterSeconds:e}}}return{kind:`refused`,envelope:t(`GET ${e} failed: ${d.summary}`,d.warnings,{problem:n})}}let f=d.data,p=r.safeParse(typeof f==`object`&&f&&`response`in f?f.response:void 0);return p.success?{kind:`detail`,detail:p.data}:{kind:`refused`,envelope:t(`${e} returned an unexpected body: ${p.error.message}`)}}export{u as registerBuiltinRunWaitCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,f as t,t as n}from"./env-DGAe95Xm.js";import{c as r,r as i}from"./result-envelope-BMqcRDpc.js";import{z as a}from"./tool-policy-DG8pafmI.js";import{s as o}from"./openapi-call-
|
|
1
|
+
import{a as e,f as t,t as n}from"./env-DGAe95Xm.js";import{c as r,r as i}from"./result-envelope-BMqcRDpc.js";import{z as a}from"./tool-policy-DG8pafmI.js";import{s as o}from"./openapi-call-DRowSHyQ.js";import{a as s,r as c}from"./api-target-vxev2RKl.js";import{i as l,n as u,s as d,t as f}from"./api-key-credential-v7YT_b1y.js";import{n as p,t as m}from"./credential-redaction-Cl6Eny3X.js";import{n as h}from"./contract-SAu4Y_Kd.js";import{t as g}from"./openapi-composites-IdxI7cAF.js";import{c as _,f as v,m as y,n as b,r as x}from"./oauth-credential-D5ioBfGK.js";import{t as S}from"./oauth-login-BDOwNja7.js";var C=h(g,`revoke`);async function w(r){let a;try{a=c(t().host)}catch(e){return i(`auth logout: invalid API host — ${m(e)}`)}let o=await j(a),s=await E(a),l=await k(a,r),u=T(a,s,l);if(o===void 0)return u;let d={...u.data??{host:a,revoked:!1,forgotten:!1},presented:o};switch(o.state){case`revoked`:return{...u,summary:`${u.summary} The API key in ${n.authToken} is revoked; unset it in this shell.`,data:d,ids:[...u.ids,o.apiKeyId]};case`unconfirmed`:return{...i(`auth logout: revocation of the API key in ${n.authToken} was not confirmed — ${o.summary}`,[`Retry when the API is available, or revoke the key at ${e}/settings/api-keys.`]),data:d};case`notApiKey`:case`rejected`:return{...u,data:d,warnings:[...u.warnings,`${n.authToken} was not revoked — ${o.summary}; unset it in this shell.`]};default:throw Error(`Unsupported AUTH_TOKEN logout state`)}}function T(e,t,n){let a=t.state===`failed`?[`OAuth credential could not be removed — ${t.summary}`]:t.state===`forgotten`&&!t.revoked?[`OAuth refresh token was not revoked remotely — ${t.summary??`no revocation endpoint`}`]:[],o={host:e,revoked:!1,forgotten:!1,oauth:t};return n===null?t.state===`missing`?r(`No CLI credential is stored for this API host.`,o):t.state===`failed`?{...i(`auth logout: ${a[0]}`),data:o}:r(t.revoked?`OAuth credential revoked remotely and removed locally.`:`OAuth credential removed locally.`,o,{warnings:a}):{...n,data:{...n.data??o,oauth:t},warnings:[...n.warnings,...a]}}async function E(e){let t=await x(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await O(t.stored):{revoked:!1};try{await b(e)}catch(e){return{state:`failed`,summary:m(e)}}return{state:`forgotten`,...n}}async function D(e){let t=Reflect.get(await S(e),`revocation_endpoint`);return typeof t==`string`?y(t,`revocation endpoint`,!0):void 0}async function O(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await D(t);if(e===void 0)return{revoked:!1};let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({token:r,client_id:_(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:m(e,v(n))}}}async function k(e,t){let n;try{n=await l(e)}catch(e){return i(`auth logout: stored credential could not be read — ${m(e)}`)}if(n.state===`unavailable`)return{...i(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let a=n.stored,o=await A(a),s=o.outcome===`revoked`,c=a.activation!==`active`&&o.outcome===`rejected`;if(!s&&!c&&!t.forgetLocal)return{...i(`auth logout: remote revocation was not confirmed; local credential preserved — ${o.summary}`,[`Retry when the API is available. If an earlier response was lost after revocation, the retry can be unauthorized because revoked keys cannot authenticate.`,"Use `--forget-local` only to remove local bytes while accepting that the remote key may remain active."]),data:N(a,!1,!1)};try{if((await u(a)).state===`changed`)return{...i(`auth logout: local credential changed during logout; current credential preserved, logout incomplete`,[o.summary]),data:N(a,s,!1)}}catch(e){return{...i(`auth logout: local credential removal failed — ${m(e,[a.credential.secret])}`,[s?"The remote key is revoked. Re-run with `--forget-local` to retry local cleanup.":`Remote revocation was not confirmed; inspect auth status before retrying.`]),data:N(a,s,!1)}}return r(s?`API key revoked remotely and removed locally.`:c?`Stale pending CLI credential removed; its remote key can no longer authenticate and unacknowledged keys expire at the authorization deadline.`:`API key removed locally without confirmed remote revocation.`,N(a,s,!0),{ids:[a.credential.apiKey.id],warnings:s||c?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function A(e){let t=await M(e.credential.secret);return t.apiKey===null?t:t.apiKey.id!==e.credential.apiKey.id||t.apiKey.subject!==e.credential.apiKey.subject?{outcome:`unconfirmed`,summary:`remote response did not match the stored API key identity`}:t}async function j(e){let n=t().userBearerToken?.trim();if(n===void 0||n.length===0)return;let r=await l(e);if(r.state===`found`&&r.stored.credential.secret===n)return;let i=await M(n);return i.outcome===`revoked`&&i.apiKey!==null?{state:`revoked`,apiKeyId:i.apiKey.id}:i.refused?{state:`notApiKey`,summary:i.summary}:{state:i.outcome===`rejected`?`rejected`:`unconfirmed`,summary:i.summary}}async function M(e){let n={apiKey:null,refused:!1},r=s(t());try{let t=await o(r,{method:C.method,path:a(C.path,{},C.operationId),headers:{Authorization:`Bearer ${e}`}},d);if(t.ok&&t.redirect)return{...n,outcome:`unconfirmed`,summary:`remote key revocation returned unexpected redirect ${t.status}`};if(!t.ok){let r=t.problem.type!==`about:blank`,i=r&&t.problem.status===401;return{...n,outcome:i?`rejected`:`unconfirmed`,refused:r&&t.problem.status===403,summary:p(t.problem,[e])}}let i={id:t.data.id,subject:t.data.subject};return t.data.status===`REVOKED`?{apiKey:i,refused:!1,outcome:`revoked`,summary:`remote key revocation confirmed`}:{apiKey:i,refused:!1,outcome:`unconfirmed`,summary:`remote response did not confirm REVOKED status`}}catch(t){return{...n,outcome:`unconfirmed`,summary:m(t,[e])}}}function N(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:f(e.activation),revoked:t,forgotten:n}}export{A as n,w as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{t as logoutCliCredentials}from"./logout-Dxt8vao3.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{t as materializeCliOAuthBearerCredential,n as materializeSavedCliOAuthBearerCredential}from"./oauth-bearer-credential-CxuQ4uM5.js";
|
package/dist/chunks/{oauth-bearer-credential-DlyXyoGr.js → oauth-bearer-credential-CxuQ4uM5.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e}from"./package-DEeHDoOT.js";import{f as t,t as n}from"./env-DGAe95Xm.js";import{r}from"./auth-resolver-CRpJNNB2.js";import{o as i}from"./logging-DYzy2g8p.js";import{r as a}from"./api-target-vxev2RKl.js";import{i as o}from"./api-key-credential-v7YT_b1y.js";import{t as s}from"./credential-redaction-Cl6Eny3X.js";import{a as c}from"./credential-store-xkwn77zF.js";import{t as l}from"./api-key-bearer-credential-DpuLoYkG.js";import{a as u,f as d,h as f,n as p,o as m,t as h}from"./oauth-credential-D5ioBfGK.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(E())return;let o=async(t,a,o,c=!1)=>{if(await l(r),!E())throw c?a:D(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,T(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,T(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 y(e)}catch(t){return await S(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 x(t))}}if(t&&i===e.credential&&(C(i)||!await g()))return f(e,i);let a;try{let{verifyUserBearerToken:e}=await import(`./openapi-call-
|
|
1
|
+
import{a as e}from"./package-DEeHDoOT.js";import{f as t,t as n}from"./env-DGAe95Xm.js";import{r}from"./auth-resolver-CRpJNNB2.js";import{o as i}from"./logging-DYzy2g8p.js";import{r as a}from"./api-target-vxev2RKl.js";import{i as o}from"./api-key-credential-v7YT_b1y.js";import{t as s}from"./credential-redaction-Cl6Eny3X.js";import{a as c}from"./credential-store-xkwn77zF.js";import{t as l}from"./api-key-bearer-credential-DpuLoYkG.js";import{a as u,f as d,h as f,n as p,o as m,t as h}from"./oauth-credential-D5ioBfGK.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(E())return;let o=async(t,a,o,c=!1)=>{if(await l(r),!E())throw c?a:D(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,T(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,T(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 y(e)}catch(t){return await S(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 x(t))}}if(t&&i===e.credential&&(C(i)||!await g()))return f(e,i);let a;try{let{verifyUserBearerToken:e}=await import(`./openapi-call-Gchy3s8a.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 w(e.host,i,n),f(e,i)},f=(e,t)=>{E()||(b({...e,credential:t}),r?.(`oauth`))},h;try{h=a(t().host)}catch(e){throw D(`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(E())return;let e=await m(a(t().host));e.state===`found`&&(process.env[n.authToken]=e.stored.credential.tokens.access_token)}async function y(t){return await c(async()=>{let n=await m(t.host),r=n.state===`found`?n.stored:t;if(!u(r.credential))return r.credential;let{renewOAuthTokens:a}=await import(`./oauth-login-155QGdTQ.js`),o=h(r.credential.client,await a(r));try{await f(t.host,o)}catch(t){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(o.tokens)))})}return o})}function b(e){let t=e.credential.tokens.access_token,i;r(t,async()=>{if(i!==void 0||process.env[n.authToken]!==t||!u(e.credential))return i;delete process.env[n.authToken];let r=Error(`no saved credential could serve this command`);try{let{materializeCommandCredential:e}=await import(`./startup-auth-DfEgkGG8.js`);if(await e(`required`),E())return}catch(e){r=e}process.env[n.authToken]=t;let{BearerVerificationUnavailableError:a}=await import(`./openapi-call-Gchy3s8a.js`);if(r instanceof a)return r.problem;let o=r instanceof TypeError,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,T(e))};return o||(i=c),c})}async function x(e){let{OAuthError:t}=await import(`./dist-DGMIRNW7.js`);return e instanceof t}async function S(e){let{OAuthError:t,OAuthErrorCode:n}=await import(`./dist-DGMIRNW7.js`),r=n.InvalidGrant;return e instanceof t&&e.code===r}function C(e){if(e.verifiedAt===void 0)return!1;let t=Date.now()-new Date(e.verifiedAt).getTime();return t>=0&&t<9e5}async function w(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 T(e){return e===void 0?[]:d(e.credential.tokens)}function E(){return(process.env[n.authToken]?.trim().length??0)>0}function D(t,n,r,i){let a=r===void 0?``:` — ${s(r,T(i))}`,o=n??e().bin[0];return Error(`OAuth sign-in is required: ${t}. Run \`${o} auth login\` before retrying.${a}`)}export{v as n,y as r,_ as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{n as fetchAuthProviderCatalog,r as loginOAuthCredential,i as renewOAuthTokens}from"./oauth-login-
|
|
1
|
+
export{n as fetchAuthProviderCatalog,r as loginOAuthCredential,i as renewOAuthTokens}from"./oauth-login-BDOwNja7.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Gt as e,Yt as t}from"./auth-BNDyLTqp-z6VNZXaE.js";import{f as n}from"./env-DGAe95Xm.js";import{c as r,r as i}from"./result-envelope-BMqcRDpc.js";import{a,n as o,s}from"./openapi-call-
|
|
1
|
+
import{Gt as e,Yt as t}from"./auth-BNDyLTqp-z6VNZXaE.js";import{f as n}from"./env-DGAe95Xm.js";import{c as r,r as i}from"./result-envelope-BMqcRDpc.js";import{a,n as o,s}from"./openapi-call-DRowSHyQ.js";import{R as c}from"./webapi-B2JTupyg.js";import{a as l,r as u}from"./api-target-vxev2RKl.js";import{n as d,t as f}from"./credential-redaction-Cl6Eny3X.js";import{n as p,s as ee}from"./credential-store-xkwn77zF.js";import"./dist-oUS6BQ43.js";import{a as te,c as m,d as h,f as g,h as ne,m as _,p as v,r as y,s as b,t as x,u as S}from"./oauth-credential-D5ioBfGK.js";import{t as C}from"./provider-catalog-CT1LnhCO.js";import{f as w,o as T,s as E,u as re}from"./dist-Dt0qAmdj.js";import{r as ie}from"./oauth-bearer-credential-CxuQ4uM5.js";import{once as ae}from"node:events";import{stderr as D}from"node:process";import{setTimeout as oe}from"node:timers/promises";import{createServer as se}from"node:http";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 _(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:m(e),scope:h(e).join(` `),resource:S(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:_(c,`verification URI`,!0),expiresAt:t+o*1e3,intervalMilliseconds:(typeof s==`number`&&s>=0?s:5)*1e3}}async function L(n,r,i){let a=_(r.token_endpoint,`token endpoint`,!0),o=i.intervalMilliseconds,s=null;for(;Date.now()<i.expiresAt;){await oe(o);let r;try{r=await fetch(a,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:m(n),grant_type:M,device_code:i.deviceCode})})}catch(e){s=`the token endpoint was unreachable — ${f(e)}`,D.write(j);continue}if(r.status>=A){await r.body?.cancel(),s=`the token endpoint answered ${r.status}`,D.write(j);continue}s=null;let c=await F(r,`token`);if(r.ok){let e=t.safeParse(c);if(!e.success)throw Error(`token endpoint returned an invalid token response`);return e.data}let l=e.safeParse(c),u=l.success?l.data.error:`HTTP ${r.status}`;if(u!==`authorization_pending`){if(u===`slow_down`)o+=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=se((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: ${f(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(e){let t;try{t=u(n().host)}catch(e){return i(`auth login: invalid API host — ${f(e)}`)}let o=await y(t);if(o.state===`missing`)return G(t,e);if(o.state===`unavailable`)return i(`auth login: ${o.summary}`);if(o.state===`invalid`)return G(t,e,`Saved OAuth credential cannot be read — ${o.summary}`);let{stored:s}=o;if(te(s.credential))return await W(s,e);let l;try{l=await a(s.credential.tokens.access_token,S(s.credential.client))}catch(n){return n instanceof c?G(t,e,`Saved OAuth credential was rejected`):i(`auth login: saved OAuth credential could not be verified — ${f(n,g(s.credential.tokens))}`)}return l===`forbidden`?i(`auth login: ${H}`):l===null?G(t,e,`Saved OAuth credential was rejected`):r(`OAuth CLI access token is already stored and verified.`,$(s))}async function W(e,t){let n=await v(e.host);if(n.state===`unavailable`)return i(`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 a;try{a=await ie(e)}catch(i){return G(e.host,t,`Saved OAuth credential could not be renewed — ${f(i,g(r))}`,n)}J(n);let o=await Q(e.host,a,`OAuth CLI access token renewed and verified.`);if(!o.ok)return o;let s=await Z(a);return s.state===`failed`?i(`auth login: ${s.summary}`):s.state===`rejected`?G(e.host,t,`Renewed OAuth access token was rejected`,n):o}async function G(e,t,n,r){let a=r??await v(e);if(a.state===`unavailable`)return i(`auth login: ${a.summary}`);J(a),n!==void 0&&D.write(`${n}; continuing to browser sign-in.\n`);let o;try{let e=(await Y()).oauthClient;if(e==null)throw Error(`the API does not advertise an OAuth CLI client`);o=e}catch(e){return i(`auth login: OAuth configuration is unavailable — ${f(e)}`)}let s;try{s=await X(o)}catch(e){return i(`auth login: OAuth authorization-server discovery failed — ${f(e)}`)}if(t.noBrowser)return await K(e,o,s);let c=ce(32).toString(`base64url`),l;try{l=await B(z(o),c);let t=await w(b(o),{metadata:s,clientInformation:{client_id:m(o)},redirectUrl:l.redirectUri,resource:S(o),scope:h(o).join(` `),state:c});t.authorizationUrl.searchParams.delete(`prompt`);let n=await ee(t.authorizationUrl,{noBrowser:!1});n.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 (${n.reason}).\nOpen this private sign-in URL in a browser that can reach this machine's loopback callback:
|
|
4
4
|
${t.authorizationUrl.toString()}\nWaiting for the loopback callback...\n`);let r=await l.waitForAuthorizationCode();if(r.state===`timed-out`)return await l.close(),l=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)}})),bn=t(((t,n)=>{var{kConstruct:r}=Z(),{kEnumerableProperty:i,setHeader:a}=$(),{iteratorMixin:o,isValidHeaderName:s,isValidHeaderValue:c}=tt(),{webidl:l}=et(),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}})),xn=t(((t,n)=>{var{Headers:r,HeadersList:i,fill:a,getHeadersGuard:o,setHeadersGuard:s,setHeadersList:c}=bn(),{extractBody:l,cloneBody:u,mixinBody:d,streamRegistry:f,bodyUnusable:p}=gt(),m=$(),h=e(`node:util`),{kEnumerableProperty:g}=m,{isValidReasonPhrase:_,isCancelled:v,isAborted:y,isErrorLike:b,environmentSettingsObject:x}=tt(),{redirectStatusSet:S,nullBodyStatus:C}=Ye(),{webidl:w}=et(),{URLSerializer:T}=$e(),{kConstruct:E}=Z(),D=e(`node:assert`),{isomorphicEncode:O,serializeJavascriptValueToJSONString:k}=Qe(),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}})),Sn=t(((t,n)=>{var{extractBody:r,mixinBody:i,cloneBody:a,bodyUnusable:o}=gt(),{Headers:s,fill:c,HeadersList:l,setHeadersGuard:u,getHeadersGuard:d,setHeadersList:f,getHeadersList:p}=bn(),m=$(),h=e(`node:util`),{isValidHTTPToken:g,sameOrigin:_,environmentSettingsObject:v}=tt(),{forbiddenMethodsSet:y,corsSafeListedMethodsSet:b,referrerPolicy:x,requestRedirect:S,requestMode:C,requestCredentials:w,requestCache:T,requestDuplex:E}=Ye(),{kEnumerableProperty:D,normalizedMethodRecordsBase:O,normalizedMethodRecords:k}=m,{webidl:A}=et(),{URLSerializer:j}=$e(),{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,U,W=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=G({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=G({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=K(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 q(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},U=e=>{e.#i?.()},A.is.Request=e=>typeof e==`object`&&!!e&&#r in e}};i(W,ae,A.is.Request);function G(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 K(e){let t=G({...e,body:null});return e.body!=null&&(t.body=a(e.body)),t}function q(e,t,n,r){let i=new W(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(W.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:W,makeRequest:G,fromInnerRequest:q,cloneRequest:K,getRequestDispatcher:V,getRequestState:ae,removeRequestAbortListener:U}})),Cn=t(((t,n)=>{var r=e(`node:assert`),{runtimeFeatures:i}=nt(),{asciiLowercase:a}=Qe(),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}})),wn=t(((t,n)=>{var{makeNetworkError:r,makeAppropriateNetworkError:i,filterResponse:a,makeResponse:o,fromInnerResponse:s,getResponseState:c}=xn(),{HeadersList:l}=bn(),{Request:u,cloneRequest:d,getRequestDispatcher:f,getRequestState:p,removeRequestAbortListener:m}=Sn(),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}=tt(),H=e(`node:assert`),{safelyExtractBody:U,extractBody:W}=gt(),{redirectStatusSet:G,nullBodyStatus:K,safeMethodsSet:q,requestBodyHeader:oe,subresourceSet:se}=Ye(),ce=e(`node:events`),{Readable:le,pipeline:ue,finished:de,isErrored:fe,isReadable:pe}=e(`node:stream`),{addAbortListener:me,bufferToLowerCasedHeaderName:he}=$(),{SocketError:ge}=Q(),{dataURLProcessor:J,serializeAMimeType:Y,minimizeSupportedMimeType:X}=$e(),{getGlobalDispatcher:_e}=tn(),{webidl:ve}=et(),{STATUS_CODES:ye}=e(`node:http`),{bytesMatch:be}=Cn(),{isomorphicEncode:xe}=Qe(),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 ce{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,se.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`||K.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=U(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=W(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=W(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:U(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`):(G.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 oe)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=U(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);!q.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=U(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`&&G.has(t),c=[];if(a.method!==`HEAD`&&a.method!==`CONNECT`&&!K.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 le({read:()=>e.resume()});let u=t=>this.onResponseError(e,t);d({status:t,statusText:r,headersList:o,body:c.length?ue(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}})),Tn=t(((t,n)=>{var r=e(`node:assert`),{URLSerializer:i}=$e(),{isValidHeaderName:a}=tt();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}})),En=t(((t,n)=>{var r=e(`node:assert`),{kConstruct:i}=Z(),{urlEquals:a,getFieldValues:o}=Tn(),{kEnumerableProperty:s,isDisturbed:c}=$(),{webidl:l}=et(),{cloneResponse:u,fromInnerResponse:d,getResponseState:f}=xn(),{Request:p,fromInnerRequest:m,getRequestState:h}=Sn(),{fetching:g}=wn(),{urlIsHttpHttpsScheme:_,readAllBytes:v}=tt(),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}})),Dn=t(((e,t)=>{var{Cache:n}=En(),{webidl:r}=et(),{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}})),On=t(((e,t)=>{t.exports={maxAttributeValueSize:1024,maxNameValuePairSize:4096}})),kn=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}})),An=t(((t,n)=>{var{collectASequenceOfCodePointsFast:r}=Qe(),{maxNameValuePairSize:i,maxAttributeValueSize:a}=On(),{isCTLExcludingHtab:o}=kn(),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}})),jn=t(((e,t)=>{var{parseSetCookie:n}=An(),{stringify:r}=kn(),{webidl:i}=et(),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}})),Mn=t(((e,t)=>{var{webidl:n}=et(),{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}})),Nn=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}}})),Pn=t(((t,n)=>{var{states:r,opcodes:i}=Nn(),{isUtf8:a}=e(`node:buffer`),{removeHTTPWhitespace:o}=$e(),{collectASequenceOfCodePointsFast:s}=Qe();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}})),Fn=t(((t,n)=>{var{runtimeFeatures:r}=nt(),{maxUnsigned16Bit:i,opcodes:a}=Nn(),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}})),In=t(((t,n)=>{var{uid:r,states:i,sentCloseFrameState:a,emptyBuffer:o,opcodes:s}=Nn(),{parseExtensions:c,isClosed:l,isClosing:u,isEstablished:d,isConnecting:f,validateCloseCodeAndReason:p}=Pn(),{makeRequest:m}=Sn(),{fetching:h}=wn(),{Headers:g,getHeadersList:_}=bn(),{getDecodeSplit:v}=tt(),{WebsocketFrameSend:y}=Fn(),b=e(`node:assert`),{runtimeFeatures:x}=nt(),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}})),Ln=t(((t,n)=>{var{createInflateRaw:r,Z_DEFAULT_WINDOWBITS:i}=e(`node:zlib`),{isValidClientWindowBits:a}=Pn(),{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)})}}}})),Rn=t(((t,n)=>{var{Writable:r}=e(`node:stream`),i=e(`node:assert`),{parserStates:a,opcodes:o,states:s,emptyBuffer:c,sentCloseFrameState:l}=Nn(),{isValidStatusCode:u,isValidOpcode:d,websocketMessageReceived:f,utf8Decode:p,isControlFrame:m,isTextBinaryFrame:h,isContinuationFrame:g}=Pn(),{failWebsocketConnection:_}=In(),{WebsocketFrameSend:v}=Fn(),{PerMessageDeflate:y}=Ln(),{MessageSizeExceededError:b}=Q(),{defaultWebSocketMaxFragments:x,defaultWebSocketMaxPayloadSize:S}=Ge();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}}}})),zn=t(((e,t)=>{var{WebsocketFrameSend:n}=Fn(),{opcodes:r,sendHints:i}=Nn(),a=bt(),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}})),Bn=t(((t,n)=>{var{isArrayBuffer:r}=e(`node:util/types`),{webidl:i}=et(),{URLSerializer:a}=$e(),{environmentSettingsObject:o}=tt(),{staticPropertyDescriptors:s,states:c,sentCloseFrameState:l,sendHints:u,opcodes:d}=Nn(),{isConnecting:f,isEstablished:p,isClosing:m,isClosed:h,isValidSubprotocol:g,fireEvent:_,utf8Decode:v,toArrayBuffer:y,getURLRecord:b}=Pn(),{establishWebSocketConnection:x,closeWebSocketConnection:S,failWebsocketConnection:C}=In(),{ByteParser:w}=Rn(),{kEnumerableProperty:T}=$(),{getGlobalDispatcher:E}=tn(),{ErrorEvent:D,CloseEvent:O,createFastMessageEvent:k}=Mn(),{SendQueue:A}=zn(),{WebsocketFrameSend:j}=Fn(),{channels:M}=Je(),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}})),Vn=t(((e,t)=>{var{webidl:n}=et(),{validateCloseCodeAndReason:r}=Pn(),{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}})),Hn=t(((t,n)=>{var{addAbortListener:r}=e(`node:events`),{environmentSettingsObject:i,readableStreamClose:a}=tt(),{states:o,opcodes:s,sentCloseFrameState:c}=Nn(),{webidl:l}=et(),{getURLRecord:u,isValidSubprotocol:d,isEstablished:f,utf8Decode:p}=Pn(),{establishWebSocketConnection:m,failWebsocketConnection:h,closeWebSocketConnection:g}=In(),{channels:_}=Je(),{WebsocketFrameSend:v}=Fn(),{ByteParser:y}=Rn(),{WebSocketError:b,createUnvalidatedWebSocketError:x}=Vn(),{kEnumerableProperty:S}=$(),{utf8DecodeBytes:C}=Ze(),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}})),Un=t(((e,t)=>{var{makeRequest:n}=Sn();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}})),Wn=t(((t,n)=>{var r=e(`node:buffer`),{Transform:i}=e(`node:stream`),{isASCIINumber:a,isValidLastEventId:o}=Un(),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())}}}})),Gn=t(((t,n)=>{var{pipeline:r}=e(`node:stream`),{fetching:i}=wn(),{webidl:a}=et(),{EventSourceStream:o}=Wn(),{parseMIMEType:s}=$e(),{createFastMessageEvent:c}=Mn(),{isNetworkError:l}=xn(),{cloneRequest:u}=Sn(),{isValidHeaderValue:d,kEnumerableProperty:f}=$(),{environmentSettingsObject:p}=tt(),{createPotentialCORSRequest:m}=Un(),{getGlobalDispatcher:h}=tn(),{isomorphicDecode:g}=Qe(),_=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}})),Kn=t(((e,t)=>{var n=yt(),r=at(),i=St(),a=Ct(),o=wt(),s=Tt(),c=Et(),l=At(),u=kt(),d=jt(),f=Nt(),p=Pt(),m=Q(),h=$(),{InvalidArgumentError:g}=m,_=Ht(),v=st(),y=qt(),{MockCallHistory:b,MockCallHistoryLog:x}=Jt(),S=Zt(),C=Yt(),w=en(),T=Ut(),E=Mt(),{getGlobalDispatcher:D,setGlobalDispatcher:O}=tn(),k=nn(),A=rn();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:an(),responseError:on(),retry:sn(),dump:cn(),dns:ln(),cache:hn(),decompress:gn(),deduplicate:vn()},t.exports.cacheStores={MemoryCacheStore:pn()};var j=yn();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=wn().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=bn().Headers,t.exports.Response=xn().Response,t.exports.Request=Sn().Request,t.exports.FormData=rt().FormData;var{setGlobalOrigin:I,getGlobalOrigin:L}=Xe();t.exports.setGlobalOrigin=I,t.exports.getGlobalOrigin=L;var{CacheStorage:R}=Dn(),{kConstruct:ee}=Z();t.exports.caches=new R(ee);var{deleteCookie:z,getCookies:B,getSetCookies:te,setCookie:ne,parseCookie:V}=jn();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}=$e();t.exports.parseMIMEType=re,t.exports.serializeAMimeType=ie;var{CloseEvent:ae,ErrorEvent:H,MessageEvent:U}=Mn(),{WebSocket:W,ping:G}=Bn();t.exports.WebSocket=W,t.exports.CloseEvent=ae,t.exports.ErrorEvent=H,t.exports.MessageEvent=U,t.exports.ping=G,t.exports.WebSocketStream=Hn().WebSocketStream,t.exports.WebSocketError=Vn().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:K}=Gn();t.exports.EventSource=K;function q(){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=q}))(),qn=11e4,Jn=8,Yn=new Set([`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`,`UND_ERR_SOCKET`,`UND_ERR_CONNECT_TIMEOUT`,`UND_ERR_HEADERS_TIMEOUT`,`UND_ERR_BODY_TIMEOUT`]),Xn=new Map;function Zn(){let e=process.env.AVENTURE_API_SOCKET_PATH,t={headersTimeout:0,bodyTimeout:0},n=Xn.get(e??``)??new Kn.Dispatcher1Wrapper(e?new Kn.Agent({...t,connect:(t,n)=>(0,Kn.buildConnector)({socketPath:e,timeout:qn})({...t,protocol:`http:`},n)}):new Kn.EnvHttpProxyAgent({...t,proxyTunnel:!0}));return Xn.set(e??``,n),n}async function Qn(e,t,n){let r=Number(process.env.AVENTURE_API_REQUEST_TIMEOUT_MS),i=t.timeoutMs??(Number.isInteger(r)&&r>0?r:qn),a=Date.now()+i,o={...t,headers:{...t.headers,[b]:L()??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`},s=t.followRollover===!0,c=(t,r={waitMs:0,deadline:a})=>$n(e,t,n,i,r.deadline,r.waitMs),l=await c(o),u=Ne(l);if(!l.ok&&l.headers!==void 0&&u===void 0){let{idempotent:n,replayRateLimit:r}=t,i=ue(l.status,l.problem,n===!0,r);i!==void 0&&Date.now()+i<a&&(ne({component:`aventure-api-client`,event:`request_retry`,fields:{...ar(o,e.host,o.headers[b]),retryKind:`http_refusal`,status:l.status,waitMs:Math.round(i)}}),l=await c({...o,idempotent:!1},{waitMs:i,deadline:a}))}let d=(!s||t.idempotent===!0)&&Ne(l)!==void 0;if(!s&&!d)return l;let f=!d&&!l.ok&&l.problem.code===`search_still_running`&&Date.now()<a?await c({...o,headers:{...o.headers,Prefer:ye(o.headers.Prefer,[`respond-async`])}}):l,p=!f.ok&&f.problem.code===`async_lookup_sign_in_required`?l:f;if(!p.ok&&!d)return p;let m={...o.headers,Accept:`application/json`};return Le(p,{origin:new URL(nr(e.host,`/`)).origin,deadline:a,signal:t.signal,rollsOver:s},(e,n)=>c({method:`GET`,path:e,headers:m,signal:t.signal},{waitMs:0,deadline:Date.now()+n}))}async function $n(e,t,r,i,a,o=0){let c=nr(e.host,t.path,t.searchParams),l=t.headers[b],u=ar(t,e.host,l),d={Accept:`application/json`,"User-Agent":n(),...t.headers,...S()},f=t.body instanceof FormData?t.body:JSON.stringify(t.body);f!==void 0&&t.contentType!==void 0&&(d[`Content-Type`]=t.contentType);let p=performance.now();B({component:`aventure-api-client`,event:`request`,fields:{...u,hasBody:t.body!==void 0}});let m=``,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 B({component:`aventure-api-client`,event:`request_failed`,message:V(e),fields:{...u,status:_?.status,timeoutMs:i,failureKind:r,durationMs:Math.round(performance.now()-p),...te(e)},error:e}),r},x=()=>(h=E(new URL(c).origin,j),m=t.unconfirmedWriteAdvice===void 0?``:`; ${t.unconfirmedWriteAdvice}`,h);try{o>0&&await ge(o,void 0,{signal:t.signal}),_=await tr(c,t,d,f,i,a,x),g=[502,503,504].includes(_.status)?`failure`:`success`,v=`body`;let e={status:_.status,headers:Object.fromEntries(_.headers)},n={...u,status:_.status},s=_.headers.get(`location`),l=ir.has(_.status)&&s!==null;l&&await _.body?.cancel().catch(()=>ne({component:`aventure-api-client`,event:`redirect_body_cleanup_failed`,message:`Redirect body cleanup failed after headers were received`,fields:n}));let h=l?``:await Oe(_,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: ${V(e)}`});v=`schema`;let b=l||h instanceof Uint8Array||h instanceof RangeError?h:or(h,_.headers.get(`content-type`),_.ok?r:void 0,n,m),S=b instanceof SyntaxError||b instanceof RangeError;S&&y(b);let C=Math.round(performance.now()-p);if(_.ok&&!S||l)return B({component:`aventure-api-client`,event:`response`,fields:{...n,durationMs:C}}),l?{ok:!0,redirect:!0,...e,location:s,data:void 0}:{ok:!0,...e,data:b};let w=S?b.message:b??h,T=le(K(_.status,w,d),_.headers);T.disposition===`TERMINAL`&&(g=`success`);let E=q(T,d),D=E.code===`search_still_running`&&(t.followRollover===!0||_.headers.has(`location`));return D&&(g=`success`),(D?B:ne)({component:`aventure-api-client`,event:D?`following_job`:`problem_response`,fields:{...u,durationMs:C,...ce(E,d)}}),{ok:!1,...e,problem:E}}catch(e){let t=y(e);if(e instanceof R)return{ok:!1,status:503,problem:K(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=V(e),r=te(e).causeChain,i=r===void 0?``:`: ${String(r)}`;throw Error(v===`body`?`Response body read from ${s()} failed: ${n}${m}`:`request to ${s()} failed: ${n}${i}${m}`,{cause:e})}finally{h?.finish(g)}}function er(e){for(let t=0;t<Jn&&e instanceof Error;t+=1){if(`code`in e&&typeof e.code==`string`)return Yn.has(e.code);if(e.name===`TimeoutError`||e.message===`socket hang up`)return!0;e=e.cause}return!1}async function tr(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=Zn(),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=AbortSignal.any([AbortSignal.timeout(Math.min(i,d)),...t.signal?[t.signal]:[]]),p;try{return u>1&&await ge(fe(),void 0,{signal:f}),f.throwIfAborted(),p=o(),await fetch(e,{method:t.method,headers:n,body:r??null,signal:f,dispatcher:c,redirect:`manual`})}catch(n){if(n instanceof R)throw n;let r=f.aborted?f.reason:n;if(u>=l||t.signal?.aborted===!0||Date.now()>=a||!er(r))throw r;p?.finish(`failure`),ne({component:`aventure-api-client`,event:`request_retry`,message:V(n),fields:{...ar(t,new URL(e).host,s),retryKind:`transport`,attempt:u,...te(n)},error:n})}}}function nr(e,t,n){let r=new URL(t,e.startsWith(`http`)?e:`https://${e}`);for(let[e,t]of Object.entries(n??{}))t!==void 0&&r.searchParams.set(e,String(t));return r.toString()}var rr=new Set([202,204,205]),ir=new Set([301,302,303,307,308]);function ar(e,t,n){let{method:r,path:i,operationId:a}=e;return{method:r,host:t,path:T(i),requestId:n,operationId:a}}function or(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(ne({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&&rr.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 sr(e,t,n,r,i){let a=r(cr(e,t,n,!1));return m(a,i)?a:r(cr(e,t,n,!0))}function cr(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:[`${e}${i.statusUrl}`]};let{data:a}=n,o=[`${e}${t}`],s=dr(a)?a.sourceDocumentId:void 0;return typeof s==`string`?{ids:[s],references:[...o,`${e}/v1/research/source-documents/${s}/body`]}:{ids:r?ur(a):[],references:o}}var lr=2;function ur(e,t=0){let n=t===0&&Array.isArray(e)?e:dr(e)&&Array.isArray(e.content)?e.content:void 0;return n===void 0?!dr(e)||t>=lr?[]:Object.values(e).flatMap(e=>ur(e,t+1)):n.flatMap(e=>{if(!dr(e))return[];let t=dr(e.entity)?e.entity:e.person,n=dr(t)&&dr(t.core)?t.core.id:void 0,r=dr(e.core)?e.core.id:e.id??n;return typeof r==`string`||typeof r==`number`?[String(r)]:[]})}var dr=e=>typeof e==`object`&&!!e&&!Array.isArray(e),fr=`actorType`,pr=`agentChassis`,mr=`agentModel`,hr=[fr,pr,mr],gr=`AVENTURE_AGENT_CHASSIS`,_r=`AVENTURE_AGENT_MODEL`,vr=[{chassis:`kimi-cli`,envNames:[`KIMI_MODEL`]},{chassis:`grok-build-cli`,envNames:[`GROK_HOME`,`GROK_MANAGED_BY_NPM`,`GROK_MANAGED_BY_INTERNAL`]},{chassis:`claude-code`,envNames:[`CLAUDECODE`,`CLAUDE_CODE`]},{chassis:`pi-cli`,envNames:[`PI_CODING_AGENT`]},{chassis:`codex-cli`,envNames:[`CODEX_MANAGED_BY_NPM`,`CODEX_SANDBOX`,`CODEX_THREAD_ID`,`CODEX_HOME`]},{chassis:`opencode`,envNames:[`OPENCODE_TERMINAL`]}],yr=[{chassis:`kimi-cli`,envNames:[`KIMI_MODEL`]},{chassis:`grok-build-cli`,envNames:[`GROK_MODEL`,`XAI_MODEL`]},{chassis:`pi-cli`,envNames:[`PI_MODEL`]}],br=[`OLLAMA_MODEL`,`OLLAMA_LAUNCH_MODEL`],xr=[`claude-code`,`claude-agent-sdk`],Sr=`codex-cli`,Cr=`opencode`;function wr(e){let t=Ir(e);return t.has(fr)||t.has(pr)&&t.has(mr)}function Tr({operation:e,searchParams:t,env:n=process.env,clientInfo:r}){if(!wr(e)){if(hr.some(e=>t?.[e]!==void 0)){let e={...t};for(let t of hr)delete e[t];return p(`Agent provenance not applicable`,e)}return p(`Agent provenance unchanged`,t)}let i=Br(t?.[fr]),a=i?.toLowerCase();if(i&&a!==`agent`&&a!==`employee`)return g(`${e.operationId} has unknown provenance actorType.`,[`Use actorType=agent or actorType=employee. actorType is optional only at the API boundary when a complete agent pair or employee JWT lets the resolver infer it before domain and write-lane enforcement.`]);let o=Br(t?.[pr]),s=Br(t?.[mr]),c=kr(n,r);if(a===`employee`)return o||s||c.status!==`missing`?g(`${e.operationId} has mixed employee and agent provenance.`,[`An agent runtime cannot claim employee attribution; use the runtime's agent provenance carrier.`]):p(`Employee provenance explicit`,{...t,actorType:`employee`});let l=zr(n,gr),u=zr(n,_r);if(o&&l&&o!==l)return g(Dr(e,`chassis`),[Or({param:pr,flag:`--agent-chassis`,envName:gr,envValue:l,explicitValue:o})]);if(s&&u&&s!==u)return g(Dr(e,`model`),[Or({param:mr,flag:`--agent-model`,envName:_r,envValue:u,explicitValue:s})]);if(o&&s){if(c.status===`partial`){let i=Mr(n,r);return o!==Fr(r?.name)&&o===Sr?g(`${e.operationId} rejected: ${Sr} binds its pair through its PreToolUse hook.`,[c.warning,`Run the CLI directly without --agent-chassis or --agent-model.`]):l===void 0&&u===void 0&&i.includes(o)?p(`Agent provenance explicit`,{...t,actorType:`agent`}):g(`${e.operationId} rejected: --agent-chassis ${o} is not this runtime.`,[c.warning,i.length===0?`Set ${gr} and ${_r} together.`:`This shell shows ${i.join(` and `)}. If that is you, pass --agent-chassis ${i.join(` or `)} --agent-model <your current model>; a different runtime launched from it sets ${gr} and ${_r} to its own pair.`])}let i=l===void 0&&o!==Sr&&Mr(n,r).includes(o);return c.status===`complete`&&!i&&(o!==c.pair.agentChassis||s!==c.pair.agentModel)?g(`${e.operationId} rejected: explicit agent provenance disagrees with the runtime environment.`,[`Detected ${c.pair.agentChassis}/${c.pair.agentModel} from runtime signals.`,`You passed --agent-chassis ${o} --agent-model ${s}.`,`Omit both flags, or set AVENTURE_AGENT_CHASSIS and AVENTURE_AGENT_MODEL after verifying the session.`]):p(`Agent provenance explicit`,{...t,actorType:`agent`})}return o||s?g(Er(e),[`Pass both agentChassis and agentModel, or omit both so the API can infer an employee actor from an authenticated user JWT session or this caller can auto-fill a verified local agent pair.`]):c.status===`missing`?a===`agent`?g(Er(e),[`actorType=agent requires agentChassis and agentModel before the API can build the enforced domain actor.`]):p(`Provenance left for API-boundary actor inference`,t):c.status===`partial`?g(Er(e),[c.warning,`Pass agentChassis and agentModel together, or neither.`]):p(`Agent provenance auto-filled`,{...t,actorType:`agent`,agentChassis:c.pair.agentChassis,agentModel:c.pair.agentModel})}function Er(e){return`${e.operationId} requires complete agent provenance.`}function Dr(e,t){return`${e.operationId} rejected: explicit agent ${t} disagrees with the runtime environment.`}function Or(e){return[`Your runtime environment declares ${e.envName}=${e.envValue}, but you passed ${e.flag} ${e.explicitValue} (query param ${e.param}).`,`The environment value comes from the container/runtime you are executing inside and is almost always correct.`,`If you (the LLM agent) believe the environment is wrong, investigate the container configuration first — do not override with a guess.`,`Otherwise, omit ${e.flag} entirely and the CLI will auto-fill from ${e.envName} (and ${_r} for the model). LLM agents hallucinate provenance frequently; stop providing false parameters.`].join(` `)}function kr(e,t){let n=zr(e,gr),r=zr(e,_r);if(n&&r)return{status:`complete`,pair:{agentChassis:n,agentModel:r}};if(n||r)return{status:`partial`,warning:`${gr} and ${_r} must be set together.`};let i=Mr(e,t),a=i.flatMap(t=>{let n=Nr(e,t);return n?[{agentChassis:t,agentModel:n}]:[]});if(a[0])return{status:`complete`,pair:a[0]};let o=i.filter(e=>e!==Cr),s=jr(i),c=s===Cr||o.some(e=>e===`codex-cli`||Pr(e))?void 0:Lr(e,...br);return s&&c?{status:`complete`,pair:{agentChassis:s,agentModel:c}}:i.length>0?{status:`partial`,warning:`${i.join(` and `)} ${i.length===1?`was`:`were`} detected, but no verified model source was present.`}:c?{status:`partial`,warning:`A model was detected, but no verified agent chassis source was present.`}:{status:`missing`,warning:`No verified local agent chassis/model pair was present.`}}function Ar(e=process.env,t){return zr(e,gr)??jr(Mr(e,t))}function jr(e){let t=e.filter(e=>e!==Cr);return t.length===1?t[0]:e.length===1?e[0]:void 0}function Mr(e,t){let n=Fr(t?.name);return n?[n]:vr.filter(t=>t.envNames.some(t=>Rr(e,t))).map(e=>e.chassis)}function Nr(e,t){let n=yr.find(e=>e.chassis===t);return n?Lr(e,...n.envNames):void 0}function Pr(e){return e!==void 0&&xr.some(t=>t===e)}function Fr(e){let t=e?.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim();if(t){if(t.includes(`claude`)&&t.includes(`sdk`))return`claude-agent-sdk`;if(t===`claude code`||t.includes(`claude code`))return`claude-code`;if(t===`codex`||t.includes(`codex`))return`codex-cli`;if(t===`kimi`||t.includes(`kimi`))return`kimi-cli`;if(t.includes(`hermes`))return`hermes-cli`;if(t.includes(`grok`))return`grok-build-cli`;if(t.includes(`mistral vibe`))return`mistral-vibe-cli`;if(t===`pi`||t===`pi cli`)return`pi-cli`}}var Ir=e=>new Set((e.parameters??[]).filter(e=>e.in===`query`).map(e=>e.name)),Lr=(e,...t)=>t.map(t=>zr(e,t)).find(e=>e!==void 0);function Rr(e,t){let n=zr(e,t)?.toLowerCase();return n!==void 0&&n!==`0`&&n!==`false`&&n!==`no`}function zr(e,t){return e[t]?.trim()||void 0}function Br(e){if(e===void 0)return;let t=typeof e==`object`?e[0]:e;return t===void 0?void 0:String(t).trim()||void 0}var Vr={AVENTURE_JOB_NAME:`X-Job-Name`,AVENTURE_TIER:`X-Tier`,AVENTURE_JOB_KEY:`X-Job-Key`},Hr=`X-Agent-Chassis`,Ur=/^[A-Za-z0-9._:-]{1,120}$/;function Wr(e){let t=[...Object.entries(Vr).map(([e,t])=>[t,process.env[e]?.trim()]),[Hr,Ar(process.env,e)]];return Object.fromEntries(t.flatMap(([e,t])=>t&&Ur.test(t)?[[e,t]]:[]))}function Gr(e,t){if(t===void 0)return e;let n=k(re().paths,`get`,t);if(n===null)throw Error(`No bundled operation serves the polled job route GET ${t}`);return n.operation}function Kr(e,t,n,r){let i=e.responses[String(t)]?.content;return n===void 0?n:qr(n,i?.[`application/json`]?.schema,r).value}function qr(e,t,n){let r=ti(t,n);if(r===void 0||typeof e!=`object`||!e)return{value:e,dropped:0};let i=[...r.oneOf??[],...r.anyOf??[]].filter(t=>Yr(ti(t,n),e));if(r.properties===void 0&&i.length>0)return i.map(t=>qr(e,t,n)).reduce((e,t)=>t.dropped<e.dropped?t:e);if(Array.isArray(e))return Jr(e,r,n);let a=Xr(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}:qr(t,r,n);return o+=i.dropped,[[e,i.value]]});return{value:Object.fromEntries(s),dropped:o}}function Jr(e,t,n){let r=t.items??(t.allOf??[]).find(e=>e.items!==void 0)?.items,i=e.map(e=>qr(e,r,n));return{value:i.map(e=>e.value),dropped:i.reduce((e,t)=>e+t.dropped,0)}}function Yr(e,t){return e===void 0?!1:Array.isArray(t)?e.items!==void 0||$r(e).includes(`array`):e.type===void 0&&e.properties===void 0||ei(e)||Qr(e).length>0}function Xr(e,t){let n=new Map,r;return Zr(e,t,n,new Set,e=>{r??=e})&&n.size>0?{properties:n,additionalProperties:r}:void 0}function Zr(e,t,n,r,i){let a=e.$ref;if(a!==void 0){if(r.has(a))return!0;r.add(a)}let o=ti(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=Qr(o);return o.properties===void 0&&s.length===0?o.type!==void 0&&!ei(o):s.every(e=>Zr(e,t,n,r,i))}function Qr(e){return[...e.allOf??[],...e.oneOf??[],...e.anyOf??[]]}function $r(e){return e.type===void 0?[]:[e.type].flat()}function ei(e){return e.properties!==void 0||$r(e).includes(`object`)}function ti(e,t){let n=C(e);return n===void 0?e:t[n]}var ni=class extends Error{problem;constructor(e){let{status:t,title:n,detail:r,code:i,retryAfterSeconds:a}=e;super(`OAuth bearer verification ${t===429?`was rate limited`:`is unavailable`}: ${t} ${n}${r?` — ${r}`:``}`+(typeof i==`string`?` [code: ${i}]`:``)+(typeof a==`number`?` [retry after ${a} seconds]`:``)),this.problem=e,this.name=`BearerVerificationUnavailableError`}};async function ri(e,t,n=[],r){let i=`authorizeOperations`,a=await Qn(li(c()),{method:`POST`,path:oi(i,{}),headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`},body:{operation:[...n]},operationId:i,idempotent:!0,replayRateLimit:!1,timeoutMs:r},Ee);if(a.ok&&a.redirect)throw new ni(K(a.status,`Unexpected authorization redirect`));if(!a.ok&&a.status!==401&&a.status!==403)throw new ni(a.problem);if(!a.ok)return a.status===403?`forbidden`:null;if(!e.includes(`.`))return a.data;try{let{typ:t}=H(e);if(t!==`at+jwt`&&t!==`application/at+jwt`)return a.data}catch{return a.data}let{aud:o}=U(e);if(o===void 0)return a.data;if(t===void 0)throw Error(`OAuth bearer verification is unavailable`);let s=Array.isArray(o)?o:[o];return s.length===1&&s[0]===t.href?a.data:null}var ii=`MCP transport credential is read-only; refused an authenticated upstream call.`,ai=11e4;function oi(e,t){let n=O(re().paths,e);if(!n)throw Error(`OpenAPI operationId not found: ${e}`);return z(n.template,y(n.operation,t,e),e)}function si(e){let t=e.pathParams??{};try{if(e.operationId!==void 0){let n=O(re().paths,e.operationId);if(n===null)return g(`OpenAPI operationId not found: ${e.operationId}`);let r=oi(e.operationId,t);return p(`Resolved ${e.operationId}`,{...n,path:r})}if(e.method===void 0||e.path===void 0)return g(`Pass operationId or method+path.`);let n=w(e.method),r=e.path;re().paths[r]?.[n]===void 0&&r.includes(`{`)&&(r=Object.entries(re().paths).find(([t,r])=>{let i=r[n];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 i=re().paths[r]?.[n],a=z(r,i===void 0?t:y(i,t,e.path),e.path),o=k(re().paths,n,a);return o===null?g(`OpenAPI operation not found for ${e.method} ${T(a)}`):(i===void 0&&y(o.operation,t,e.path),p(`Resolved ${o.operation.operationId}`,{...o,path:a}))}catch(e){return g(e instanceof Error?e.message:String(e))}}async function ci(e){let t=Number(process.env.AVENTURE_API_REQUEST_TIMEOUT_MS),n=Date.now()+(Number.isInteger(t)&&t>0?t:ai),r=k(re().paths,w(e.method),e.path);if(!r)return g(`OpenAPI operation not found for ${e.method} ${T(e.path)}`,[`Use a path in this package's OpenAPI contract; undocumented routes are not supported.`]);let i=r.operation,a=A(i.requestBody?.content),o=ee(a,e.contentType);if(!o.ok||o.data===null)return g(o.summary,o.warnings);let c=_e(i,e.headers);if(!c.ok||c.data===null)return g(c.summary,c.warnings);let l=e.requesterScope??`write`,m=e.auth===`auto`?(i.security?.length??0)>0?`bearer`:`none`:e.auth,y=x();if(l===`read`&&y===void 0&&(m===`write`||m===`bearer`))return g(ii,[`Resolved upstream auth=${m} for ${e.method} ${e.path}.`,`Pass auth='read' explicitly for POST read endpoints, or sign in with an account that permits the call.`]);let b=N(e.body);if(!b.ok)return g(b.summary,b.warnings);if(I(o.data,re().components.schemas)&&b.data!==void 0&&!Array.isArray(b.data))return g(`${i.operationId} requires a JSON array body.`);let S=i.operationId;if(e.responseFormat===`xlsx`&&!Y(i))return g(`This operation does not offer XLSX; use --csv.`);let C=e.responseFormat===`csv`||e.responseFormat===`xlsx`,E=!C&&e.responseBytes===!0&&P(i),O=E?`*/*`:X(e.responseFormat??`auto`,i),j=await v();if(j!==void 0)return oe(`Auth`,j);let L=e.preparedAuth===void 0?y===void 0?ui(m,i,{searchParams:e.searchParams,body:b.data}):d(`none`):p(`reused prepared auth`,e.preparedAuth);if(!L.ok||!L.data)return g(L.summary,L.warnings);let R=e.preparedAuth===void 0&&y!==void 0?{...L.data,credential:u.authToken,headers:{Authorization:`Bearer ${y}`}}:L.data;e.onAuthPrepared?.(R);let z=Tr({operation:i,searchParams:he(i,e.searchParams,b.data,R.headers.Authorization),clientInfo:e.clientInfo});if(!z.ok)return g(z.summary,z.warnings);let B=z.data??void 0,te=di(e.path,B),ne=Fe(i,e.method,te),V=li(L.data.env),H=li({...V,host:s()}).host,U={method:e.method,endpoint:te,operationId:S},W=await M(i,b.data,e.contentType,{deadline:n,signal:e.signal,defaultContentType:e.method===`PATCH`?`application/merge-patch+json`:e.method===`POST`||e.method===`PUT`?`application/json`:void 0});if(!W.ok||W.data===null)return g(W.summary,W.warnings,{httpStatus:W.httpStatus});if(e.signal?.aborted||Date.now()>=n)return g(`Request canceled or invocation deadline exceeded before upload.`);let G=F({method:e.method,path:r.template,operation:i,includeBinary:!0}),K={method:e.method,path:te,headers:{...be(i,c.data,ne),...R.headers,...Wr(e.clientInfo),Accept:O},body:W.data.body,contentType:W.data.contentType,operationId:S,readbackOperationId:i[`x-aventure-mutation-readback`]?.readOperationId,idempotent:e.method===`POST`&&G?.scope===`read`&&G.mutates!==!0&&i[`x-aventure-mutation-readback`]===void 0,followRollover:Ie(Object.keys(i.responses)),signal:AbortSignal.any([AbortSignal.timeout(Math.max(1,n-Date.now())),...e.signal?[e.signal]:[]])};e.onDispatch?.();let q=E?await Qn(V,{...K,responseBytes:!0}):C?await Qn(V,{...K,responseBytes:`negotiated`},h):await Qn(V,K,h),ce=S??e.method;if(!q.ok)return oe(`${ce} failed`,q.problem,[`endpoint=${te}`]);if(e.responseFormat===`xlsx`&&q.headers[`content-type`]?.split(`;`)[0]?.trim().toLowerCase()!==`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`)return g(`This operation did not return XLSX; use --csv.`);if(q.data instanceof Uint8Array)return C?p(`${ce} succeeded`,q.data,{...U,httpStatus:q.status}):ie(p(`${ce} succeeded`,q.data));if(e.responseFormat===`xlsx`)return g(`This operation did not return XLSX; use --csv.`);let le=!q.redirect&&q.rolloverJob?.running===!0&&K.followRollover,ue=le&&e.pendingResult!==void 0?void 0:Ve(ce,q,K.followRollover),de={...U,httpStatus:q.status},fe=f(q.data),pe=O===`text/plain`&&typeof q.data==`string`?q.data:{...de,...a.length>1&&o.data!==void 0?{contentType:o.data.contentType}:{},...q.redirect?{location:q.location}:{},summary:i.summary,...q.headers[`x-next-cursor`]?{nextCursor:q.headers[`x-next-cursor`]}:{},response:Kr(Gr(i,q.redirect?void 0:q.rolloverJob?.answeredPath),q.status,q.data,re().components.schemas)};if(ue!==void 0)return q.redirect||q.rolloverJob?.running===!0?ue:{...ue,data:pe};let me=sr(H,te,q,e=>p(He(ce,q),pe,{...de,format:q.redirect||q.rolloverJob||O!==`text/plain`?`json`:`text`,count:_(q.data,fe),page:fe,filters:D(i,B),...se(q.headers),...e}),e.responseFormat===`json`?ae:void 0);return(le?e.pendingResult?.(me,q):void 0)??me}function li(e){let t=e.host.trim();return/^https?:\/\//i.test(t)?t===e.host?e:{...e,host:t}:{...e,host:`${l(t)?`http`:`https`}://${t}`}}function ui(e,t,n){if(e!==`none`)return d(e);let r=d(`none`);return!r.ok||!r.data?r:me(t,n.searchParams,n.body)===`required`||r.data.env.userBearerToken?d(`bearer`):r}function di(e,t){let n=new URL(e,`https://placeholder.invalid`);for(let[e,r]of Object.entries(t??{}))if(r!==void 0){if(Array.isArray(r))for(let t of r)n.searchParams.append(e,String(t));else n.searchParams.set(e,String(r))}return`${n.pathname}${n.search}`}export{ri as a,Ie as c,ci as i,Ee as l,oi as n,hr as o,si as r,Qn as s,ni as t,xe 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=bn().Headers,t.exports.Response=xn().Response,t.exports.Request=Sn().Request,t.exports.FormData=rt().FormData;var{setGlobalOrigin:I,getGlobalOrigin:L}=Xe();t.exports.setGlobalOrigin=I,t.exports.getGlobalOrigin=L;var{CacheStorage:R}=Dn(),{kConstruct:ee}=Z();t.exports.caches=new R(ee);var{deleteCookie:z,getCookies:B,getSetCookies:te,setCookie:ne,parseCookie:V}=jn();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}=$e();t.exports.parseMIMEType=re,t.exports.serializeAMimeType=ie;var{CloseEvent:ae,ErrorEvent:H,MessageEvent:U}=Mn(),{WebSocket:W,ping:G}=Bn();t.exports.WebSocket=W,t.exports.CloseEvent=ae,t.exports.ErrorEvent=H,t.exports.MessageEvent=U,t.exports.ping=G,t.exports.WebSocketStream=Hn().WebSocketStream,t.exports.WebSocketError=Vn().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:K}=Gn();t.exports.EventSource=K;function q(){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=q}))(),qn=11e4,Jn=8,Yn=new Set([`ECONNRESET`,`ECONNREFUSED`,`ETIMEDOUT`,`EPIPE`,`UND_ERR_SOCKET`,`UND_ERR_CONNECT_TIMEOUT`,`UND_ERR_HEADERS_TIMEOUT`,`UND_ERR_BODY_TIMEOUT`]),Xn=new Map;function Zn(){let e=process.env.AVENTURE_API_SOCKET_PATH,t={headersTimeout:0,bodyTimeout:0},n=Xn.get(e??``)??new Kn.Dispatcher1Wrapper(e?new Kn.Agent({...t,connect:(t,n)=>(0,Kn.buildConnector)({socketPath:e,timeout:qn})({...t,protocol:`http:`},n)}):new Kn.EnvHttpProxyAgent({...t,proxyTunnel:!0}));return Xn.set(e??``,n),n}async function Qn(e,t,n){let r=Number(process.env.AVENTURE_API_REQUEST_TIMEOUT_MS),i=t.timeoutMs??(Number.isInteger(r)&&r>0?r:qn),a=Date.now()+i,o={...t,headers:{...t.headers,[b]:L()??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`},s=t.followRollover===!0,c=(t,r={waitMs:0,deadline:a})=>$n(e,t,n,i,r.deadline,r.waitMs),l=Date.now(),u=await c(o),d=Ne(u);if(!u.ok&&u.headers!==void 0&&d===void 0){let{idempotent:n,replayRateLimit:r}=t,i=ue(u.status,u.problem,n===!0,r),s=Date.now();i!==void 0&&s+i+(s-l)<a&&(ne({component:`aventure-api-client`,event:`request_retry`,fields:{...ar(o,e.host,o.headers[b]),retryKind:`http_refusal`,status:u.status,waitMs:Math.round(i)}}),u=await c({...o,idempotent:!1},{waitMs:i,deadline:a}))}let f=(!s||t.idempotent===!0)&&Ne(u)!==void 0;if(!s&&!f)return u;let p=!f&&!u.ok&&u.problem.code===`search_still_running`&&Date.now()<a?await c({...o,headers:{...o.headers,Prefer:ye(o.headers.Prefer,[`respond-async`])}}):u,m=!p.ok&&p.problem.code===`async_lookup_sign_in_required`?u:p;if(!m.ok&&!f)return m;let h={...o.headers,Accept:`application/json`};return Le(m,{origin:new URL(nr(e.host,`/`)).origin,deadline:a,signal:t.signal,rollsOver:s},(e,n)=>c({method:`GET`,path:e,headers:h,signal:t.signal},{waitMs:0,deadline:Date.now()+n}))}async function $n(e,t,r,i,a,o=0){let c=nr(e.host,t.path,t.searchParams),l=t.headers[b],u=ar(t,e.host,l),d={Accept:`application/json`,"User-Agent":n(),...t.headers,...S()},f=t.body instanceof FormData?t.body:JSON.stringify(t.body);f!==void 0&&t.contentType!==void 0&&(d[`Content-Type`]=t.contentType);let p=performance.now();B({component:`aventure-api-client`,event:`request`,fields:{...u,hasBody:t.body!==void 0}});let m=``,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 B({component:`aventure-api-client`,event:`request_failed`,message:V(e),fields:{...u,status:_?.status,timeoutMs:i,failureKind:r,durationMs:Math.round(performance.now()-p),...te(e)},error:e}),r},x=()=>(h=E(new URL(c).origin,j),m=t.unconfirmedWriteAdvice===void 0?``:`; ${t.unconfirmedWriteAdvice}`,h);try{o>0&&await ge(o,void 0,{signal:t.signal}),_=await tr(c,t,d,f,i,a,x),g=[502,503,504].includes(_.status)?`failure`:`success`,v=`body`;let e={status:_.status,headers:Object.fromEntries(_.headers)},n={...u,status:_.status},s=_.headers.get(`location`),l=ir.has(_.status)&&s!==null;l&&await _.body?.cancel().catch(()=>ne({component:`aventure-api-client`,event:`redirect_body_cleanup_failed`,message:`Redirect body cleanup failed after headers were received`,fields:n}));let h=l?``:await Oe(_,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: ${V(e)}`});v=`schema`;let b=l||h instanceof Uint8Array||h instanceof RangeError?h:or(h,_.headers.get(`content-type`),_.ok?r:void 0,n,m),S=b instanceof SyntaxError||b instanceof RangeError;S&&y(b);let C=Math.round(performance.now()-p);if(_.ok&&!S||l)return B({component:`aventure-api-client`,event:`response`,fields:{...n,durationMs:C}}),l?{ok:!0,redirect:!0,...e,location:s,data:void 0}:{ok:!0,...e,data:b};let w=S?b.message:b??h,T=le(K(_.status,w,d),_.headers);T.disposition===`TERMINAL`&&(g=`success`);let E=q(T,d),D=E.code===`search_still_running`&&(t.followRollover===!0||_.headers.has(`location`));return D&&(g=`success`),(D?B:ne)({component:`aventure-api-client`,event:D?`following_job`:`problem_response`,fields:{...u,durationMs:C,...ce(E,d)}}),{ok:!1,...e,problem:E}}catch(e){let t=y(e);if(e instanceof R)return{ok:!1,status:503,problem:K(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=V(e),r=te(e).causeChain,i=r===void 0?``:`: ${String(r)}`;throw Error(v===`body`?`Response body read from ${s()} failed: ${n}${m}`:`request to ${s()} failed: ${n}${i}${m}`,{cause:e})}finally{h?.finish(g)}}function er(e){for(let t=0;t<Jn&&e instanceof Error;t+=1){if(`code`in e&&typeof e.code==`string`)return Yn.has(e.code);if(e.name===`TimeoutError`||e.message===`socket hang up`)return!0;e=e.cause}return!1}async function tr(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=Zn(),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=AbortSignal.any([AbortSignal.timeout(Math.min(i,d)),...t.signal?[t.signal]:[]]),p;try{return u>1&&await ge(fe(),void 0,{signal:f}),f.throwIfAborted(),p=o(),await fetch(e,{method:t.method,headers:n,body:r??null,signal:f,dispatcher:c,redirect:`manual`})}catch(n){if(n instanceof R)throw n;let r=f.aborted?f.reason:n;if(u>=l||t.signal?.aborted===!0||Date.now()>=a||!er(r))throw r;p?.finish(`failure`),ne({component:`aventure-api-client`,event:`request_retry`,message:V(n),fields:{...ar(t,new URL(e).host,s),retryKind:`transport`,attempt:u,...te(n)},error:n})}}}function nr(e,t,n){let r=new URL(t,e.startsWith(`http`)?e:`https://${e}`);for(let[e,t]of Object.entries(n??{}))t!==void 0&&r.searchParams.set(e,String(t));return r.toString()}var rr=new Set([202,204,205]),ir=new Set([301,302,303,307,308]);function ar(e,t,n){let{method:r,path:i,operationId:a}=e;return{method:r,host:t,path:T(i),requestId:n,operationId:a}}function or(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(ne({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&&rr.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 sr(e,t,n,r,i){let a=r(cr(e,t,n,!1));return m(a,i)?a:r(cr(e,t,n,!0))}function cr(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:[`${e}${i.statusUrl}`]};let{data:a}=n,o=[`${e}${t}`],s=dr(a)?a.sourceDocumentId:void 0;return typeof s==`string`?{ids:[s],references:[...o,`${e}/v1/research/source-documents/${s}/body`]}:{ids:r?ur(a):[],references:o}}var lr=2;function ur(e,t=0){let n=t===0&&Array.isArray(e)?e:dr(e)&&Array.isArray(e.content)?e.content:void 0;return n===void 0?!dr(e)||t>=lr?[]:Object.values(e).flatMap(e=>ur(e,t+1)):n.flatMap(e=>{if(!dr(e))return[];let t=dr(e.entity)?e.entity:e.person,n=dr(t)&&dr(t.core)?t.core.id:void 0,r=dr(e.core)?e.core.id:e.id??n;return typeof r==`string`||typeof r==`number`?[String(r)]:[]})}var dr=e=>typeof e==`object`&&!!e&&!Array.isArray(e),fr=`actorType`,pr=`agentChassis`,mr=`agentModel`,hr=[fr,pr,mr],gr=`AVENTURE_AGENT_CHASSIS`,_r=`AVENTURE_AGENT_MODEL`,vr=[{chassis:`kimi-cli`,envNames:[`KIMI_MODEL`]},{chassis:`grok-build-cli`,envNames:[`GROK_HOME`,`GROK_MANAGED_BY_NPM`,`GROK_MANAGED_BY_INTERNAL`]},{chassis:`claude-code`,envNames:[`CLAUDECODE`,`CLAUDE_CODE`]},{chassis:`pi-cli`,envNames:[`PI_CODING_AGENT`]},{chassis:`codex-cli`,envNames:[`CODEX_MANAGED_BY_NPM`,`CODEX_SANDBOX`,`CODEX_THREAD_ID`,`CODEX_HOME`]},{chassis:`opencode`,envNames:[`OPENCODE_TERMINAL`]}],yr=[{chassis:`kimi-cli`,envNames:[`KIMI_MODEL`]},{chassis:`grok-build-cli`,envNames:[`GROK_MODEL`,`XAI_MODEL`]},{chassis:`pi-cli`,envNames:[`PI_MODEL`]}],br=[`OLLAMA_MODEL`,`OLLAMA_LAUNCH_MODEL`],xr=[`claude-code`,`claude-agent-sdk`],Sr=`codex-cli`,Cr=`opencode`;function wr(e){let t=Ir(e);return t.has(fr)||t.has(pr)&&t.has(mr)}function Tr({operation:e,searchParams:t,env:n=process.env,clientInfo:r}){if(!wr(e)){if(hr.some(e=>t?.[e]!==void 0)){let e={...t};for(let t of hr)delete e[t];return p(`Agent provenance not applicable`,e)}return p(`Agent provenance unchanged`,t)}let i=Br(t?.[fr]),a=i?.toLowerCase();if(i&&a!==`agent`&&a!==`employee`)return g(`${e.operationId} has unknown provenance actorType.`,[`Use actorType=agent or actorType=employee. actorType is optional only at the API boundary when a complete agent pair or employee JWT lets the resolver infer it before domain and write-lane enforcement.`]);let o=Br(t?.[pr]),s=Br(t?.[mr]),c=kr(n,r);if(a===`employee`)return o||s||c.status!==`missing`?g(`${e.operationId} has mixed employee and agent provenance.`,[`An agent runtime cannot claim employee attribution; use the runtime's agent provenance carrier.`]):p(`Employee provenance explicit`,{...t,actorType:`employee`});let l=zr(n,gr),u=zr(n,_r);if(o&&l&&o!==l)return g(Dr(e,`chassis`),[Or({param:pr,flag:`--agent-chassis`,envName:gr,envValue:l,explicitValue:o})]);if(s&&u&&s!==u)return g(Dr(e,`model`),[Or({param:mr,flag:`--agent-model`,envName:_r,envValue:u,explicitValue:s})]);if(o&&s){if(c.status===`partial`){let i=Mr(n,r);return o!==Fr(r?.name)&&o===Sr?g(`${e.operationId} rejected: ${Sr} binds its pair through its PreToolUse hook.`,[c.warning,`Run the CLI directly without --agent-chassis or --agent-model.`]):l===void 0&&u===void 0&&i.includes(o)?p(`Agent provenance explicit`,{...t,actorType:`agent`}):g(`${e.operationId} rejected: --agent-chassis ${o} is not this runtime.`,[c.warning,i.length===0?`Set ${gr} and ${_r} together.`:`This shell shows ${i.join(` and `)}. If that is you, pass --agent-chassis ${i.join(` or `)} --agent-model <your current model>; a different runtime launched from it sets ${gr} and ${_r} to its own pair.`])}let i=l===void 0&&o!==Sr&&Mr(n,r).includes(o);return c.status===`complete`&&!i&&(o!==c.pair.agentChassis||s!==c.pair.agentModel)?g(`${e.operationId} rejected: explicit agent provenance disagrees with the runtime environment.`,[`Detected ${c.pair.agentChassis}/${c.pair.agentModel} from runtime signals.`,`You passed --agent-chassis ${o} --agent-model ${s}.`,`Omit both flags, or set AVENTURE_AGENT_CHASSIS and AVENTURE_AGENT_MODEL after verifying the session.`]):p(`Agent provenance explicit`,{...t,actorType:`agent`})}return o||s?g(Er(e),[`Pass both agentChassis and agentModel, or omit both so the API can infer an employee actor from an authenticated user JWT session or this caller can auto-fill a verified local agent pair.`]):c.status===`missing`?a===`agent`?g(Er(e),[`actorType=agent requires agentChassis and agentModel before the API can build the enforced domain actor.`]):p(`Provenance left for API-boundary actor inference`,t):c.status===`partial`?g(Er(e),[c.warning,`Pass agentChassis and agentModel together, or neither.`]):p(`Agent provenance auto-filled`,{...t,actorType:`agent`,agentChassis:c.pair.agentChassis,agentModel:c.pair.agentModel})}function Er(e){return`${e.operationId} requires complete agent provenance.`}function Dr(e,t){return`${e.operationId} rejected: explicit agent ${t} disagrees with the runtime environment.`}function Or(e){return[`Your runtime environment declares ${e.envName}=${e.envValue}, but you passed ${e.flag} ${e.explicitValue} (query param ${e.param}).`,`The environment value comes from the container/runtime you are executing inside and is almost always correct.`,`If you (the LLM agent) believe the environment is wrong, investigate the container configuration first — do not override with a guess.`,`Otherwise, omit ${e.flag} entirely and the CLI will auto-fill from ${e.envName} (and ${_r} for the model). LLM agents hallucinate provenance frequently; stop providing false parameters.`].join(` `)}function kr(e,t){let n=zr(e,gr),r=zr(e,_r);if(n&&r)return{status:`complete`,pair:{agentChassis:n,agentModel:r}};if(n||r)return{status:`partial`,warning:`${gr} and ${_r} must be set together.`};let i=Mr(e,t),a=i.flatMap(t=>{let n=Nr(e,t);return n?[{agentChassis:t,agentModel:n}]:[]});if(a[0])return{status:`complete`,pair:a[0]};let o=i.filter(e=>e!==Cr),s=jr(i),c=s===Cr||o.some(e=>e===`codex-cli`||Pr(e))?void 0:Lr(e,...br);return s&&c?{status:`complete`,pair:{agentChassis:s,agentModel:c}}:i.length>0?{status:`partial`,warning:`${i.join(` and `)} ${i.length===1?`was`:`were`} detected, but no verified model source was present.`}:c?{status:`partial`,warning:`A model was detected, but no verified agent chassis source was present.`}:{status:`missing`,warning:`No verified local agent chassis/model pair was present.`}}function Ar(e=process.env,t){return zr(e,gr)??jr(Mr(e,t))}function jr(e){let t=e.filter(e=>e!==Cr);return t.length===1?t[0]:e.length===1?e[0]:void 0}function Mr(e,t){let n=Fr(t?.name);return n?[n]:vr.filter(t=>t.envNames.some(t=>Rr(e,t))).map(e=>e.chassis)}function Nr(e,t){let n=yr.find(e=>e.chassis===t);return n?Lr(e,...n.envNames):void 0}function Pr(e){return e!==void 0&&xr.some(t=>t===e)}function Fr(e){let t=e?.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim();if(t){if(t.includes(`claude`)&&t.includes(`sdk`))return`claude-agent-sdk`;if(t===`claude code`||t.includes(`claude code`))return`claude-code`;if(t===`codex`||t.includes(`codex`))return`codex-cli`;if(t===`kimi`||t.includes(`kimi`))return`kimi-cli`;if(t.includes(`hermes`))return`hermes-cli`;if(t.includes(`grok`))return`grok-build-cli`;if(t.includes(`mistral vibe`))return`mistral-vibe-cli`;if(t===`pi`||t===`pi cli`)return`pi-cli`}}var Ir=e=>new Set((e.parameters??[]).filter(e=>e.in===`query`).map(e=>e.name)),Lr=(e,...t)=>t.map(t=>zr(e,t)).find(e=>e!==void 0);function Rr(e,t){let n=zr(e,t)?.toLowerCase();return n!==void 0&&n!==`0`&&n!==`false`&&n!==`no`}function zr(e,t){return e[t]?.trim()||void 0}function Br(e){if(e===void 0)return;let t=typeof e==`object`?e[0]:e;return t===void 0?void 0:String(t).trim()||void 0}var Vr={AVENTURE_JOB_NAME:`X-Job-Name`,AVENTURE_TIER:`X-Tier`,AVENTURE_JOB_KEY:`X-Job-Key`},Hr=`X-Agent-Chassis`,Ur=/^[A-Za-z0-9._:-]{1,120}$/;function Wr(e){let t=[...Object.entries(Vr).map(([e,t])=>[t,process.env[e]?.trim()]),[Hr,Ar(process.env,e)]];return Object.fromEntries(t.flatMap(([e,t])=>t&&Ur.test(t)?[[e,t]]:[]))}function Gr(e,t){if(t===void 0)return e;let n=k(re().paths,`get`,t);if(n===null)throw Error(`No bundled operation serves the polled job route GET ${t}`);return n.operation}function Kr(e,t,n,r){let i=e.responses[String(t)]?.content;return n===void 0?n:qr(n,i?.[`application/json`]?.schema,r).value}function qr(e,t,n){let r=ti(t,n);if(r===void 0||typeof e!=`object`||!e)return{value:e,dropped:0};let i=[...r.oneOf??[],...r.anyOf??[]].filter(t=>Yr(ti(t,n),e));if(r.properties===void 0&&i.length>0)return i.map(t=>qr(e,t,n)).reduce((e,t)=>t.dropped<e.dropped?t:e);if(Array.isArray(e))return Jr(e,r,n);let a=Xr(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}:qr(t,r,n);return o+=i.dropped,[[e,i.value]]});return{value:Object.fromEntries(s),dropped:o}}function Jr(e,t,n){let r=t.items??(t.allOf??[]).find(e=>e.items!==void 0)?.items,i=e.map(e=>qr(e,r,n));return{value:i.map(e=>e.value),dropped:i.reduce((e,t)=>e+t.dropped,0)}}function Yr(e,t){return e===void 0?!1:Array.isArray(t)?e.items!==void 0||$r(e).includes(`array`):e.type===void 0&&e.properties===void 0||ei(e)||Qr(e).length>0}function Xr(e,t){let n=new Map,r;return Zr(e,t,n,new Set,e=>{r??=e})&&n.size>0?{properties:n,additionalProperties:r}:void 0}function Zr(e,t,n,r,i){let a=e.$ref;if(a!==void 0){if(r.has(a))return!0;r.add(a)}let o=ti(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=Qr(o);return o.properties===void 0&&s.length===0?o.type!==void 0&&!ei(o):s.every(e=>Zr(e,t,n,r,i))}function Qr(e){return[...e.allOf??[],...e.oneOf??[],...e.anyOf??[]]}function $r(e){return e.type===void 0?[]:[e.type].flat()}function ei(e){return e.properties!==void 0||$r(e).includes(`object`)}function ti(e,t){let n=C(e);return n===void 0?e:t[n]}var ni=class extends Error{problem;constructor(e){let{status:t,title:n,detail:r,code:i,retryAfterSeconds:a}=e;super(`OAuth bearer verification ${t===429?`was rate limited`:`is unavailable`}: ${t} ${n}${r?` — ${r}`:``}`+(typeof i==`string`?` [code: ${i}]`:``)+(typeof a==`number`?` [retry after ${a} seconds]`:``)),this.problem=e,this.name=`BearerVerificationUnavailableError`}};async function ri(e,t,n=[],r){let i=`authorizeOperations`,a=await Qn(li(c()),{method:`POST`,path:oi(i,{}),headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`},body:{operation:[...n]},operationId:i,idempotent:!0,replayRateLimit:!1,timeoutMs:r},Ee);if(a.ok&&a.redirect)throw new ni(K(a.status,`Unexpected authorization redirect`));if(!a.ok&&a.status!==401&&a.status!==403)throw new ni(a.problem);if(!a.ok)return a.status===403?`forbidden`:null;if(!e.includes(`.`))return a.data;try{let{typ:t}=H(e);if(t!==`at+jwt`&&t!==`application/at+jwt`)return a.data}catch{return a.data}let{aud:o}=U(e);if(o===void 0)return a.data;if(t===void 0)throw Error(`OAuth bearer verification is unavailable`);let s=Array.isArray(o)?o:[o];return s.length===1&&s[0]===t.href?a.data:null}var ii=`MCP transport credential is read-only; refused an authenticated upstream call.`,ai=11e4;function oi(e,t){let n=O(re().paths,e);if(!n)throw Error(`OpenAPI operationId not found: ${e}`);return z(n.template,y(n.operation,t,e),e)}function si(e){let t=e.pathParams??{};try{if(e.operationId!==void 0){let n=O(re().paths,e.operationId);if(n===null)return g(`OpenAPI operationId not found: ${e.operationId}`);let r=oi(e.operationId,t);return p(`Resolved ${e.operationId}`,{...n,path:r})}if(e.method===void 0||e.path===void 0)return g(`Pass operationId or method+path.`);let n=w(e.method),r=e.path;re().paths[r]?.[n]===void 0&&r.includes(`{`)&&(r=Object.entries(re().paths).find(([t,r])=>{let i=r[n];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 i=re().paths[r]?.[n],a=z(r,i===void 0?t:y(i,t,e.path),e.path),o=k(re().paths,n,a);return o===null?g(`OpenAPI operation not found for ${e.method} ${T(a)}`):(i===void 0&&y(o.operation,t,e.path),p(`Resolved ${o.operation.operationId}`,{...o,path:a}))}catch(e){return g(e instanceof Error?e.message:String(e))}}async function ci(e){let t=Number(process.env.AVENTURE_API_REQUEST_TIMEOUT_MS),n=Date.now()+(Number.isInteger(t)&&t>0?t:ai),r=k(re().paths,w(e.method),e.path);if(!r)return g(`OpenAPI operation not found for ${e.method} ${T(e.path)}`,[`Use a path in this package's OpenAPI contract; undocumented routes are not supported.`]);let i=r.operation,a=A(i.requestBody?.content),o=ee(a,e.contentType);if(!o.ok||o.data===null)return g(o.summary,o.warnings);let c=_e(i,e.headers);if(!c.ok||c.data===null)return g(c.summary,c.warnings);let l=e.requesterScope??`write`,m=e.auth===`auto`?(i.security?.length??0)>0?`bearer`:`none`:e.auth,y=x();if(l===`read`&&y===void 0&&(m===`write`||m===`bearer`))return g(ii,[`Resolved upstream auth=${m} for ${e.method} ${e.path}.`,`Pass auth='read' explicitly for POST read endpoints, or sign in with an account that permits the call.`]);let b=N(e.body);if(!b.ok)return g(b.summary,b.warnings);if(I(o.data,re().components.schemas)&&b.data!==void 0&&!Array.isArray(b.data))return g(`${i.operationId} requires a JSON array body.`);let S=i.operationId;if(e.responseFormat===`xlsx`&&!Y(i))return g(`This operation does not offer XLSX; use --csv.`);let C=e.responseFormat===`csv`||e.responseFormat===`xlsx`,E=!C&&e.responseBytes===!0&&P(i),O=E?`*/*`:X(e.responseFormat??`auto`,i),j=await v();if(j!==void 0)return oe(`Auth`,j);let L=e.preparedAuth===void 0?y===void 0?ui(m,i,{searchParams:e.searchParams,body:b.data}):d(`none`):p(`reused prepared auth`,e.preparedAuth);if(!L.ok||!L.data)return g(L.summary,L.warnings);let R=e.preparedAuth===void 0&&y!==void 0?{...L.data,credential:u.authToken,headers:{Authorization:`Bearer ${y}`}}:L.data;e.onAuthPrepared?.(R);let z=Tr({operation:i,searchParams:he(i,e.searchParams,b.data,R.headers.Authorization),clientInfo:e.clientInfo});if(!z.ok)return g(z.summary,z.warnings);let B=z.data??void 0,te=di(e.path,B),ne=Fe(i,e.method,te),V=li(L.data.env),H=li({...V,host:s()}).host,U={method:e.method,endpoint:te,operationId:S},W=await M(i,b.data,e.contentType,{deadline:n,signal:e.signal,defaultContentType:e.method===`PATCH`?`application/merge-patch+json`:e.method===`POST`||e.method===`PUT`?`application/json`:void 0});if(!W.ok||W.data===null)return g(W.summary,W.warnings,{httpStatus:W.httpStatus});if(e.signal?.aborted||Date.now()>=n)return g(`Request canceled or invocation deadline exceeded before upload.`);let G=F({method:e.method,path:r.template,operation:i,includeBinary:!0}),K={method:e.method,path:te,headers:{...be(i,c.data,ne),...R.headers,...Wr(e.clientInfo),Accept:O},body:W.data.body,contentType:W.data.contentType,operationId:S,readbackOperationId:i[`x-aventure-mutation-readback`]?.readOperationId,idempotent:e.method===`POST`&&G?.scope===`read`&&G.mutates!==!0&&i[`x-aventure-mutation-readback`]===void 0,followRollover:Ie(Object.keys(i.responses)),signal:AbortSignal.any([AbortSignal.timeout(Math.max(1,n-Date.now())),...e.signal?[e.signal]:[]])};e.onDispatch?.();let q=E?await Qn(V,{...K,responseBytes:!0}):C?await Qn(V,{...K,responseBytes:`negotiated`},h):await Qn(V,K,h),ce=S??e.method;if(!q.ok)return oe(`${ce} failed`,q.problem,[`endpoint=${te}`]);if(e.responseFormat===`xlsx`&&q.headers[`content-type`]?.split(`;`)[0]?.trim().toLowerCase()!==`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`)return g(`This operation did not return XLSX; use --csv.`);if(q.data instanceof Uint8Array)return C?p(`${ce} succeeded`,q.data,{...U,httpStatus:q.status}):ie(p(`${ce} succeeded`,q.data));if(e.responseFormat===`xlsx`)return g(`This operation did not return XLSX; use --csv.`);let le=!q.redirect&&q.rolloverJob?.running===!0&&K.followRollover,ue=le&&e.pendingResult!==void 0?void 0:Ve(ce,q,K.followRollover),de={...U,httpStatus:q.status},fe=f(q.data),pe=O===`text/plain`&&typeof q.data==`string`?q.data:{...de,...a.length>1&&o.data!==void 0?{contentType:o.data.contentType}:{},...q.redirect?{location:q.location}:{},summary:i.summary,...q.headers[`x-next-cursor`]?{nextCursor:q.headers[`x-next-cursor`]}:{},response:Kr(Gr(i,q.redirect?void 0:q.rolloverJob?.answeredPath),q.status,q.data,re().components.schemas)};if(ue!==void 0)return q.redirect||q.rolloverJob?.running===!0?ue:{...ue,data:pe};let me=sr(H,te,q,e=>p(He(ce,q),pe,{...de,format:q.redirect||q.rolloverJob||O!==`text/plain`?`json`:`text`,count:_(q.data,fe),page:fe,filters:D(i,B),...se(q.headers),...e}),e.responseFormat===`json`?ae:void 0);return(le?e.pendingResult?.(me,q):void 0)??me}function li(e){let t=e.host.trim();return/^https?:\/\//i.test(t)?t===e.host?e:{...e,host:t}:{...e,host:`${l(t)?`http`:`https`}://${t}`}}function ui(e,t,n){if(e!==`none`)return d(e);let r=d(`none`);return!r.ok||!r.data?r:me(t,n.searchParams,n.body)===`required`||r.data.env.userBearerToken?d(`bearer`):r}function di(e,t){let n=new URL(e,`https://placeholder.invalid`);for(let[e,r]of Object.entries(t??{}))if(r!==void 0){if(Array.isArray(r))for(let t of r)n.searchParams.append(e,String(t));else n.searchParams.set(e,String(r))}return`${n.pathname}${n.search}`}export{ri as a,Ie as c,ci as i,Ee as l,oi as n,hr as o,si as r,Qn as s,ni as t,xe as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{t as BearerVerificationUnavailableError,n as buildOpenApiPath,r as resolveOpenApiOperationSelector,i as runOpenApiCall,a as verifyUserBearerToken}from"./openapi-call-
|
|
1
|
+
export{t as BearerVerificationUnavailableError,n as buildOpenApiPath,r as resolveOpenApiOperationSelector,i as runOpenApiCall,a as verifyUserBearerToken}from"./openapi-call-DRowSHyQ.js";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{n as e}from"./commander-DEj7N1b9.js";import{a as t}from"./package-DEeHDoOT.js";import{c as n}from"./result-envelope-BMqcRDpc.js";import{t as r}from"./output-D8SD_tSW.js";import{a as i,t as a}from"./output-mode-DIt-t4Fu.js";import{a as o,c as s,i as c,l,o as u,r as d,s as f,t as p,u as m}from"./operations-catalog-
|
|
1
|
+
import{n as e}from"./commander-DEj7N1b9.js";import{a as t}from"./package-DEeHDoOT.js";import{c as n}from"./result-envelope-BMqcRDpc.js";import{t as r}from"./output-D8SD_tSW.js";import{a as i,t as a}from"./output-mode-DIt-t4Fu.js";import{a as o,c as s,i as c,l,o as u,r as d,s as f,t as p,u as m}from"./operations-catalog-D_8difUe.js";var h=`Match only the first canonical or CLI-alias command segment`,g=[`text`,`lines`,`compact`,`json`,`ndjson`],_=`20`;function v(e,n,r=t().bin[0]){let a=y((e.commands.find(e=>e.name()===`help`)??e.command(`help`)).command(`catalog`).summary(`Search or list generated command metadata offline`).description([`Search or list generated ${r} command metadata without calling the API.`,`A query ranks the closest ${_} operations; no query lists every operation.`,`Run \`${r} help <command>\` for one operation's full documentation.`,`Use --format lines for rg/grep/ag/ack, ndjson|json for ast-grep/sg/parsers,`,"and compact for one `cli · summary · requiredFlags` row per operation."].join(`
|
|
2
2
|
`)).argument(`[query...]`,`Words to rank operations by; omit to list every operation`));a.addHelpText(`after`,()=>b(r)),a.action(function(e){let t=this.optsWithGlobals(),a=c(t,e),o=(a.q?.trim()??``)!==``;u(o&&t.limit===void 0?{...a,limit:_}:a,n,i(t,`text`),r)})}function y(t){return t.option(`--root <root>`,h).addOption(new e(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new e(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new e(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new e(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new e(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`).addOption(new e(`--format <format>`,`Text/file render format`).choices(g)).option(`--output <path>`,`Write rendered output to a file`),a(t),t}function b(e){return[``,`Shipped with this install, greppable without running this CLI:`,` ${p(e)} (operations callable without an admin grant)`,` ${d(e)} (every operation's CLI, API, and MCP forms as JSON)`,``].join(`
|
|
3
3
|
`)}function x(e,n,r=t().bin[0]){let i=e.command(`command-catalog`,{hidden:!0}).summary(`Deprecated: run \`${r} help catalog\``).description(`Deprecated: run \`${r} help catalog\` to search or list operations, and \`${r} help <command>\` for one operation.`);C(i,n,r),w(i,n,r),T(i,n,r),E(i,r)}function S(e,t,n){return e.hook(`preAction`,()=>{process.stderr.write(`warning: Deprecated: \`${t} command-catalog ${e.name()}\` is replaced by \`${t} ${n}\`.\n`)})}function C(e,t,n){let r=y(e.command(`search`).summary("Deprecated: run `help catalog <query...>`").argument(`[query...]`,`Search query; same as --q.`).option(`--q <query>`,`Search generated command metadata`));S(r,n,`help catalog <query...>`),r.action(function(e){let r=this.optsWithGlobals(),a=c(r,e),o=(a.q?.trim()??``)===``?t.filter(({deprecated:e})=>e!==!0):t;u({...a,limit:r.limit??_},o,i(r,`text`),n)})}function w(t,n,r){let o=t.command(`show`).summary("Deprecated: run `help <command>`").option(`--command <command>`,`CLI command path, with or without ${r} prefix`).option(`--operation-id <operationId>`,`Generated OpenAPI operationId`).addOption(new e(`--format <format>`,`Text/file render format`).choices([`usage`,`lines`,`compact`,`json`,`ndjson`]).default(`usage`)).option(`--output <path>`,`Write rendered output to a file`);a(S(o,r,`help <command>`)),o.action(function(){let e=this.optsWithGlobals();f(e,n,i(e,`text`),r)})}function T(e,t,n){let r=y(e.command(`dump`).summary("Deprecated: run `help catalog`"));S(r,n,`help catalog`),r.action(function(){let e=this.optsWithGlobals();u(e,t,i(e,`text`),n)})}function E(e,t){let c=e.command(`unified`).summary(`Deprecated: read the shipped unified-operations.json`).option(`--output <path>`,`Write unified operations JSON to a file`);a(S(c,t,`help catalog --help`)),c.action(async function(){let e=this.optsWithGlobals(),t=i(e,`text`),{MCP_GENERATION_CONTRACT:a}=await import(`./mcp-generation-contract-C3gxk0Nn.js`);if(t===`text`&&e.output===void 0&&(e.text===!0||e.allFields===!0)){r({mode:t},n(`Unified operations JSON`,`Use --output <path> to write the unified operations JSON.`,{counts:{totalOperations:a.length}}));return}let c=s(a);if(e.output!==void 0){let i=m(e.output,c);r({mode:t},n(`Unified operations JSON written`,{outputPath:i.target,byteLength:i.byteLength,schemaVersion:c.schemaVersion},{counts:{totalOperations:i.totalOperations}}))}else t===`text`?o(`Unified operations JSON`,l(c)):r({mode:t},n(`Unified operations JSON`,c,{counts:{totalOperations:c.totalOperations}}))})}export{v as registerHelpCatalogCommand,x as registerRetiredCommandCatalog};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{s as writeShowResult}from"./operations-catalog-D_8difUe.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e}from"./package-DEeHDoOT.js";import{c as t,r as n}from"./result-envelope-BMqcRDpc.js";import{s as r}from"./tool-policy-DG8pafmI.js";import{i}from"./output-spill-DysSe1O-.js";import"./startup-auth-
|
|
1
|
+
import{a as e}from"./package-DEeHDoOT.js";import{c as t,r as n}from"./result-envelope-BMqcRDpc.js";import{s as r}from"./tool-policy-DG8pafmI.js";import{i}from"./output-spill-DysSe1O-.js";import"./startup-auth-BuGIFRmd.js";import{i as a,r as o}from"./operations-metadata-CzOMH0PS.js";import{t as s}from"./output-D8SD_tSW.js";import{fileURLToPath as c}from"node:url";import{dirname as l,resolve as u}from"node:path";import{existsSync as d,mkdirSync as f,writeFileSync as p}from"node:fs";var m=`unified-operations.json`;function h(e,t=new Date){let n=v(e);return{schemaVersion:1,generatedFrom:`MCP_GENERATION_CONTRACT`,generatedAt:t.toISOString(),totalOperations:n.length,note:`1:1 projection of MCP_GENERATION_CONTRACT written by the CLI build ([MCP1b.1-EXC1]).`,operations:n}}function g(e){return`${JSON.stringify(e,null,2)}\n`}function _(e,t){let n=u(e),r=g(t);return f(l(n),{recursive:!0}),p(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function v(e){return e.map(e=>({operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,cliCommand:e.projection.cliPath.join(` `),cliPath:e.projection.cliPath,mcpTool:r(e),bodySchemaName:e.requestBody?.[0]?.schemaName??null,bodySchemaImport:e.requestBody?.[0]?.schemaImport??null,auth:e.projection.auth,scope:e.projection.scope,destructive:e.projection.destructive})).toSorted((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)||e.operationId.localeCompare(t.operationId))}var y=`command-catalog.compact.txt`,b=`dist/aventure-cli`,x=` · `,S=`-`;function C(t=e().bin[0]){return T(y,t)}function w(t=e().bin[0]){return T(m,t)}function T(e,t){return u(E(l(c(import.meta.url)),t),b,e)}function E(e,t){let n=e;for(;;){if(d(u(n,`package.json`)))return n;let r=l(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function D(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function O(t,n,r,i=e().bin[0]){let a=o(t,n,i);!a.ok||a.data===null?s({mode:r},a):A({opts:t,mode:r,data:a.data,defaultFormat:`lines`,rendered:N(a.data,M(t.format,`lines`)),summary:`Generated operation matches`})}function k(t,n,r,i=e().bin[0]){let o=a(t,n,i);!o.ok||o.data===null?s({mode:r},o):A({opts:t,mode:r,data:o.data,defaultFormat:`usage`,rendered:P(o.data,M(t.format,`usage`)),summary:`Generated operation detail`})}function A(e){let r=e.mode,i=M(e.opts.format,e.defaultFormat),a=e.opts.text===!0||e.opts.allFields===!0;if(e.opts.output===void 0&&a&&(i===`json`||i===`ndjson`)){s({mode:r},n(`--text or --all-fields cannot be combined with --format json or ndjson`,[`Omit the text flag for machine output, or use --format lines, compact, or text.`]));return}let o=e.opts.output===void 0&&r===`text`&&`count`in e.data&&e.data.count.matched===0&&(a||e.opts.format===void 0||i===`text`)?`No generated operations matched.`:e.rendered,c=o.endsWith(`
|
|
2
2
|
`)?o:`${o}\n`;e.opts.output===void 0?r===`text`?j(e.summary,c):s({mode:r},t(e.summary,e.data,{counts:B(e.data)})):(p(e.opts.output,c),s({mode:r},t(e.summary,{outputPath:e.opts.output,byteLength:Buffer.byteLength(c,`utf8`),format:i},{counts:B(e.data)})))}function j(e,n){let r=i(t(e,n));!r.ok||r.data===null?s({mode:`text`},r):process.stdout.write(r.data.endsWith(`
|
|
3
3
|
`)?r.data:`${r.data}\n`)}function M(e,t){return e??t}function N(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?e.operation.map(e=>JSON.stringify(e)).join(`
|
|
4
4
|
`):t===`text`?L(e.operation):t===`compact`?e.operation.map(F).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{u as e}from"./tool-policy-DG8pafmI.js";import{c as t,s as n}from"./startup-auth-
|
|
1
|
+
import{u as e}from"./tool-policy-DG8pafmI.js";import{c as t,s as n}from"./startup-auth-BuGIFRmd.js";import{t as r}from"./openapi-commands-B2dIDk9o.js";import{_ as i,g as a}from"./help-catalog-PSifyPm6.js";import{r as o}from"./operations-metadata-CzOMH0PS.js";import{n as s}from"./operations-catalog-D_8difUe.js";import{a as c,t as l}from"./payload-operand-guard-Cne4mq9F.js";function u(e,t){return e.message.match(RegExp(`${t} '([^']+)'`,`iu`))?.[1]?.split(/\s+/u)[0]}function d(e){return e.flags.split(` `)[0]??e.flags}function f(e,t){let n=u(t,`required option`),r=e.options.findIndex(e=>d(e)===n);if(r<0)return;let i=new Set((M(c(e))?.parameters??[]).flatMap(e=>e.location===`path`?[e.optionKey]:[])),a=e.options.slice(r+1).find(t=>{let n=e.getOptionValue(t.attributeName());return i.has(t.attributeName())&&typeof n==`string`&&n!==``});if(a!==void 0)return`hint: ${n} is still required for this nested command; supplied child selector ${d(a)} does not replace the parent selector.`}var p=[[`--search`,`--query`,`--q`,`--term`,`--keyword`],[`--size`,`--limit`,`--page-size`,`--per-page`],[`--transaction-id`,`--fundraise-round-id`]];function m(e){let t=new Set(e.options.map(d)),n=process.argv.indexOf(`--`),r=new Set(n<0?process.argv:process.argv.slice(0,n));return e.args.filter(e=>r.has(e)&&/^--[^-=]/u.test(e)).map(e=>e.split(`=`)[0]??e).filter(e=>!t.has(e))}function h(e){let t=M(c(e))?.parameters??[],n=m(e).flatMap(n=>{let r=p.find(e=>e.includes(n))?.find(t=>e.options.some(e=>d(e)===t))??t.filter(({name:e})=>`--${e.replace(/[A-Z]/gu,`-$&`).toLowerCase()}`===n).map(e=>e.flag.split(` `)[0])[0];return r===void 0?[]:[`use ${r}, not ${n}`]});return n.length===0?void 0:`hint: ${n.join(`; `)}`}function g(e){return e.commands.length===0?[e]:e.commands.flatMap(g)}function _(e){return e.parent===null?e:_(e.parent)}function v(e,t){let n=t=>{let n=c(t).slice(c(e).length);return n.length*2+ +![`get`,`list`].includes(n.at(-1)??``)};return t.toSorted((e,t)=>n(e)-n(t))[0]}function y(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function b(e,t){let n=[...e.options,...e.createHelp().visibleOptions(e)];for(let t=e.parent;t!==null;t=t.parent)n.push(...t.options);let r=t,i;for(let e=0;e<t.length;e++){let a=t[e];if(a===void 0||a===`--`)break;if(!a.startsWith(`-`)||a===`-`||i?.variadic&&Number.isFinite(Number(a)))continue;let o=a.indexOf(`=`),s=o<0?a:a.slice(0,o);if(i=n.find(e=>e.short===s||e.long===s),i===void 0||o>=0&&!i.required&&!i.optional){r=[`--help`];break}o<0&&(i.required||i.optional&&!t[e+1]?.startsWith(`-`))&&e++}return[_(e).name(),...c(e),...r].map(y).join(` `)}function x(e,t){let n=u(t,`unknown option`);if(n===void 0||e.commands.length===0)return;let r=v(e,g(e).filter(e=>e.options.some(e=>d(e)===n)));return r===void 0?void 0:`hint: run: ${b(r,process.argv.slice(2+c(e).length))}`}function S(e){return e!==void 0&&Object.hasOwn(t,e)}function C(e,t){return t.reduce((e,t)=>e?.commands.find(e=>e.name()===t),e)}function w(e,t){let n=c(e),r=[...n.slice(1),t];if(!S(n.at(0))||!S(r.at(0)))return;let i=C(_(e),r);if(i===void 0)return;let a=i;for(let e of process.argv.slice(2+n.length+1)){if(e.startsWith(`-`))break;let t=a.commands.find(t=>t.name()===e);if(t===void 0)break;r.push(e),a=t}return r}function T(e,t){let[n]=c(e);if(n===void 0||!S(n))return;let r=[n,t];return C(_(e),r)?.commands.length===0?r:void 0}function E(e){let[t,...n]=e.args;if(t===void 0)return[];let r=g(_(e)).map(c),i=n.findIndex((e,t)=>{let i=[...n.slice(0,t),e];return!r.some(e=>e.some((t,n)=>t===i[0]&&i.every((t,r)=>e[n+r]===t)))});return[t,...i<0?n:n.slice(0,i)]}function D(e,t,i=[]){let a=c(e),o=n(r).map(e=>e.cliPath).filter(e=>e[0]!==a[0]&&e.length>=t.length&&t.every((n,r)=>e[e.length-t.length+r]===n)),s=o.find(e=>e.length===t.length&&e.every((e,n)=>e===t[n]))??(o.length===1?o[0]:void 0);if(s===void 0)return;let l=C(_(e),s);return l===void 0?void 0:`hint: run: ${b(l,i)}`}function O(e,t,n){if(!A(t))return;let r=C(_(e),t);if(r===void 0)return;let i=e.args.slice(n.length),a=i.findIndex(e=>e.startsWith(`-`));return`hint: Did you mean: ${b(r,a<0?[]:i.slice(a))}`}function k(e){let t=c(e);if(t.at(1)!==void 0&&S(t.at(0)))return`hint: inspect generated command group: ${[_(e).name(),...t,`--help`].map(y).join(` `)}`}function A(t,n){let r=M(t)?.intent;return r!==void 0&&(n===void 0||e(r)===n)}var j=new Map(r.toReversed().map(e=>[e.cliPath.join(` `),e])),M=e=>j.get(e.join(` `));function N(e){let t=c(e).join(` `),i=n(r),o=i.find(e=>e.cliPath.join(` `)===t);return o===void 0?[]:a(o.operationId,i,_(e).name()).map(e=>`hint: ${e}`)}function P(e){let t=c(e);if(S(t.at(0))&&A(t))return`hint: inspect generated command: ${[_(e).name(),...t,`--help`].map(y).join(` `)}`}function F(t){let n=new Set,i=[];for(let a of r){let r=C(t,a.cliPath);if(r===void 0)continue;let o=r.options.map(d);if(e(a.intent))i.push(o);else for(let e of o)n.add(e)}let[a=[],...o]=i;return new Set(a.filter(e=>!n.has(e)&&o.every(t=>t.includes(e))))}function I(e,t){let n=c(e);if(A(n,!1)&&F(_(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function L(e,t,i=!0){let a=_(e),l=a.commands.find(e=>e.name()===`help`),u=l?.commands.find(e=>e.name()===`catalog`);if(l===void 0||u===void 0)return;let f=[a.name(),l.name(),u.name(),t],p=c(e).at(0),m=u.options.find(e=>d(e)===`--root`),h=i&&m!==void 0&&S(p)?p:void 0;m!==void 0&&h!==void 0&&f.push(d(m),h);let g=n(r),v=o({q:t,root:h,limit:`3`},g,a.name()),b=v.ok&&v.data!==null?s(v.data,`compact`):``;return[`hint: search generated commands: ${f.map(y).join(` `)}`,...b===``?[]:[`hint: closest commands (command · summary · required flags):`],...b.split(`
|
|
2
2
|
`).filter(Boolean).map(e=>` ${e}`)].join(`
|
|
3
3
|
`)}function R(e,t=``){if(e.commands.length>0&&!A(c(e)))return;let a=e.options.flatMap(e=>e.hidden?[]:[d(e)]),o=n(r),s=i(t,o,c(e),_(e).name());return`${s===void 0?``:`hint: an id you already hold is read with: ${s}\n`}hint: ${c(e).join(` `)} accepts: ${a.join(` `)}`}function z(e,t){let n=u(t,`unknown command`);if(n===void 0||t.message.includes(`
|
|
4
4
|
(Did you mean `))return;let r=E(e),i=process.argv.slice(2+c(e).length);if(r.length>0&&r.every((e,t)=>i[t]===e)){let t=D(e,r);if(t!==void 0)return t}let a=c(e),o=[...a.slice(0,-1),`${a.at(-1)}-${n}`,...r.slice(1)],s=(A(o)?o:void 0)??w(e,n)??T(e,n);if(s!==void 0)return O(e,s,r)??L(e,s.join(` `),!1);let l=r.join(` `)||n,d=k(e)??L(e,l),f=[...a,...r.slice(1)];return[d,r.length===a.length+a.length&&a.at(-1)===a.at(0)?O(e,f,r)?.replace(/^hint: Did you mean: /u,` `).concat(` · `):f.slice(1,-1).length>0?O(e,f,r):void 0].filter(e=>e!==void 0).join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,o as t,t as n}from"./commander-DEj7N1b9.js";import{c as r,f as i,t as a}from"./env-DGAe95Xm.js";import{c as o,r as s}from"./result-envelope-BMqcRDpc.js";import{y as c}from"./tool-policy-DG8pafmI.js";import{n as l}from"./cli-help-policy-DCn_wXe1.js";function u(e,t){return e.parameters.filter(e=>e.required&&t[e.optionKey]===void 0).map(e=>e.flag)}function d(e,t){return(e.requestBody?.length??0)>1&&typeof t.contentType==`string`?t.contentType:void 0}var f=e=>typeof e==`string`&&e.trim()===``;function p(e,t){let n=new Set([...t.parameters,...(t.requestBody??[]).flatMap(({parameter:e})=>e)].filter(e=>e.required).map(e=>e.optionKey));for(let t of e.options){let r=t.attributeName(),i=e.getOptionValue(r);if(!(Array.isArray(i)?i.some(f):f(i)))continue;let a=Array.isArray(i)?i.filter(e=>!f(e)):[];a.length>0?e.setOptionValue(r,a):(n.has(r)&&e.error(`error: option '${t.flags}' requires a value`),e.setOptionValue(r,void 0))}}function m(e){return e.split(` `)[0]??e}function h(e){if(e.requestBody===void 0||e.requestBody.length===0){let[t,n]=e.parameters.filter(e=>e.required);return n===void 0&&t?.schemaType===`string`?t:void 0}if(e.requestBody.length!==1||e.parameters.some(e=>e.required))return;let t=e.requestBody[0]?.parameter??[],n=t.filter(e=>e.required);if(n.length===1&&n[0]?.schemaType===`string`)return n[0];if(n.length!==0||e.intent!==`search`)return;let r=t.filter(e=>{let t=e.name.split(`.`).at(-1);return e.schemaType===`string`&&(t===`query`||t===`search`)});return r.length===1?r[0]:void 0}function g(e,t,n){let r=t.join(` `).trim();return r.length===0?o(`No positional text`,n):n[e.optionKey]===void 0?o(`Positional text parsed`,{...n,[e.optionKey]:r}):s(`Unexpected argument "${r}": ${m(e.flag)} already sets this value, and this command has no subcommand by that name. Drop "${r}".`)}var _={addresses:{summary:`List Address Links`,section:`administration`},"addresses links":{summary:`Returns every entity and person linked to this physical address, past and present, with each link's id, the linked record's id, and its role when one is recorded`},auth:{summary:`Sign-in, session, API key, and CLI authorization endpoints`,section:`account`},"auth api-key":{summary:`Get Current API Key`},"auth me":{summary:`Current User Permissions`},"auth me permissions":{summary:`Returns the current caller's resolved roles and permissions`},billing:{summary:`Plans, prices, subscription, usage, and upgrades`,section:`account`},"billing additional-usage":{summary:`Update Additional Usage Settings`},"billing ai-credits":{summary:`Read the Current AI Credit Allowance`},"billing checkout-sessions":{summary:`Create or Reuse a Checkout Session`},"billing credit-purchases":{summary:`Read a Prepaid Credit Purchase Confirmation`},"billing plan-change-previews":{summary:`Preview a Subscription Plan Change`},"billing plan-changes":{summary:`Change the Subscription Plan`},"billing plans":{summary:`List Subscription Tiers and Plans`},"billing portal-sessions":{summary:`Create a Hosted Billing Portal Session`},"billing subscription":{summary:`Read the Current Billing Subscription`},"billing subscription next-charge":{summary:`Preview the Next Subscription Charge`},"billing subscription payment-profile":{summary:`Read Your Card on File and Introductory Offer`},content:{summary:`Publications about one company or person, and platform-wide publication search`,section:`researchData`},"content facets":{summary:`Count One Owner's Publications`},directory:{summary:`Views of the public directories: publish, list, and read shared views by slug, and export a view's rows as JSON, CSV, or XLSX`,section:`researchData`},"directory exports":{summary:`Export Directory Records`},"directory shared":{summary:`List Shared Directory Views`},"directory shared slug":{summary:`Read a Shared Directory View by Slug`},enrichments:{summary:`Enrich Companies, People, or a News Article's Mentions`,section:`researchData`},entities:{summary:`Companies and funds: people, funding, and news`,section:`researchData`},"entities acquisitions":{summary:`Acquisitions a company made or was part of`},"entities addresses":{summary:`A company's recorded office and headquarters addresses`},"entities analysis-replay":{summary:`Get an Example Published Analysis Section`},"entities blog-posts":{summary:`External blog and article links for entities and people`},"entities brand":{summary:`Get a Company's Names, Logos, Links, and Tags`},"entities classifications":{summary:`Classification tags on a company, and suggested tags`},"entities classifications catalog":{summary:`Get the Company Classification Taxonomy`},"entities classifications suggestions":{summary:`Suggest Classifications for a Company`},"entities classifications tags":{summary:`List Classification Tags`},"entities contact-details":{summary:`List a Company's Contact Details`},"entities employee-counts":{summary:`List a Company's Headcount Over Time`},"entities enrichments":{summary:`Enrich One Company, Product, or Service`},"entities filters":{summary:`Filter options for company listings: available values, refinement, and option search`},"entities fundraise-investor-joins":{summary:`List the Investors in a Funding Round`},"entities fundraise-rounds":{summary:`List a Company's Funding Rounds`},"entities investments":{summary:`List the Investments a Company Made`},"entities investor-activity":{summary:`Get Investor Portfolio Counts, Sectors and Recipients`},"entities investors":{summary:`List a Company's Investors`},"entities investors people":{summary:`List Person Investors`},"entities logo":{summary:`Get a Company Logo`},"entities lookup-exact":{summary:`Read Full Entity Detail by aVenture Profile URL, Slug, Website, or Domain`},"entities people":{summary:`People linked to companies, and the role each one holds`},"entities relationships":{summary:`Relationships between companies, investors, and other organizations`},"entities relationships types":{summary:`List Entity Relationship Types`},"entities repositories":{summary:`List a Company's GitHub Repositories`},"entities research":{summary:`Get the Research Gathered About a Company`},"entities research-details":{summary:`List Research Details`},"entities research-details types":{summary:`List the Accepted Research Detail Types`},"entities research-snippets":{summary:`List Research Snippets`},"entities research-snippets types":{summary:`List the Accepted Research Snippet Types`},"entities search":{summary:`Search Companies, Products, and Services`},"entities search jobs":{summary:`Get an Async Semantic Entity Search`},"entities sec":{summary:`Get SEC EDGAR Facts for an SEC Registrant`},"entities similar":{summary:`Similar companies, as full records or short summaries, by id`},"entities similar summary":{summary:`Get Similar Company Summaries by ID`},"entities slug":{summary:`Get a Company's Slug`},"entities texts":{summary:`Descriptions and other written text for companies and people`},"entities texts types":{summary:`List the Accepted Company Text Types`},"entities trending-news":{summary:`List Trending News About a Company`},"entities types":{summary:`List the Accepted typeRecord Values`},"entities unique-ids":{summary:`External identifiers and the records they name`},"entities urls":{summary:`Websites, social profiles, and other URLs for companies and people`},"entities valuations":{summary:`List a Company's Valuation Over Time`},help:{summary:`Answer a Natural-Language Platform Help Question`,section:`cli`},lookup:{summary:`Identify a Company, Product, Service, or Person by Name, URL, or ID`,section:`researchData`},"lookup jobs":{summary:`Get a Lookup Job's State and the Records Its Article Names`},metrics:{summary:`Get Platform Totals for Companies, Funding, and People`,section:`cli`,listed:!1},news:{summary:`News linked to the companies and people in it`,section:`researchData`},"news feedback":{summary:`Submit News Feedback`},"news related-entities":{summary:`List the Entities a News Article Is About`},"news subscriptions":{summary:`List Entity News Subscriptions`},"news subscriptions test-events":{summary:`Send a Test News Event`},"news thumbnail":{summary:`Get News Thumbnail`},people:{summary:`Founders and investors, and what they back`,section:`researchData`},"people addresses":{summary:`A person's recorded addresses`},"people blog-posts":{summary:`External blog and article links for entities and people`},"people contact-details":{summary:`List a Person's Contact Details`},"people enrichments":{summary:`Enrich One Person`},"people entities":{summary:`People linked to companies, and the role each one holds`},"people filters":{summary:`Filter options for people listings and option search`},"people graph":{summary:`Get Person Graph`},"people investments":{summary:`List a Person's Investments`},"people investor-activity":{summary:`Get Person Investor Activity`},"people lookup-exact":{summary:`Read One Person's Full Detail by aVenture Profile URL, Slug, or URL`},"people photo":{summary:`Get Person Photo`},"people repositories":{summary:`List a Person's GitHub Repositories`},"people similar":{summary:`List People Similar to One Person`},"people unique-ids":{summary:`External identifiers and the records they name`},"people urls":{summary:`Websites, social profiles, and other URLs for companies and people`},research:{summary:`Research requests you file for a company, Product, Service, or person, and their progress`,section:`researchData`},"research runs":{summary:`List Your Research Runs`},"research runs draft":{summary:`Get a Research Run Draft`},"research runs draft sections":{summary:`Edit a Research Draft Section`},"research runs draft sources":{summary:`Get a Research Draft's Sources`},"research runs events":{summary:`Read a Research Run's Events`},"research runs presets":{summary:`List Research Presets`},"research runs turns":{summary:`Continue a Research Session`},search:{summary:`Search Companies, People, and News Together`,section:`researchData`},"search link":{summary:`Search From a Page URL`},"search link jobs":{summary:`Get a Link Search Job`},"search natural":{summary:`Find companies and people in natural language`},"search shared":{summary:`Search companies, people, and news, or by URL`},"search shared slug":{summary:`Read a Shared Search by Slug`},"unique-ids":{summary:`External identifiers and the records they name`,section:`researchData`},"unique-ids types":{summary:`List the Accepted Unique Identifier Types`},"url-types":{summary:`List URL Types`,section:`researchData`},web:{summary:`Search companies, people, and news, or by URL`,section:`researchData`},"web searches":{summary:`Get an Async Web Search Job`},"web searches jobs":{summary:"Reads the web-search job a `Prefer: respond-async` search accepted"}};function v(e){return x(e,y())}function y(){return!!i().userBearerToken?.trim()}function b(e){return y()||!l(e,_)}function x(e,t){return t?e:e.filter(e=>!l(e.cliPath[0],_)||e.visibility!==`private`).map(S)}function S(e){let t=e.parameters.filter(C),n=e.requestBody?.map(e=>{let t=e.parameter.filter(C);return t.length===e.parameter.length?e:{...e,parameter:t}}),r=n?.every((t,n)=>t===e.requestBody?.[n]);return t.length===e.parameters.length&&r!==!1?e:{...e,parameters:t,requestBody:n}}var C=e=>e.visibility!==`private`;async function w(e){if(e===`none`||process.env[a.authToken]?.trim())return;let{materializeCliOAuthBearerCredential:t,materializeSavedCliOAuthBearerCredential:n}=await import(`./oauth-bearer-credential-DvY2H2LR.js`),{materializeCliApiKeyBearerCredential:r}=await import(`./api-key-bearer-credential-BB4N6Moa.js`);await(e===`stored`?n():t()),await r()}function T(t){let r=t.findIndex(e=>e===`--version`||e===`-V`);if(r===-1)return!1;let i=new n().passThroughOptions().addOption(new e(`--environment <environment>`)).addOption(new e(`-h, --help`)).addOption(new e(`-V, --version`));return i.parseOptions(t.slice(0,r+1)),i.opts().version===!0}function E(t,i){let a=t.indexOf(`--`),o=t.slice(0,a===-1?t.length:a),s=new n().exitOverride().configureOutput({writeErr:()=>void 0}).addOption(new e(`--environment <environment>`)).parseOptions([...o]).operands,c=i.filter(e=>O(s,e.cliPath)).toSorted((e,t)=>t.cliPath.length-e.cliPath.length)[0],l=c!==void 0&&[...c.parameters,...c.requestBody?.flatMap(({parameter:e})=>e)??[]].some(e=>e.optionKey===`environment`),u=new n().exitOverride().configureOutput({writeErr:()=>void 0}).passThroughOptions(l).addOption(new e(`--environment <environment>`).choices([...r()])),{operands:d,unknown:f}=u.parseOptions([...o]);return{environment:u.opts().environment,commandArgv:[...d,...f,...a===-1?[]:t.slice(a)],positionalOptions:l}}function D(r,i){let a=r.indexOf(`--`),o=r.slice(0,a===-1?r.length:a);if(T(r))return`none`;let s=E(r,i),u=new n().exitOverride().configureOutput({writeErr:()=>void 0}).addOption(new e(`--content-type <media-type>`)),f=u.parseOptions([...s.commandArgv]).operands;s.environment!==void 0&&(process.env.API_ENV=s.environment);let p=i.find(e=>O(f,e.cliPath)),m=p===void 0?void 0:d(p,u.opts());if(p!==void 0&&m!==void 0){let e=c(p.requestBody??[],m);if(!e.ok)throw new t(e.summary)}let h=f.at(0);return h===void 0?`stored`:h===`update`||h===`auth`&&p===void 0?`none`:o.some(e=>e===`--help`||e===`-h`)?(p??(h===`help`?i.find(e=>O(f.slice(1),e.cliPath)):void 0))!==void 0||l(h,_)?`stored`:`none`:l(h,_)?`required`:h===`help`&&f[1]===`catalog`?`optional`:h===`help`?p===void 0?`stored`:`required`:h===`agents`&&f[1]===`setup`?`required`:[`command-catalog`,`completion`].includes(h)?`optional`:h===`batch`?`required`:p===void 0?`optional`:`required`}function O(e,t){return t.every((t,n)=>e[n]===t)}export{T as a,_ as c,u as d,p as f,E as i,d as l,g as m,D as n,x as o,h as p,w as r,v as s,b as t,m as u};
|
|
1
|
+
import{n as e,o as t,t as n}from"./commander-DEj7N1b9.js";import{c as r,f as i,t as a}from"./env-DGAe95Xm.js";import{c as o,r as s}from"./result-envelope-BMqcRDpc.js";import{y as c}from"./tool-policy-DG8pafmI.js";import{n as l}from"./cli-help-policy-DCn_wXe1.js";function u(e,t){return e.parameters.filter(e=>e.required&&t[e.optionKey]===void 0).map(e=>e.flag)}function d(e,t){return(e.requestBody?.length??0)>1&&typeof t.contentType==`string`?t.contentType:void 0}var f=e=>typeof e==`string`&&e.trim()===``;function p(e,t){let n=new Set([...t.parameters,...(t.requestBody??[]).flatMap(({parameter:e})=>e)].filter(e=>e.required).map(e=>e.optionKey));for(let t of e.options){let r=t.attributeName(),i=e.getOptionValue(r);if(!(Array.isArray(i)?i.some(f):f(i)))continue;let a=Array.isArray(i)?i.filter(e=>!f(e)):[];a.length>0?e.setOptionValue(r,a):(n.has(r)&&e.error(`error: option '${t.flags}' requires a value`),e.setOptionValue(r,void 0))}}function m(e){return e.split(` `)[0]??e}function h(e){if(e.requestBody===void 0||e.requestBody.length===0){let[t,n]=e.parameters.filter(e=>e.required);return n===void 0&&t?.schemaType===`string`?t:void 0}if(e.requestBody.length!==1||e.parameters.some(e=>e.required))return;let t=e.requestBody[0]?.parameter??[],n=t.filter(e=>e.required);if(n.length===1&&n[0]?.schemaType===`string`)return n[0];if(n.length!==0||e.intent!==`search`)return;let r=t.filter(e=>{let t=e.name.split(`.`).at(-1);return e.schemaType===`string`&&(t===`query`||t===`search`)});return r.length===1?r[0]:void 0}function g(e,t,n){let r=t.join(` `).trim();return r.length===0?o(`No positional text`,n):n[e.optionKey]===void 0?o(`Positional text parsed`,{...n,[e.optionKey]:r}):s(`Unexpected argument "${r}": ${m(e.flag)} already sets this value, and this command has no subcommand by that name. Drop "${r}".`)}var _={addresses:{summary:`List Address Links`,section:`administration`},"addresses links":{summary:`Returns every entity and person linked to this physical address, past and present, with each link's id, the linked record's id, and its role when one is recorded`},auth:{summary:`Sign-in, session, API key, and CLI authorization endpoints`,section:`account`},"auth api-key":{summary:`Get Current API Key`},"auth me":{summary:`Current User Permissions`},"auth me permissions":{summary:`Returns the current caller's resolved roles and permissions`},billing:{summary:`Plans, prices, subscription, usage, and upgrades`,section:`account`},"billing additional-usage":{summary:`Update Additional Usage Settings`},"billing ai-credits":{summary:`Read the Current AI Credit Allowance`},"billing checkout-sessions":{summary:`Create or Reuse a Checkout Session`},"billing credit-purchases":{summary:`Read a Prepaid Credit Purchase Confirmation`},"billing plan-change-previews":{summary:`Preview a Subscription Plan Change`},"billing plan-changes":{summary:`Change the Subscription Plan`},"billing plans":{summary:`List Subscription Tiers and Plans`},"billing portal-sessions":{summary:`Create a Hosted Billing Portal Session`},"billing subscription":{summary:`Read the Current Billing Subscription`},"billing subscription next-charge":{summary:`Preview the Next Subscription Charge`},"billing subscription payment-profile":{summary:`Read Your Card on File and Introductory Offer`},content:{summary:`Publications about one company or person, and platform-wide publication search`,section:`researchData`},"content facets":{summary:`Count One Owner's Publications`},directory:{summary:`Views of the public directories: publish, list, and read shared views by slug, and export a view's rows as JSON, CSV, or XLSX`,section:`researchData`},"directory exports":{summary:`Export Directory Records`},"directory shared":{summary:`List Shared Directory Views`},"directory shared slug":{summary:`Read a Shared Directory View by Slug`},enrichments:{summary:`Enrich Companies, People, or a News Article's Mentions`,section:`researchData`},entities:{summary:`Companies and funds: people, funding, and news`,section:`researchData`},"entities acquisitions":{summary:`Acquisitions a company made or was part of`},"entities addresses":{summary:`A company's recorded office and headquarters addresses`},"entities analysis-replay":{summary:`Get an Example Published Analysis Section`},"entities blog-posts":{summary:`External blog and article links for entities and people`},"entities brand":{summary:`Get a Company's Names, Logos, Links, and Tags`},"entities classifications":{summary:`Classification tags on a company, and suggested tags`},"entities classifications catalog":{summary:`Get the Company Classification Taxonomy`},"entities classifications suggestions":{summary:`Suggest Classifications for a Company`},"entities classifications tags":{summary:`List Classification Tags`},"entities contact-details":{summary:`List a Company's Contact Details`},"entities employee-counts":{summary:`List a Company's Headcount Over Time`},"entities enrichments":{summary:`Enrich One Company, Product, or Service`},"entities filters":{summary:`Filter options for company listings: available values, refinement, and option search`},"entities fundraise-investor-joins":{summary:`List the Investors in a Funding Round`},"entities fundraise-rounds":{summary:`List a Company's Funding Rounds`},"entities investments":{summary:`List the Investments a Company Made`},"entities investor-activity":{summary:`Get Investor Portfolio Counts, Sectors and Recipients`},"entities investors":{summary:`List a Company's Investors`},"entities investors people":{summary:`List Person Investors`},"entities logo":{summary:`Get a Company Logo`},"entities lookup-exact":{summary:`Read Full Entity Detail by aVenture Profile URL, Slug, Website, or Domain`},"entities people":{summary:`People linked to companies, and the role each one holds`},"entities relationships":{summary:`Relationships between companies, investors, and other organizations`},"entities relationships types":{summary:`List Entity Relationship Types`},"entities repositories":{summary:`List a Company's GitHub Repositories`},"entities research":{summary:`Get the Research Gathered About a Company`},"entities research-details":{summary:`List Research Details`},"entities research-details types":{summary:`List the Accepted Research Detail Types`},"entities research-snippets":{summary:`List Research Snippets`},"entities research-snippets types":{summary:`List the Accepted Research Snippet Types`},"entities search":{summary:`Search Companies, Products, and Services`},"entities search jobs":{summary:`Get an Async Semantic Entity Search`},"entities sec":{summary:`Get SEC EDGAR Facts for an SEC Registrant`},"entities similar":{summary:`Similar companies, as full records or short summaries, by id`},"entities similar summary":{summary:`Get Similar Company Summaries by ID`},"entities slug":{summary:`Get a Company's Slug`},"entities texts":{summary:`Descriptions and other written text for companies and people`},"entities texts types":{summary:`List the Accepted Company Text Types`},"entities trending-news":{summary:`List Trending News About a Company`},"entities types":{summary:`List the Accepted typeRecord Values`},"entities unique-ids":{summary:`External identifiers and the records they name`},"entities urls":{summary:`Websites, social profiles, and other URLs for companies and people`},"entities valuations":{summary:`List a Company's Valuation Over Time`},help:{summary:`Answer a Natural-Language Platform Help Question`,section:`cli`},lookup:{summary:`Identify a Company, Product, Service, or Person by Name, URL, or ID`,section:`researchData`},"lookup jobs":{summary:`Get a Lookup Job's State and the Records Its Article Names`},metrics:{summary:`Get Platform Totals for Companies, Funding, and People`,section:`cli`,listed:!1},news:{summary:`News linked to the companies and people in it`,section:`researchData`},"news feedback":{summary:`Submit News Feedback`},"news related-entities":{summary:`List the Entities a News Article Is About`},"news subscriptions":{summary:`List Entity News Subscriptions`},"news subscriptions test-events":{summary:`Send a Test News Event`},"news thumbnail":{summary:`Get News Thumbnail`},people:{summary:`Founders and investors, and what they back`,section:`researchData`},"people addresses":{summary:`A person's recorded addresses`},"people blog-posts":{summary:`External blog and article links for entities and people`},"people contact-details":{summary:`List a Person's Contact Details`},"people enrichments":{summary:`Enrich One Person`},"people entities":{summary:`People linked to companies, and the role each one holds`},"people filters":{summary:`Filter options for people listings and option search`},"people graph":{summary:`Get Person Graph`},"people investments":{summary:`List a Person's Investments`},"people investor-activity":{summary:`Get Person Investor Activity`},"people lookup-exact":{summary:`Read One Person's Full Detail by aVenture Profile URL, Slug, or URL`},"people photo":{summary:`Get Person Photo`},"people repositories":{summary:`List a Person's GitHub Repositories`},"people similar":{summary:`List People Similar to One Person`},"people unique-ids":{summary:`External identifiers and the records they name`},"people urls":{summary:`Websites, social profiles, and other URLs for companies and people`},research:{summary:`Research requests you file for a company, Product, Service, or person, and their progress`,section:`researchData`},"research runs":{summary:`List Your Research Runs`},"research runs draft":{summary:`Get a Research Run Draft`},"research runs draft sections":{summary:`Edit a Research Draft Section`},"research runs draft sources":{summary:`Get a Research Draft's Sources`},"research runs events":{summary:`Read a Research Run's Events`},"research runs presets":{summary:`List Research Presets`},"research runs turns":{summary:`Continue a Research Session`},search:{summary:`Search Companies, People, and News Together`,section:`researchData`},"search link":{summary:`Search From a Page URL`},"search link jobs":{summary:`Get a Link Search Job`},"search natural":{summary:`Find companies and people in natural language`},"search shared":{summary:`Search companies, people, and news, or by URL`},"search shared slug":{summary:`Read a Shared Search by Slug`},"unique-ids":{summary:`External identifiers and the records they name`,section:`researchData`},"unique-ids types":{summary:`List the Accepted Unique Identifier Types`},"url-types":{summary:`List URL Types`,section:`researchData`},web:{summary:`Search companies, people, and news, or by URL`,section:`researchData`},"web searches":{summary:`Get an Async Web Search Job`},"web searches jobs":{summary:"Reads the web-search job a `Prefer: respond-async` search accepted"}};function v(e){return x(e,y())}function y(){return!!i().userBearerToken?.trim()}function b(e){return y()||!l(e,_)}function x(e,t){return t?e:e.filter(e=>!l(e.cliPath[0],_)||e.visibility!==`private`).map(S)}function S(e){let t=e.parameters.filter(C),n=e.requestBody?.map(e=>{let t=e.parameter.filter(C);return t.length===e.parameter.length?e:{...e,parameter:t}}),r=n?.every((t,n)=>t===e.requestBody?.[n]);return t.length===e.parameters.length&&r!==!1?e:{...e,parameters:t,requestBody:n}}var C=e=>e.visibility!==`private`;async function w(e){if(e===`none`||process.env[a.authToken]?.trim())return;let{materializeCliOAuthBearerCredential:t,materializeSavedCliOAuthBearerCredential:n}=await import(`./oauth-bearer-credential-BiDojkqU.js`),{materializeCliApiKeyBearerCredential:r}=await import(`./api-key-bearer-credential-BB4N6Moa.js`);await(e===`stored`?n():t()),await r()}function T(t){let r=t.findIndex(e=>e===`--version`||e===`-V`);if(r===-1)return!1;let i=new n().passThroughOptions().addOption(new e(`--environment <environment>`)).addOption(new e(`-h, --help`)).addOption(new e(`-V, --version`));return i.parseOptions(t.slice(0,r+1)),i.opts().version===!0}function E(t,i){let a=t.indexOf(`--`),o=t.slice(0,a===-1?t.length:a),s=new n().exitOverride().configureOutput({writeErr:()=>void 0}).addOption(new e(`--environment <environment>`)).parseOptions([...o]).operands,c=i.filter(e=>O(s,e.cliPath)).toSorted((e,t)=>t.cliPath.length-e.cliPath.length)[0],l=c!==void 0&&[...c.parameters,...c.requestBody?.flatMap(({parameter:e})=>e)??[]].some(e=>e.optionKey===`environment`),u=new n().exitOverride().configureOutput({writeErr:()=>void 0}).passThroughOptions(l).addOption(new e(`--environment <environment>`).choices([...r()])),{operands:d,unknown:f}=u.parseOptions([...o]);return{environment:u.opts().environment,commandArgv:[...d,...f,...a===-1?[]:t.slice(a)],positionalOptions:l}}function D(r,i){let a=r.indexOf(`--`),o=r.slice(0,a===-1?r.length:a);if(T(r))return`none`;let s=E(r,i),u=new n().exitOverride().configureOutput({writeErr:()=>void 0}).addOption(new e(`--content-type <media-type>`)),f=u.parseOptions([...s.commandArgv]).operands;s.environment!==void 0&&(process.env.API_ENV=s.environment);let p=i.find(e=>O(f,e.cliPath)),m=p===void 0?void 0:d(p,u.opts());if(p!==void 0&&m!==void 0){let e=c(p.requestBody??[],m);if(!e.ok)throw new t(e.summary)}let h=f.at(0);return h===void 0?`stored`:h===`update`||h===`auth`&&p===void 0?`none`:o.some(e=>e===`--help`||e===`-h`)?(p??(h===`help`?i.find(e=>O(f.slice(1),e.cliPath)):void 0))!==void 0||l(h,_)?`stored`:`none`:l(h,_)?`required`:h===`help`&&f[1]===`catalog`?`optional`:h===`help`?p===void 0?`stored`:`required`:h===`agents`&&f[1]===`setup`?`required`:[`command-catalog`,`completion`].includes(h)?`optional`:h===`batch`?`required`:p===void 0?`optional`:`required`}function O(e,t){return t.every((t,n)=>e[n]===t)}export{T as a,_ as c,u as d,p as f,E as i,d as l,g as m,D as n,x as o,h as p,w as r,v as s,b as t,m as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{n as commandAuthMaterializationMode,r as materializeCommandCredential}from"./startup-auth-
|
|
1
|
+
export{n as commandAuthMaterializationMode,r as materializeCommandCredential}from"./startup-auth-BuGIFRmd.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aventurevc/aventure-cli",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.387",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Command-line access to aVenture research data on companies, people, funding, and news.",
|
|
6
6
|
"homepage": "https://docs.aventure.vc/cli",
|
|
@@ -33,9 +33,9 @@
|
|
|
33
33
|
},
|
|
34
34
|
"aventurePublicApi": {
|
|
35
35
|
"repository": "aventurevc/aventure-docs",
|
|
36
|
-
"commit": "
|
|
36
|
+
"commit": "2561efc1068c508d0da9da42c678a8d790e951e0",
|
|
37
37
|
"openapiPath": "openapi/openapi.json",
|
|
38
|
-
"openapiSha256": "
|
|
38
|
+
"openapiSha256": "1a0333c28afdaa2e19fe9a9d55edcc2794a3dcda5e8261c805ef3c05bda75795"
|
|
39
39
|
},
|
|
40
40
|
"scripts": {}
|
|
41
41
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{t as logoutCliCredentials}from"./logout-Du693hU1.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{t as materializeCliOAuthBearerCredential,n as materializeSavedCliOAuthBearerCredential}from"./oauth-bearer-credential-DlyXyoGr.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export{s as writeShowResult}from"./operations-catalog-BV65bfY8.js";
|