@aventurevc/aventure-cli 0.8.34 → 0.8.35

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.
@@ -1,4 +1,4 @@
1
- import{$ as e,Bt as t,C as n,D as r,E as i,Ht as a,Rt as o,T as s,V as c,Y as l,Z as u,_ as d,at as f,b as p,c as m,ct as h,et as g,f as _,g as v,h as ee,l as te,m as ne,nt as re,o as ie,ot as y,p as ae,q as oe,rt as b,s as se,st as x,tt as ce,u as le,x as ue,z as de,zt as S}from"./auth-BGCkxIpd.js";import{R as fe,T as C,b as w,i as T,k as pe,s as me,y as he}from"./person-owner-9MfK4f_5.js";import{A as ge,C as _e,D as ve,M as E,N as ye,O as be,S as xe,T as Se,a as Ce,b as we,c as Te,d as Ee,g as De,j as Oe,k as ke,l as Ae,m as je,o as Me,r as Ne,s as Pe,t as Fe,u as Ie,v as Le,w as Re,x as ze,y as Be}from"./oauth-bearer-credential-C6qZqSzH.js";import{_ as Ve,a as He,c as Ue,d as We,f as Ge,g as Ke,h as qe,l as Je,m as Ye,n as Xe,o as D,p as Ze,r as O,s as Qe,t as k,u as $e}from"./openapi-commands-JaBXH77z.js";import{a as et}from"./text-field-Jxu-y1IN.js";import{a as tt,n as nt,o as rt,r as it,t as at}from"./text-response-BIJ8COZZ.js";import{n as ot,r as st,t as ct}from"./oauth-login-BZ98-fvQ.js";import{spawnSync as lt}from"node:child_process";import{basename as ut,dirname as A,resolve as j,sep as M}from"node:path";import{copyFileSync as dt,existsSync as ft,lstatSync as pt,mkdirSync as mt,mkdtempSync as ht,readFileSync as gt,readlinkSync as _t,realpathSync as vt,renameSync as yt,rmdirSync as bt,unlinkSync as xt,writeFileSync as St}from"node:fs";import N,{stderr as P,stdin as Ct}from"node:process";import{TextDecoder as wt,inspect as Tt}from"node:util";import{fileURLToPath as Et}from"node:url";import{readFile as Dt}from"node:fs/promises";import{webcrypto as Ot}from"node:crypto";import{homedir as kt,hostname as At,platform as jt}from"node:os";import{setTimeout as Mt}from"node:timers/promises";import{createInterface as Nt}from"node:readline/promises";function Pt(e,t,n){let r={...n};for(let n of t.parameter){let t=n.envName;if(t===void 0)continue;let i=process.env[t]?.trim();if(i===void 0||i.length===0)continue;let a=r[n.optionKey];if(a!==void 0&&(typeof a!=`string`||a!==i))return{...y(`${e} ${n.flag.split(` `)[0]??n.name} conflicts with ${t}; omit the flag or use ${i}.`),data:r};a===void 0&&(r[n.optionKey]=i)}return x(`Environment-bound options applied`,r)}function Ft(e,t,n){if(!I(n))return null;for(let r of t.parameter){let t=r.envName,i=t===void 0?void 0:process.env[t]?.trim();if(t===void 0||i===void 0||i.length===0||!Yt(n,r.name))continue;let a=Jt(n,r.name);if(typeof a!=`string`||a!==i)return`${e} ${r.name} in --from-file conflicts with ${t}; omit the field or use ${i}.`}return null}function It(e){let t=new Set(e.parameter.map(({name:e})=>e));return e.kind===`multipart`?e.requiredPath:e.requiredPath.filter(e=>!t.has(e))}function Lt(e,t,n,r=!1){if(r||!F(t)||!Array.isArray(n))return $t(e,t,n);for(let[r,i]of n.entries()){let n=$t(e,t,i,r);if(!n.ok)return n}return x(`Body value assigned`,null)}function Rt(e,t,n,r){return $t(e,t,r,n)}function zt(e){let t=[];for(let n of e.split(`.`)){let e=tn(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function Bt(e,t){let n=zt(t);if(n===null)return null;let r=qt(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:Kt(r)}:null}function Vt(e,t){if(F(e.name)||e.schemaType===`array`)return x(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return x(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?x(`Scalar body option selected`,t[0]):y(`${n} was already given; pass it once.`)}var Ht=/^(?<row>\d+):(?<item>.*)$/su;function Ut(e,t){let n=zt(e.name);if(e.schemaType!==`array`||n===null||t===void 0||typeof t==`boolean`)return null;let r=new Map,i=[];for(let e of typeof t==`string`?[t]:t){let t=Ht.exec(e)?.groups,n=t?.row,a=t?.item;if(n===void 0||a===void 0){i.push(e);continue}let o=r.get(Number(n));o===void 0?r.set(Number(n),[a]):o.push(a)}return r.size===0?null:{container:n,rows:r,plain:i}}function Wt(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&zt(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function Gt(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=Bt(r,i.name);if(a===null)continue;if(a.firstHole!==null)return y(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||Ut(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return y(`${o} fills one ${a.path}[] row's list, so ${e} cannot also build ${a.rowCount} ${a.path}[] rows from direct options — prefix each value with its 0-based ${a.path}[] row index, as 0:value, or pass the rows with --from-file.`)}return null}function Kt(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function qt(e,t){let n=e;for(let e of t){if(!I(n))return;n=n[e]??null}return n}function Jt(e,t){if(!F(t))return qt(e,t.split(`.`))}function Yt(e,t){return Zt(e,t.split(`.`))}function Xt(e,t,n){if(!I(n))return null;let r=new Set(t.parameter.map(({name:e})=>e));for(let i of e)if(i!==t){for(let e of i.parameter)if(!r.has(e.name)&&Yt(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function Zt(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=tn(n);if(!I(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>Zt(e,r)):Zt(a,r)}function F(e){return e.split(`.`).some(e=>tn(e).isArray)}function Qt(e,t){return e.parameter.length===0||!I(t)?null:rn(t,[],nn(e.parameter))}function I(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $t(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=tn(o),c=e===i.length-1,l=en(a,s,t,c,n,r);if(!l.ok||l.data===null)return y(l.summary,l.warnings);if(c)return x(`Body value assigned`,null);a=l.data}return y(`${t} is not a valid body option path.`)}function en(e,t,n,r,i,a){let o=()=>y(`${n} cannot be combined with another body option at ${t.key}.`),s=e[t.key];if(t.isArray){if(s!==void 0&&!Array.isArray(s))return o();let n=s??[];if(s===void 0&&(e[t.key]=n),r)return n[a]===void 0?(n[a]=i,x(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,x(`Body path created`,e)}return I(c)?x(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,x(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,x(`Body path created`,n)}return I(s)?x(`Body path stepped`,s):o()}function tn(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function nn(e){let t=new Set,n=new Set;for(let r of e){let e=`${r.name}${r.schemaType===`array`?`[]`:``}`;t.add(e);let i=e.split(`.`);for(let e=1;e<i.length;e+=1)n.add(i.slice(0,e).join(`.`))}return{leaf:t,prefix:n}}function rn(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=rn(r,t,n);if(e!==null)return e}return null}if(!I(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!an(a,n)){if(!on(e))continue;return{path:a,suggestion:sn(e,n)}}let o=rn(i,e,n);if(o!==null)return o}return null}function an(e,t){return t.prefix.has(e)||t.leaf.has(e)}function on(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function sn(e,t){let n=e.slice(0,-1).join(`.`),r=e.at(-1)?.replace(/\[\]$/u,``).toLowerCase()??``;return[...t.leaf].filter(e=>e.split(`.`).slice(0,-1).join(`.`)===n).map(e=>({path:e,score:cn(r,e.split(`.`).at(-1)??``)})).filter(({score:e})=>e<1/0).toSorted((e,t)=>e.score-t.score||e.path.localeCompare(t.path))[0]?.path}function cn(e,t){let n=t.replace(/\[\]$/u,``).toLowerCase();return n===e?0:n.endsWith(e)||e.endsWith(n)?1:n.includes(e)||e.includes(n)?2:1/0}function ln(e,t){let n=new Map;for(let e of t){let t=e.flag?.split(` `)[0];t!==void 0&&n.set(t,t===`--from-file`?{...e,inputType:`file`}:e)}for(let t of e){let e=t.long===void 0?void 0:n.get(t.long);e!==void 0&&t.helpGroup(Ke(e))}e.sort((e,t)=>{let r=e.long===void 0?void 0:n.get(e.long),i=t.long===void 0?void 0:n.get(t.long);return r!==void 0&&i!==void 0?_n(r,i):r===void 0?i===void 0?0:1:-1})}function un(e){let t=new Map;for(let n of e)for(let e of n.parameter){let r=e.flag.split(` `)[0]??e.flag,i=t.get(r);i===void 0?t.set(r,{variant:[{descriptor:n,parameter:e}]}):t.set(r,{variant:[...i.variant,{descriptor:n,parameter:e}]})}return[...t.values()]}function dn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function fn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:hn(e,t)})),n=t[0];return n===void 0?``:t.every(({text:e})=>e===n.text)?`${n.text===``?``:`${n.text} `}Request content: ${t.map(({contentType:e})=>e).join(`, `)}.`:t.map(({contentType:e,text:t})=>`${e}: ${t}`).join(` `)}function pn(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function mn(e,t){let n=e.kind===`multipart`?`Read a JSON object keyed by multipart part name from a file, or use - for stdin`:`Read the JSON request body from a file, or use - for stdin`,r=t.filter(e=>!t.some(t=>t.startsWith(`${e}.`)||t.startsWith(`${e}[].`)));return r.length===0?Ve(n):`${Ve(n)} Required JSON paths: ${r.join(`, `)}.`}function hn(e,t){let n=Ye(t.description,void 0),r=e.kind!==`multipart`&&F(t.name),i=e.kind!==`multipart`&&t.optionKey!==t.name&&/^\w+$/u.test(t.name);return`${n}${r?` Repeat to add another value.`:``}${i?` --from-file JSON key: ${t.name}.`:``}${gn(e,t)}`}function gn(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=zt(t.name);return n===null?``:` Prefix each value with its 0-based ${n}[] row index, as 0:value, to fill more than one ${n}[] row. A leading digits-and-colon is always read as that index, so name the row of a value that starts the same way, as 0:0:00 for the value 0:00.`}function _n(e,t){return qe(e)-qe(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function vn(e){let t;try{t=e===`-`?await yn():await Dt(e,`utf8`)}catch(t){return y(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return x(`No input provided`,null);let e=JSON.parse(t);return x(`Input parsed`,e)}catch(e){return y(`Input is not valid JSON: ${e.message}`)}}async function yn(){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 bn=`--content-type`;function xn(e,t,n){let r=e=>!n?.has(e)&&(n?.add(e),!0),i=t.requestBody??[];if(i.length>1&&r(bn)){let t=i.map(({contentType:e})=>e);e.addOption(new S(`${bn} <media-type>`,`Select the request content type; omit for ${t[0]}.`).choices(t).argParser(Cn(i)))}if(Hn(t)&&r(`--from-file`)){let n=i[0];if(n===void 0)throw Error(`${t.operationId} has no request body`);e.addOption(new S(`--from-file <path>`,mn(n,n.requiredPath)).argParser(Tn(`--from-file`)))}let a=un(i).filter(e=>r(L(e.variant[0].parameter)));for(let t of a.toSorted((e,t)=>_n(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:n,parameter:r}=t.variant[0],a=new S(dn(t),i.length>1?fn(t):hn(n,r));i.length===1&&r.envName!==void 0&&a.env(r.envName);let o=i.length===1?pn(n,r.optionKey):[];o.length>0&&a.conflicts(o),i.length>1?a.argParser(Sn):F(r.name)||r.schemaType===`array`?a.argParser(wn):a.argParser(Tn(r.flag)),e.addOption(a),a.envVar!==void 0&&e.on(`optionEnv:${a.name()}`,()=>{let t=e.opts()[r.optionKey];typeof t==`string`&&t.trim()&&e.setOptionValueWithSource(r.optionKey,t.trim(),`env`)})}Vn(e,t,a)}function Sn(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function Cn(e){return(t,n)=>{if(n!==void 0)throw new a(`${bn} was already given; pass it once.`);let i=r(e,t);if(!i.ok)throw new a(i.summary);return t}}function wn(e,t){return[...t??[],e]}function Tn(e){let t=e.split(/\s+/u)[0]??e;return(e,n)=>{if(n!==void 0)throw new a(`${t} was already given; pass it once.`);return e}}async function En(e,t){let n=typeof t.contentType==`string`?t.contentType:void 0,i=r(e.requestBody??[],n);if(!i.ok||i.data===null)return y(i.summary,i.warnings);let a=i.data;if(a===void 0)return x(`No body`,void 0);let o=Dn(e,a,t);if(o!==null)return y(o);let s=Pt(e.operationId,a,t);if(!s.ok)return y(s.summary,s.warnings);t=s.data;let c=On(a,t);if(c!==null)return y(c);let l=await Mn(t);if(!l.ok)return y(l.summary,l.warnings);let u=Xt(e.requestBody??[],a,l.data);if(u!==null)return y(u);let d=jn(e.operationId,a,l.data);if(!d.ok)return d;let f=Ft(e.operationId,a,l.data);if(f!==null)return y(f);let p=Nn(e.operationId,a,t);if(!p.ok)return p;if(l.data===void 0&&p.data===void 0)return a.required?y(Bn(e.operationId,a)):x(`No body`,void 0);let m=Fn(e.operationId,l.data,p.data);if(!m.ok||m.data===void 0)return m;if(a.schemaType===`array`&&!Array.isArray(m.data))return y(`${e.operationId} requires a JSON array body.`);if(a.parameter.length>0&&!I(m.data)){let t=a.kind===`multipart`?` keyed by multipart part name`:` body`;return y(`${e.operationId} requires a JSON object${t}.`)}let h=An(a,m.data);if(h.length>0)return y(`${e.operationId} requires body option(s): ${h.join(`, `)}`);let g=m.data,_=I(g)?It(a).filter(e=>!Yt(g,e)):[];return _.length>0?y(kn(e.operationId,a,_)):m}function Dn(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`${L(t)} requires ${bn} ${i.join(` or `)}.`}return null}function On(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 kn(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 An(e,t){return I(t)?e.parameter.filter(e=>e.required&&!Yt(t,e.name)).map(L):[]}function jn(e,t,n){let r=Qt(t,n);if(r===null)return x(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion}.`;return y(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function Mn(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return x(`No body file`,void 0);let n=await vn(t);if(!n.ok)return y(n.summary,n.warnings);let r=h.safeParse(n.data);return r.success?x(`Input parsed`,r.data):y(`Input is not valid JSON value: ${r.error.message}`)}function Nn(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=Vt(e,n[e.optionKey]);if(!a.ok||a.data===null)return y(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=Pn(t,n,r,e,o);if(!s.ok)return y(s.summary,s.warnings);i=!0}if(!i)return x(`No direct body options`,void 0);let a=Gt(e,t,n,r);return a===null?x(`Direct body options parsed`,r):a}function Pn(e,t,n,r,i){let a=Ut(r,i);if(a===null){let e=Rn(r,i);return e.ok?Lt(n,r.name,e.data,r.schemaType===`array`):y(e.summary,e.warnings)}if(a.plain.length>0)return y(`${L(r)} mixes row-form values with plain value(s): ${a.plain.join(`, `)} — prefix every value with its 0-based ${a.container}[] row index, as 0:value.`);let o=Wt(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return y(`${L(r)} names ${a.container}[] row ${e}, but these options build at most ${o} ${a.container}[] row(s) — number rows from 0, and name the row of a value that itself starts with digits and a colon, as 0:0:00 for the value 0:00.`);for(let[e,t]of a.rows){let i=[];for(let e of t){let t=zn(r.name,r.itemSchemaType,e);if(!t.ok)return y(t.summary,t.warnings);i.push(t.data)}let a=Rt(n,r.name,e,i);if(!a.ok)return a}return x(`Body value assigned`,null)}var L=e=>e.flag.split(` `)[0]??e.name;function Fn(e,t,n){if(t===void 0)return x(`Direct body parsed`,n);if(n===void 0)return x(`Input parsed`,t);if(I(t)&&I(n))try{return x(`Input parsed`,In(t,n))}catch(t){return y(`${e} ${t.message}`)}return y(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function In(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(Array.isArray(t)&&Array.isArray(r))throw Error(`cannot combine --from-file array '${e}' with array body options at the same key — move the per-item fields inside the matching '${e}[]' object(s) in the file body.`);if(t!==void 0&&Ln(t)!==Ln(r))throw Error(`cannot combine --from-file ${Ln(t)} '${e}' with ${Ln(r)} body option(s) at the same key — align the file body shape with the schema.`);n[e]=I(t)&&I(r)?In(t,r):r}return n}function Ln(e){return Array.isArray(e)?`array`:I(e)?`object`:`scalar`}function Rn(e,t){if(typeof t==`boolean`)return x(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return zn(e.name,e.schemaType,t??``);let n=[],r=F(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=zn(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return x(`Body value parsed`,n)}function zn(e,t,n){if(t===`boolean`)return n===`true`?x(`Body value parsed`,!0):n===`false`?x(`Body value parsed`,!1):y(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?y(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?y(`${e} must be an integer.`):x(`Body value parsed`,i)}return x(`Body value parsed`,n)}function Bn(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(L).join(`, `)}`;let r=It(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(L).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function Vn(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:bn,location:`body`}),Hn(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),ln(e.options,r)}function Hn(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function Un(e){let t=f(e);return Qn(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function Wn(e){Qn(e);let t=at(e.data,e.summary);if(e.ok&&t!==null){process.stdout.write(t.endsWith(`
1
+ import{$ as e,Bt as t,C as n,D as r,E as i,Ht as a,Rt as o,T as s,V as c,Y as l,Z as u,_ as d,at as f,b as p,c as m,ct as h,et as g,f as _,g as v,h as ee,l as te,m as ne,nt as re,o as ie,ot as y,p as ae,q as oe,rt as b,s as se,st as x,tt as ce,u as le,x as ue,z as de,zt as S}from"./auth-o0Bk3f3c.js";import{R as fe,T as C,b as w,i as T,k as pe,s as me,y as he}from"./person-owner-9MfK4f_5.js";import{A as ge,C as _e,D as ve,M as E,N as ye,O as be,S as xe,T as Se,a as Ce,b as we,c as Te,d as Ee,g as De,j as Oe,k as ke,l as Ae,m as je,o as Me,r as Ne,s as Pe,t as Fe,u as Ie,v as Le,w as Re,x as ze,y as Be}from"./oauth-bearer-credential-boAXSRDY.js";import{_ as Ve,a as He,c as Ue,d as We,f as Ge,g as Ke,h as qe,l as Je,m as Ye,n as Xe,o as D,p as Ze,r as O,s as Qe,t as k,u as $e}from"./openapi-commands-CTzllhhv.js";import{a as et}from"./text-field-C7a277EN.js";import{a as tt,n as nt,o as rt,r as it,t as at}from"./text-response-8kYRmQBZ.js";import{n as ot,r as st,t as ct}from"./oauth-login-CP2Hh0U0.js";import{spawnSync as lt}from"node:child_process";import{basename as ut,dirname as A,resolve as j,sep as M}from"node:path";import{copyFileSync as dt,existsSync as ft,lstatSync as pt,mkdirSync as mt,mkdtempSync as ht,readFileSync as gt,readlinkSync as _t,realpathSync as vt,renameSync as yt,rmdirSync as bt,unlinkSync as xt,writeFileSync as St}from"node:fs";import N,{stderr as P,stdin as Ct}from"node:process";import{TextDecoder as wt,inspect as Tt}from"node:util";import{fileURLToPath as Et}from"node:url";import{readFile as Dt}from"node:fs/promises";import{webcrypto as Ot}from"node:crypto";import{homedir as kt,hostname as At,platform as jt}from"node:os";import{setTimeout as Mt}from"node:timers/promises";import{createInterface as Nt}from"node:readline/promises";function Pt(e,t,n){let r={...n};for(let n of t.parameter){let t=n.envName;if(t===void 0)continue;let i=process.env[t]?.trim();if(i===void 0||i.length===0)continue;let a=r[n.optionKey];if(a!==void 0&&(typeof a!=`string`||a!==i))return{...y(`${e} ${n.flag.split(` `)[0]??n.name} conflicts with ${t}; omit the flag or use ${i}.`),data:r};a===void 0&&(r[n.optionKey]=i)}return x(`Environment-bound options applied`,r)}function Ft(e,t,n){if(!I(n))return null;for(let r of t.parameter){let t=r.envName,i=t===void 0?void 0:process.env[t]?.trim();if(t===void 0||i===void 0||i.length===0||!Yt(n,r.name))continue;let a=Jt(n,r.name);if(typeof a!=`string`||a!==i)return`${e} ${r.name} in --from-file conflicts with ${t}; omit the field or use ${i}.`}return null}function It(e){let t=new Set(e.parameter.map(({name:e})=>e));return e.kind===`multipart`?e.requiredPath:e.requiredPath.filter(e=>!t.has(e))}function Lt(e,t,n,r=!1){if(r||!F(t)||!Array.isArray(n))return $t(e,t,n);for(let[r,i]of n.entries()){let n=$t(e,t,i,r);if(!n.ok)return n}return x(`Body value assigned`,null)}function Rt(e,t,n,r){return $t(e,t,r,n)}function zt(e){let t=[];for(let n of e.split(`.`)){let e=tn(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function Bt(e,t){let n=zt(t);if(n===null)return null;let r=qt(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:Kt(r)}:null}function Vt(e,t){if(F(e.name)||e.schemaType===`array`)return x(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return x(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?x(`Scalar body option selected`,t[0]):y(`${n} was already given; pass it once.`)}var Ht=/^(?<row>\d+):(?<item>.*)$/su;function Ut(e,t){let n=zt(e.name);if(e.schemaType!==`array`||n===null||t===void 0||typeof t==`boolean`)return null;let r=new Map,i=[];for(let e of typeof t==`string`?[t]:t){let t=Ht.exec(e)?.groups,n=t?.row,a=t?.item;if(n===void 0||a===void 0){i.push(e);continue}let o=r.get(Number(n));o===void 0?r.set(Number(n),[a]):o.push(a)}return r.size===0?null:{container:n,rows:r,plain:i}}function Wt(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&zt(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function Gt(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=Bt(r,i.name);if(a===null)continue;if(a.firstHole!==null)return y(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||Ut(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return y(`${o} fills one ${a.path}[] row's list, so ${e} cannot also build ${a.rowCount} ${a.path}[] rows from direct options — prefix each value with its 0-based ${a.path}[] row index, as 0:value, or pass the rows with --from-file.`)}return null}function Kt(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function qt(e,t){let n=e;for(let e of t){if(!I(n))return;n=n[e]??null}return n}function Jt(e,t){if(!F(t))return qt(e,t.split(`.`))}function Yt(e,t){return Zt(e,t.split(`.`))}function Xt(e,t,n){if(!I(n))return null;let r=new Set(t.parameter.map(({name:e})=>e));for(let i of e)if(i!==t){for(let e of i.parameter)if(!r.has(e.name)&&Yt(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function Zt(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=tn(n);if(!I(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>Zt(e,r)):Zt(a,r)}function F(e){return e.split(`.`).some(e=>tn(e).isArray)}function Qt(e,t){return e.parameter.length===0||!I(t)?null:rn(t,[],nn(e.parameter))}function I(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $t(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=tn(o),c=e===i.length-1,l=en(a,s,t,c,n,r);if(!l.ok||l.data===null)return y(l.summary,l.warnings);if(c)return x(`Body value assigned`,null);a=l.data}return y(`${t} is not a valid body option path.`)}function en(e,t,n,r,i,a){let o=()=>y(`${n} cannot be combined with another body option at ${t.key}.`),s=e[t.key];if(t.isArray){if(s!==void 0&&!Array.isArray(s))return o();let n=s??[];if(s===void 0&&(e[t.key]=n),r)return n[a]===void 0?(n[a]=i,x(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,x(`Body path created`,e)}return I(c)?x(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,x(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,x(`Body path created`,n)}return I(s)?x(`Body path stepped`,s):o()}function tn(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function nn(e){let t=new Set,n=new Set;for(let r of e){let e=`${r.name}${r.schemaType===`array`?`[]`:``}`;t.add(e);let i=e.split(`.`);for(let e=1;e<i.length;e+=1)n.add(i.slice(0,e).join(`.`))}return{leaf:t,prefix:n}}function rn(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=rn(r,t,n);if(e!==null)return e}return null}if(!I(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!an(a,n)){if(!on(e))continue;return{path:a,suggestion:sn(e,n)}}let o=rn(i,e,n);if(o!==null)return o}return null}function an(e,t){return t.prefix.has(e)||t.leaf.has(e)}function on(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function sn(e,t){let n=e.slice(0,-1).join(`.`),r=e.at(-1)?.replace(/\[\]$/u,``).toLowerCase()??``;return[...t.leaf].filter(e=>e.split(`.`).slice(0,-1).join(`.`)===n).map(e=>({path:e,score:cn(r,e.split(`.`).at(-1)??``)})).filter(({score:e})=>e<1/0).toSorted((e,t)=>e.score-t.score||e.path.localeCompare(t.path))[0]?.path}function cn(e,t){let n=t.replace(/\[\]$/u,``).toLowerCase();return n===e?0:n.endsWith(e)||e.endsWith(n)?1:n.includes(e)||e.includes(n)?2:1/0}function ln(e,t){let n=new Map;for(let e of t){let t=e.flag?.split(` `)[0];t!==void 0&&n.set(t,t===`--from-file`?{...e,inputType:`file`}:e)}for(let t of e){let e=t.long===void 0?void 0:n.get(t.long);e!==void 0&&t.helpGroup(Ke(e))}e.sort((e,t)=>{let r=e.long===void 0?void 0:n.get(e.long),i=t.long===void 0?void 0:n.get(t.long);return r!==void 0&&i!==void 0?_n(r,i):r===void 0?i===void 0?0:1:-1})}function un(e){let t=new Map;for(let n of e)for(let e of n.parameter){let r=e.flag.split(` `)[0]??e.flag,i=t.get(r);i===void 0?t.set(r,{variant:[{descriptor:n,parameter:e}]}):t.set(r,{variant:[...i.variant,{descriptor:n,parameter:e}]})}return[...t.values()]}function dn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function fn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:hn(e,t)})),n=t[0];return n===void 0?``:t.every(({text:e})=>e===n.text)?`${n.text===``?``:`${n.text} `}Request content: ${t.map(({contentType:e})=>e).join(`, `)}.`:t.map(({contentType:e,text:t})=>`${e}: ${t}`).join(` `)}function pn(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function mn(e,t){let n=e.kind===`multipart`?`Read a JSON object keyed by multipart part name from a file, or use - for stdin`:`Read the JSON request body from a file, or use - for stdin`,r=t.filter(e=>!t.some(t=>t.startsWith(`${e}.`)||t.startsWith(`${e}[].`)));return r.length===0?Ve(n):`${Ve(n)} Required JSON paths: ${r.join(`, `)}.`}function hn(e,t){let n=Ye(t.description,void 0),r=e.kind!==`multipart`&&F(t.name),i=e.kind!==`multipart`&&t.optionKey!==t.name&&/^\w+$/u.test(t.name);return`${n}${r?` Repeat to add another value.`:``}${i?` --from-file JSON key: ${t.name}.`:``}${gn(e,t)}`}function gn(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=zt(t.name);return n===null?``:` Prefix each value with its 0-based ${n}[] row index, as 0:value, to fill more than one ${n}[] row. A leading digits-and-colon is always read as that index, so name the row of a value that starts the same way, as 0:0:00 for the value 0:00.`}function _n(e,t){return qe(e)-qe(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function vn(e){let t;try{t=e===`-`?await yn():await Dt(e,`utf8`)}catch(t){return y(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return x(`No input provided`,null);let e=JSON.parse(t);return x(`Input parsed`,e)}catch(e){return y(`Input is not valid JSON: ${e.message}`)}}async function yn(){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 bn=`--content-type`;function xn(e,t,n){let r=e=>!n?.has(e)&&(n?.add(e),!0),i=t.requestBody??[];if(i.length>1&&r(bn)){let t=i.map(({contentType:e})=>e);e.addOption(new S(`${bn} <media-type>`,`Select the request content type; omit for ${t[0]}.`).choices(t).argParser(Cn(i)))}if(Hn(t)&&r(`--from-file`)){let n=i[0];if(n===void 0)throw Error(`${t.operationId} has no request body`);e.addOption(new S(`--from-file <path>`,mn(n,n.requiredPath)).argParser(Tn(`--from-file`)))}let a=un(i).filter(e=>r(L(e.variant[0].parameter)));for(let t of a.toSorted((e,t)=>_n(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:n,parameter:r}=t.variant[0],a=new S(dn(t),i.length>1?fn(t):hn(n,r));i.length===1&&r.envName!==void 0&&a.env(r.envName);let o=i.length===1?pn(n,r.optionKey):[];o.length>0&&a.conflicts(o),i.length>1?a.argParser(Sn):F(r.name)||r.schemaType===`array`?a.argParser(wn):a.argParser(Tn(r.flag)),e.addOption(a),a.envVar!==void 0&&e.on(`optionEnv:${a.name()}`,()=>{let t=e.opts()[r.optionKey];typeof t==`string`&&t.trim()&&e.setOptionValueWithSource(r.optionKey,t.trim(),`env`)})}Vn(e,t,a)}function Sn(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function Cn(e){return(t,n)=>{if(n!==void 0)throw new a(`${bn} was already given; pass it once.`);let i=r(e,t);if(!i.ok)throw new a(i.summary);return t}}function wn(e,t){return[...t??[],e]}function Tn(e){let t=e.split(/\s+/u)[0]??e;return(e,n)=>{if(n!==void 0)throw new a(`${t} was already given; pass it once.`);return e}}async function En(e,t){let n=typeof t.contentType==`string`?t.contentType:void 0,i=r(e.requestBody??[],n);if(!i.ok||i.data===null)return y(i.summary,i.warnings);let a=i.data;if(a===void 0)return x(`No body`,void 0);let o=Dn(e,a,t);if(o!==null)return y(o);let s=Pt(e.operationId,a,t);if(!s.ok)return y(s.summary,s.warnings);t=s.data;let c=On(a,t);if(c!==null)return y(c);let l=await Mn(t);if(!l.ok)return y(l.summary,l.warnings);let u=Xt(e.requestBody??[],a,l.data);if(u!==null)return y(u);let d=jn(e.operationId,a,l.data);if(!d.ok)return d;let f=Ft(e.operationId,a,l.data);if(f!==null)return y(f);let p=Nn(e.operationId,a,t);if(!p.ok)return p;if(l.data===void 0&&p.data===void 0)return a.required?y(Bn(e.operationId,a)):x(`No body`,void 0);let m=Fn(e.operationId,l.data,p.data);if(!m.ok||m.data===void 0)return m;if(a.schemaType===`array`&&!Array.isArray(m.data))return y(`${e.operationId} requires a JSON array body.`);if(a.parameter.length>0&&!I(m.data)){let t=a.kind===`multipart`?` keyed by multipart part name`:` body`;return y(`${e.operationId} requires a JSON object${t}.`)}let h=An(a,m.data);if(h.length>0)return y(`${e.operationId} requires body option(s): ${h.join(`, `)}`);let g=m.data,_=I(g)?It(a).filter(e=>!Yt(g,e)):[];return _.length>0?y(kn(e.operationId,a,_)):m}function Dn(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`${L(t)} requires ${bn} ${i.join(` or `)}.`}return null}function On(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 kn(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 An(e,t){return I(t)?e.parameter.filter(e=>e.required&&!Yt(t,e.name)).map(L):[]}function jn(e,t,n){let r=Qt(t,n);if(r===null)return x(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion}.`;return y(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function Mn(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return x(`No body file`,void 0);let n=await vn(t);if(!n.ok)return y(n.summary,n.warnings);let r=h.safeParse(n.data);return r.success?x(`Input parsed`,r.data):y(`Input is not valid JSON value: ${r.error.message}`)}function Nn(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=Vt(e,n[e.optionKey]);if(!a.ok||a.data===null)return y(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=Pn(t,n,r,e,o);if(!s.ok)return y(s.summary,s.warnings);i=!0}if(!i)return x(`No direct body options`,void 0);let a=Gt(e,t,n,r);return a===null?x(`Direct body options parsed`,r):a}function Pn(e,t,n,r,i){let a=Ut(r,i);if(a===null){let e=Rn(r,i);return e.ok?Lt(n,r.name,e.data,r.schemaType===`array`):y(e.summary,e.warnings)}if(a.plain.length>0)return y(`${L(r)} mixes row-form values with plain value(s): ${a.plain.join(`, `)} — prefix every value with its 0-based ${a.container}[] row index, as 0:value.`);let o=Wt(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return y(`${L(r)} names ${a.container}[] row ${e}, but these options build at most ${o} ${a.container}[] row(s) — number rows from 0, and name the row of a value that itself starts with digits and a colon, as 0:0:00 for the value 0:00.`);for(let[e,t]of a.rows){let i=[];for(let e of t){let t=zn(r.name,r.itemSchemaType,e);if(!t.ok)return y(t.summary,t.warnings);i.push(t.data)}let a=Rt(n,r.name,e,i);if(!a.ok)return a}return x(`Body value assigned`,null)}var L=e=>e.flag.split(` `)[0]??e.name;function Fn(e,t,n){if(t===void 0)return x(`Direct body parsed`,n);if(n===void 0)return x(`Input parsed`,t);if(I(t)&&I(n))try{return x(`Input parsed`,In(t,n))}catch(t){return y(`${e} ${t.message}`)}return y(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function In(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(Array.isArray(t)&&Array.isArray(r))throw Error(`cannot combine --from-file array '${e}' with array body options at the same key — move the per-item fields inside the matching '${e}[]' object(s) in the file body.`);if(t!==void 0&&Ln(t)!==Ln(r))throw Error(`cannot combine --from-file ${Ln(t)} '${e}' with ${Ln(r)} body option(s) at the same key — align the file body shape with the schema.`);n[e]=I(t)&&I(r)?In(t,r):r}return n}function Ln(e){return Array.isArray(e)?`array`:I(e)?`object`:`scalar`}function Rn(e,t){if(typeof t==`boolean`)return x(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return zn(e.name,e.schemaType,t??``);let n=[],r=F(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=zn(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return x(`Body value parsed`,n)}function zn(e,t,n){if(t===`boolean`)return n===`true`?x(`Body value parsed`,!0):n===`false`?x(`Body value parsed`,!1):y(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?y(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?y(`${e} must be an integer.`):x(`Body value parsed`,i)}return x(`Body value parsed`,n)}function Bn(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(L).join(`, `)}`;let r=It(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(L).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function Vn(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:bn,location:`body`}),Hn(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),ln(e.options,r)}function Hn(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function Un(e){let t=f(e);return Qn(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function Wn(e){Qn(e);let t=at(e.data,e.summary);if(e.ok&&t!==null){process.stdout.write(t.endsWith(`
2
2
  `)?t:`${t}\n`),Gn(e);return}let n=e.ok?`OK`:`FAIL`;process.stdout.write(`[${n}] ${e.summary}\n`),!e.ok&&e.problem!==void 0&&Jn(e.problem),Gn(e)}function Gn(e){e.ids.length>0&&process.stdout.write(` ids: ${e.ids.join(`, `)}\n`);for(let[t,n]of Object.entries(e.counts))process.stdout.write(` ${t}: ${n}\n`);for(let t of e.references)process.stdout.write(` ref: ${t}\n`);if(e.truncation!==void 0){let t=e.truncation.omitted.join(`, `);process.stdout.write(` truncated: byteLength=${e.truncation.byteLength} maxBytes=${e.truncation.maxBytes} omitted=${t}\n`),process.stdout.write(` recovery: ${e.truncation.recovery}\n`)}for(let t of e.warnings)process.stdout.write(` warn: ${t}\n`)}function R(e,t){if(e.mode===`data`||e.mode===`data-full`){let n=e.mode===`data`?f(t):t;Qn(n),process.stdout.write(`${JSON.stringify(n.ok&&n.truncated!==!0?Kn(n.data):n)}\n`),n.ok||(process.exitCode=1);return}let n=e.mode===`json`?Un(t):t;e.mode===`text`&&Wn(n),n.ok||(process.exitCode=1)}function Kn(e){return typeof e!=`object`||!e||Array.isArray(e)||!Reflect.has(e,`method`)||!Reflect.has(e,`endpoint`)||!(`response`in e)||e.response===void 0?e:e.response}function qn(e,t){let n=nt(t);if(n===null){process.stderr.write(`explain: the response carried no search interpretation
3
3
  `),process.exitCode=1;return}(e===`text`?process.stdout:process.stderr).write(n)}function Jn(e){typeof e.code==`string`&&process.stdout.write(` code: ${e.code}\n`),typeof e.detail==`string`&&process.stdout.write(` detail: ${e.detail}\n`),typeof e.hint==`string`&&process.stdout.write(` hint: ${e.hint}\n`),typeof e.suggestion==`string`&&process.stdout.write(` suggestion: ${e.suggestion}\n`);let t=Object.entries(e.suggestions??{});if(t.length>0){let e=t.map(([e,t])=>`${e}=${t}`).join(`; `);process.stdout.write(` suggestions: ${e}\n`)}typeof e.requiredRole==`string`&&process.stdout.write(` requiredRole: ${e.requiredRole}\n`),Yn(e),Xn(`unknownParameters`,e.unknownParameters),Xn(`validParameters`,e.validParameters),Zn(e.resolution)}function Yn(e){let t=[];typeof e.limitType==`string`&&t.push(`limitType=${e.limitType}`),typeof e.used==`number`&&t.push(`used=${e.used}`),typeof e.limit==`number`&&t.push(`limit=${e.limit}`),typeof e.remaining==`number`&&t.push(`remaining=${e.remaining}`),typeof e.resetAt==`string`&&t.push(`resetAt=${e.resetAt}`),typeof e.windowSeconds==`number`&&t.push(`windowSeconds=${e.windowSeconds}`),typeof e.retryAfterSeconds==`number`&&t.push(`retryAfterSeconds=${e.retryAfterSeconds}`),t.length>0&&process.stdout.write(` meter: ${t.join(` `)}\n`)}function Xn(e,t){t!=null&&t.length>0&&process.stdout.write(` ${e}: ${t.join(`, `)}\n`)}function Zn(e){if(e==null)return;let t=[`action=${e.action}`];typeof e.parameter==`string`&&t.push(`parameter=${e.parameter}`),typeof e.fieldPath==`string`&&t.push(`fieldPath=${e.fieldPath}`),typeof e.endpoint==`string`&&t.push(`endpoint=${e.endpoint}`),e.acceptedValue!==null&&e.acceptedValue!==void 0&&e.acceptedValue.length>0&&t.push(`acceptedValue=${e.acceptedValue.join(`, `)}`),typeof e.retryable==`boolean`&&t.push(`retryable=${e.retryable}`),process.stdout.write(` resolution: ${t.join(` `)}\n`)}function Qn(e){e.ok&&e.warnings.length===0||c({component:l().bin[0],event:e.ok?`command_warning`:`command_failed`,message:e.warnings.length>0?e.warnings.join(` | `):e.summary,fields:{warningCount:e.warnings.length,summary:e.summary}})}function $n(e,t,n=l().bin[0]){let r=e.limit===void 0?void 0:Number(e.limit);if(r!==void 0&&(e.limit?.trim()===``||!Number.isInteger(r)||r<0))return y(`Invalid --limit value: ${JSON.stringify(e.limit)} (expected a non-negative integer)`,["Pass a non-negative integer, e.g. `--limit 20`."]);let i=it(e.q??``,nr(t,n).filter(t=>or(t,e)),e=>({...e,cliPath:e.cli.path,enumParameter:e.flags.map(({choices:e,location:t})=>({values:e,direct:t!==`body`})),parameterName:e.flags.flatMap(({wireName:e,optionKey:t})=>[e,t]),parameterDescription:[e.body.description,...e.flags.map(({description:e})=>e)]})).map(({item:e})=>e),a=i.slice(0,r);return x(`Operation catalog matches`,{operation:a,count:{totalOperations:t.length,matched:i.length,returned:a.length}})}function er(e,t,n=l().bin[0]){let r=nr(t,n),i=e.operationId===void 0?tr(r,e.command):r.find(t=>t.operationId===e.operationId);if(i===void 0){let i=yr(e.command??``),a=r.map(e=>e.cli.command).filter(e=>e.startsWith(`${n} ${i} `));if(a.length>0)return y(`${i} is a command group; show one of its subcommands.`,[`Run \`${n} command-catalog show --command "<subcommand>"\` with one of:`,...a]);let o=i.split(` `),s=new Set([...[...o.keys()].map(e=>o.slice(e+1).join(` `)),...o.slice(1).map((e,t)=>o.toSpliced(t,2,`${o[t]}-${e}`).join(` `))]),c=$n({q:e.command??e.operationId},t,n),l=[...r.filter(({cli:e})=>e.path.length>1&&s.has(e.path.join(` `))).toSorted((e,t)=>t.cli.path.length-e.cli.path.length),...c.data?.operation??[]];return y(`Generated operation not found`,[...[...new Set(l.map(({cli:e,operationId:t})=>`${e.command} (operationId ${t})`))].slice(0,3).map(e=>`closest: ${e}`),`List candidates with \`${n} command-catalog search "<text>"\`.`])}return x(`Generated operation detail`,{operation:i,usage:cr(i,r)})}function tr(e,t){if(t===void 0)return;let{bin:n}=l(),r=yr(t,n);return e.find(e=>yr(e.cli.command,n)===r)}function nr(e,t){return e.map(e=>{let n=e.requestBody??[],r=[...e.parameters.map(e=>rr(e)),...n.flatMap(e=>e.parameter.map(t=>rr(t,n.length>1?e.contentType:void 0))),...ir(n)],a=[t,...e.cliPath].join(` `),o=s(e.intent),c=e.method===`DELETE`||e.intent===`delete`,l=n[0];return{operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,scope:e.scope,mutates:o,destructive:c,auth:e.auth,cli:{command:a,path:e.cliPath},mcpTool:e.binaryResponse?null:i(e.intent),body:{hasBody:l!==void 0,kind:l?.kind??null,...l!==void 0&&n.length>1?{contentType:l.contentType}:{},required:l?.required??!1,description:l?.description??``,requiredPath:l?.requiredPath??[]},flags:r,errorResponse:e.errorResponse,summary:e.summary,description:e.description,deprecated:e.deprecated}})}function rr(e,t){let n=e.flag.split(/\s+/u);return{name:n[0]??e.flag,optionKey:e.optionKey,wireName:e.name,location:e.location,required:e.required,placeholder:n.length<=1?null:n.slice(1).join(` `),description:e.description,choices:e.choices??[],...t===void 0?{}:{contentType:t}}}function ir(e){if((e?.length??0)<=1)return[];let t=e?.map(({contentType:e})=>e)??[];return[{name:`--content-type`,optionKey:`contentType`,wireName:`Content-Type`,location:`body`,required:!1,placeholder:`<media-type>`,description:`Select the request content type; omit for ${t[0]}.`,choices:t}]}function ar(e){return e.flags.filter(({contentType:t})=>t===void 0||t===e.body.contentType)}function or(e,t){return!(t.root!==void 0&&!sr(e,t.root)||t.scope!==void 0&&t.scope!==`all`&&t.scope!==e.scope||t.mutates!==void 0&&t.mutates!==`any`&&t.mutates===`true`!==e.mutates||t.destructive!==void 0&&t.destructive!==`any`&&t.destructive===`true`!==e.destructive||t.intent!==void 0&&t.intent!==`all`&&t.intent!==e.intent||t.method!==void 0&&t.method!==`all`&&t.method!==e.method)}function sr(e,t){let n=rt(t);return n.length===0||rt(e.cli.path.at(0)??``)===n}function cr(e,t){let n=ar(e),r=n.filter(e=>e.required),i=n.filter(e=>!e.required);return[`cli: ${e.cli.command}`,`${e.method} ${e.path}`,`operationId: ${e.operationId}`,`resource: ${e.resource}`,`intent: ${e.intent}`,`scope: ${e.scope}`,`mutates: ${e.mutates}`,`destructive: ${e.destructive}`,`mcpTool: ${e.mcpTool??`unavailable (binary CLI operation)`}`,e.body.hasBody?`body: kind=${e.body.kind??`unknown`} required=${e.body.required} requiredPath=${e.body.requiredPath.join(`,`)}`:`body: none`,z(`required path flags`,r,`path`),z(`required query flags`,r,`query`),z(`required header flags`,r,`header`),z(`required body flags`,r,`body`),z(`optional path flags`,i,`path`),z(`optional query flags`,i,`query`),z(`optional header flags`,i,`header`),z(`optional body flags`,i,`body`),...mr(e,t),...lr(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
4
4
  `)}function lr(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}var ur=[`-id`,`-slug`,`-url`],dr=[`--id`,`--slug`,`--url`],fr=`--from-file "<path>"`;function pr(e,t,n=l().bin[0]){let r=nr(t,n),i=r.find(t=>t.operationId===e);return i===void 0?[]:mr(i,r)}function mr(e,t){return[`example: ${[e.cli.command,...gr(e),`--data`].join(` `)}`,...hr(e,t)]}function hr(e,t){return ar(e).flatMap(e=>{if(!e.required||!e.optionKey.endsWith(`Id`))return[];let n=`${e.optionKey.slice(0,-2)}Slug`,r=t.find(e=>e.method===`GET`&&/\/lookup(?:-exact)?$/u.test(e.path)&&e.flags.some(e=>e.optionKey===n)),i=r?.flags.find(e=>e.optionKey===n);if(r===void 0||i===void 0)return[];let a=`${r.cli.command} ${vr(i)} --data`,o=t.find(e=>e.method===`POST`&&e.path===r.path.replace(/-exact$/u,``)),s=o?.flags.find(e=>e.optionKey===`name`),c=`lookup: ${e.name} from a slug: ${a}`;return o===void 0||s===void 0?[c]:[c,`lookup: ${e.name} from a name or URL: ${o.cli.command} ${vr(s)} --data, then match.owner.${e.optionKey} when status is MATCHED`]})}function gr(e){let t=ar(e).filter(e=>e.required),n=(t.length>0?t:_r(e)).map(vr);return(e.body.required||e.body.requiredPath.length>0)&&!t.some(e=>e.location===`body`)?[...n,fr]:n}function _r(e){let t=new Set;tt(t,e.resource);for(let n of ur)for(let r of t){let t=e.flags.find(e=>e.name===`--${r}${n}`);if(t!==void 0)return[t]}for(let t of dr){let n=e.flags.find(e=>e.name===t);if(n!==void 0)return[n]}return[]}function vr(e){return e.placeholder===null?e.name:`${e.name} "${e.placeholder}"`}function z(e,t,n){let r=t.filter(e=>e.location===n);return`${e}: ${r.length===0?`none`:r.map(e=>e.name).join(` `)}`}function yr(e,t=l().bin){let[n=``,...r]=e.trim().split(/\s+/u);return(t.includes(n)?r:[n,...r]).join(` `)}var br=`dist/aventure-cli/command-catalog.compact.txt`,xr=` · `,Sr=`-`;function Cr(e=l().bin[0]){return j(wr(A(Et(import.meta.url)),e),br)}function wr(e,t){let n=e;for(;;){if(ft(j(n,`package.json`)))return n;let r=A(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function Tr(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function Er(e,t,n,r=l().bin[0]){let i=$n(e,t,r);if(!i.ok||i.data===null){R({mode:n},i);return}Or({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:Ar(i.data,kr(e.format,`lines`)),summary:`Generated operation matches`})}function Dr(e,t,n,r=l().bin[0]){let i=er(e,t,r);if(!i.ok||i.data===null){R({mode:n},i);return}Or({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:jr(i.data,kr(e.format,`usage`)),summary:`Generated operation detail`})}function Or(e){let t=e.mode,n=kr(e.opts.format,e.defaultFormat),r=e.opts.text===!0||e.opts.allFields===!0;if(e.opts.output===void 0&&r&&(n===`json`||n===`ndjson`)){R({mode:t},y(`--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 i=e.opts.output===void 0&&t===`text`&&`count`in e.data&&e.data.count.returned===0&&(r||e.opts.format===void 0||n===`text`)?`No generated operations matched.`:e.rendered,a=i.endsWith(`
@@ -8,7 +8,7 @@ import{$ as e,Bt as t,C as n,D as r,E as i,Ht as a,Rt as o,T as s,V as c,Y as l,
8
8
  `)}function jr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?JSON.stringify(e.operation):t===`lines`?Fr(e.operation):t===`compact`?Mr(e.operation):e.usage}function Mr(e){let t=Nr(e);return[e.cli.command,e.summary,t.length===0?Sr:t.join(` `)].join(xr)}function Nr(e){return e.flags.filter(t=>t.required&&(t.contentType===void 0||t.contentType===e.body.contentType)).map(e=>e.name)}function Pr(e){return e.map(e=>`${e.cli.command}\n ${Fr(e)}`).join(`
9
9
  `)}function Fr(e){let t=Nr(e);return[B(`operationId`,e.operationId),B(`scope`,e.scope),B(`mutates`,String(e.mutates)),B(`destructive`,String(e.destructive)),B(`intent`,e.intent),B(`resource`,e.resource),B(`cli`,e.cli.command),e.mcpTool===null?``:B(`mcpTool`,e.mcpTool),B(`method`,e.method),B(`path`,e.path),B(`auth`,e.auth),B(`flags`,[...new Set(e.flags.map(e=>e.name))].join(` `)),B(`requiredFlags`,t.join(` `)),B(`bodyKind`,e.body.kind??``),B(`bodyRequired`,String(e.body.required)),B(`summary`,e.summary)].filter(e=>e.length>0).join(` `)}function B(e,t){return t.length===0?``:`${e}=${JSON.stringify(t)}`}function Ir(e){return`count`in e?e.count:{returned:1}}function Lr(e,t,n=l().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, or ask a question`).description([`Show a command's full documentation offline. Select it by command path,`,"operationId, or `<METHOD> <path>`; `<command> --help` prints only its usage.","`help ask <question>` or `help --ask <question>` answers a platform question."].join(`
10
10
  `)).argument(`[command...]`,"command path, operationId, or METHOD and path, e.g. `help entities get`"),r.addOption(new Rr(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()});let i=Wr(t);i!==void 0&&r.option(`--ask <question>`,i.summary),O(r),r.action(async function(r){let a=this.optsWithGlobals();if(a.help&&r.length===0){this.outputHelp();return}if(!a.help&&i!==void 0&&a.ask!==void 0){let e=D(a);if(r.length>0){R({mode:e},y(`Use either a command path or --ask, not both.`));return}R({mode:e},await Jr(i,a.ask,a.environment,e));return}let o=qr(e,r),s=t.find(t=>o!==void 0&&qr(e,t.cliPath)===o);if(a.help||o!==void 0&&s===void 0){o===void 0&&this.error(`unknown command '${r.join(` `)}' (run \`${n} --help\` for the command tree)`),o.outputHelp();return}let c=s===void 0?Kr(r,t):x(`Resolved by command path`,{operationId:s.operationId});if(c.ok&&c.data?.command!==void 0&&this.error(`unknown command '${r.join(` `)}' (run \`${n} --help\` for the command tree)`),!c.ok||c.data===null){R({mode:D(a)},c);return}Dr({...a,...c.data},t,D(a,`text`),n)}),Ur(e,t,n)}var Rr=class extends S{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))}},zr=2,Br=6,Vr={formatHelp(e,n){let r=r=>t.prototype.formatHelp.call(this,e,Object.assign(Object.create(n),r));if(n.visibleCommands(e).length===0)return r({});let i=n.padWidth(e,n),a={padWidth:()=>i,visibleOptions:()=>[],showGlobalOptions:!1},o=r({...a,visibleCommands:()=>[]}),s=r({padWidth:()=>i,visibleCommands:()=>[]}).slice(o.length);return r(a)+s},visibleCommands(e){let n=t.prototype.visibleCommands.call(this,e);return e.parent===null?n.filter(e=>!Ge.has(e.name())):n},subcommandTerm(e){let n=t.prototype.subcommandTerm.call(this,e);return e.commands.length>0&&e.registeredArguments.length===0?`${n} <command>`:n},formatItem(e,n,r,i){let a=i.helpWidth??80,o=a-n-4;return r===``||o>=i.minWidthToWrap?t.prototype.formatItem.call(i,e,n,r,i):`${` `.repeat(zr)}${e}\n${Hr(r,a,i)}`}};function Hr(e,t,n){return n.boxWrap(e,t-Br).replace(/^/gmu,` `.repeat(Br))}function Ur(e,t,n){for(let r of t){let i=qr(e,r.cliPath);i!==void 0&&i.addHelpText(`after`,()=>{let e=i.createHelp();e.prepareContext({helpWidth:i.configureOutput().getOutHelpWidth?.()});let a=e.helpWidth??80,o=pr(r.operationId,t,n),[s,...c]=lr(r.errorResponse),l=c.map(t=>Hr(t.trimStart(),a,e).replace(/^ +/u,` `.repeat(zr))),u=s===void 0?[]:[``,s,...l];return`\n${[...o,...u].join(`
11
- `)}\n`})}}function Wr(e){let[t,...n]=e.filter(e=>{let[t,n,...r]=e.cliPath;return t===`help`&&n!==void 0&&r.length===0&&Yr(e)!==void 0});return n.length===0?t:void 0}var Gr='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function Kr(e,t){let[n,...r]=e,i=v.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return x(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=_(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return x(`Resolved by route template`,{operationId:s.operationId});let c=te({method:a,path:o});return!c.ok||c.data===null?y(c.summary,[...c.warnings,Gr]):x(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function qr(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}async function Jr(e,t,n,r){let i=Yr(e);if(i===void 0)return y(`The \`${e.cliPath.join(` `)}\` operation no longer takes a single required text body; run it directly instead of \`help --ask\`.`);n!==void 0&&(process.env.API_ENV=n);let a=await En(e,{[i.optionKey]:t});return a.ok?await le({method:e.method,path:se(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:He(r)?`json`:`auto`}):a}function Yr(e){if(e.requestBody?.length!==1||e.parameters.some(e=>e.required))return;let t=(e.requestBody[0]?.parameter??[]).filter(e=>e.required);return t.length===1&&t[0]?.schemaType===`string`?t[0]:void 0}function Xr(e,t){return e.parameters.filter(e=>e.required&&t[e.optionKey]===void 0).map(e=>e.flag)}var Zr=e=>typeof e==`string`&&e.trim()===``;function Qr(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(Zr):Zr(i)))continue;let a=Array.isArray(i)?i.filter(e=>!Zr(e)):[];if(a.length>0){e.setOptionValue(r,a);continue}n.has(r)&&e.error(`error: option '${t.flags}' requires a value`),e.setOptionValue(r,void 0)}}function $r(e){return e.split(` `)[0]??e}function ei(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 ti(e,t,n){let r=t.join(` `).trim();return r.length===0?x(`No positional text`,n):n[e.optionKey]===void 0?x(`Positional text parsed`,{...n,[e.optionKey]:r}):y(`Use either the positional argument or ${$r(e.flag)}, not both.`)}function ni(e,t,n){if(e.cliPath[0]!==`lookup`||!ri(n))return null;let r=e.parameters.filter(e=>t[e.optionKey]!==void 0).map(e=>`${e.name}=${String(t[e.optionKey])}`),i=`no record for ${r.length===0?`the given input`:r.join(`, `)}`;return n.ok?y(i):y(i,[],{httpStatus:n.httpStatus,problem:n.problem})}function ri(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}var ii=w({artifact:C().nullish(),group:C().nullish(),name:C().nullish(),revision:C().nullish(),time:T({offset:!0}).nullish(),version:C().nullish()}),ai=w({build:ii});function V(e,t){let[n,r]=e.filter(e=>e.role===t);if(n===void 0||r!==void 0)throw Error(`Generated composite CLI role '${t}' is incomplete`);return n}var oi=me([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),si=me([`RSA_OAEP_256_A256_GCM_V1`]),ci=w({clientLabel:C().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:oi.nullish(),encryptionAlgorithm:si.nullish(),encryptionPublicKey:C().min(344).max(12e3).nullish()}),li=32;async function ui(){let e=await Ot.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await Ot.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function di(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=fi(n,`wrapped key`,128,1024),s=fi(r,`nonce`,12,12),c=fi(i,`ciphertext`,1,65536),l=fi(a,`authentication tag`,16,16),u;try{u=await Ot.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!==li)throw Error(`broker credential used an invalid AES-256 key`);let e=await Ot.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 Ot.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new wt(`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 fi(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 pi=me([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),mi=me([`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`]),hi=w({approvedAt:T({offset:!0}).nullish(),clientLabel:C(),clientPlatform:oi,comparisonCode:C(),consumedAt:T({offset:!0}).nullish(),createdAt:T({offset:!0}),expiresAt:T({offset:!0}),id:pe(),intervalSeconds:he().int().min(1),keyReadyAt:T({offset:!0}).nullish(),status:pi,terminalAt:T({offset:!0}).nullish(),terminalReason:mi.nullish(),updatedAt:T({offset:!0})}),gi=w({algorithm:si,authenticationTag:C(),ciphertext:C(),nonce:C(),wrappedKey:C()}),_i=w({delivery:gi.nullish(),expiresAt:T({offset:!0}),status:pi,terminalReason:mi.nullish()}),vi=w({comparisonCode:C(),expiresAt:T({offset:!0}),id:pe(),intervalSeconds:he().int().min(1),pollSecret:C(),verificationUrl:C()}),H=[{command:`auth login`,role:`oauth`,summary:`Sign in through your browser`,description:`Sign in through your browser and save verified CLI access in the credential store.`,operationId:`getAuthProviderCatalog`,method:`GET`,path:`/v1/auth/providers`,bodyOption:[],localOption:[{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`},{optionKey:`providers`,flag:`--providers`,description:`Print the sign-in providers and CLI OAuth client, then exit without signing in.`}]},{command:`auth login`,role:`start`,summary:`Sign in with a browser-approved aVenture API key`,description:`Creates a short-lived browser approval request and returns its poll credential once.`,operationId:`createCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations`,bodyOption:[{name:`clientLabel`,optionKey:`clientLabel`,flag:`--client-label <client-label>`,required:!1,description:`Label for this CLI installation.`}],localOption:[{optionKey:`key`,flag:`--key`,description:`Sign in with a browser-approved aVenture API key instead of OAuth; the approval URL opens on any device.`},{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`}]},{command:`auth login`,role:`poll`,summary:`Poll CLI authorization`,description:`Returns pending state, a terminal state, or an encrypted one-time credential delivery.`,operationId:`pollCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/poll`,bodyOption:[],localOption:[]},{command:`auth login`,role:`acknowledge`,summary:`Acknowledge CLI credential delivery`,description:`Confirms the CLI stored the delivered API key in its credential store and clears transient delivery material.`,operationId:`acknowledgeCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/acknowledge`,bodyOption:[],localOption:[]},{command:`auth logout`,role:`revoke`,summary:`Sign out: revoke the API key and forget stored OAuth`,description:`Revokes the aVenture API key authenticating this request and returns its metadata so the CLI can confirm revocation before deleting its saved copy.`,operationId:`revokeCurrentApiKey`,method:`DELETE`,path:`/v1/auth/api-key`,bodyOption:[],localOption:[{optionKey:`forgetLocal`,flag:`--forget-local`,description:`Delete the saved key even when revocation cannot be confirmed.`}]}],yi=V(H,`start`),bi=V(H,`poll`),xi=V(H,`acknowledge`),Si=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${ye(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=Oi(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},Ci=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${E(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function wi(e){let t=await ae(ge(b()),{method:yi.method,path:d(yi.path,{},yi.operationId),headers:{},contentType:`application/json`,body:e},vi);if(!t.ok)throw new Si(`start`,t.problem);return ki(t.data)}async function Ti(e,t){let n=m(bi.operationId),r=await ae(ge(b()),{method:bi.method,path:d(bi.path,{cliAuthorizationId:e},bi.operationId),headers:{[n]:t}},_i);if(!r.ok)throw new Si(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:Di(r.headers[`retry-after`])}}async function Ei(e,t){let n=m(xi.operationId),r;try{r=await ae(ge(b()),{method:xi.method,path:d(xi.path,{cliAuthorizationId:e},xi.operationId),headers:{[n]:t}},hi)}catch(e){throw new Ci(`acknowledge`,e,[t])}if(!r.ok)throw new Si(`acknowledge`,r.problem,[t]);return r.data}function Di(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function Oi(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function ki(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())})`},[Tt.custom]:{enumerable:!1,value:a}})}async function Ai(e){let t=await ji(e.credential.secret);if(t.state!==`verified`||e.activation!==`active`)return{stored:e,verification:t};try{return{stored:await _e(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`),verification:t}}catch(n){return{stored:e,verification:{state:`unavailable`,summary:`${t.summary}, but the cached metadata could not be updated — ${E(n,[e.credential.secret])}`}}}}async function ji(e){let t=ge(b()),n;try{n=await ae(t,{method:`GET`,path:se(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},Re)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${E(t,[e])}`}}return n.ok?n.data.status===`ACTIVE`?{state:`verified`,summary:`API key verified by aVenture sign-in`,apiKey:n.data}:{state:`invalid`,summary:`API key is not active`}:{state:n.problem.status===401||n.problem.status===403?`invalid`:`unavailable`,summary:`identity verification: ${ye(n.problem,[e])}`}}var Mi=V(H,`revoke`);async function Ni(e){let t;try{t=Be(b().host)}catch(e){return y(`auth logout: invalid API host — ${E(e)}`)}let n=await Pi(t),r=await Li(t,e),i=n.state===`failed`?[`OAuth credential could not be removed — ${n.summary}`]:n.state===`forgotten`&&!n.revoked?[`OAuth refresh token was not revoked remotely — ${n.summary??`no revocation endpoint`}`]:[],a={host:t,revoked:!1,forgotten:!1,oauth:n};return r===null?n.state===`missing`?x(`No CLI credential is stored for this API host.`,a):n.state===`failed`?{...y(`auth logout: ${i[0]}`),data:a}:x(n.revoked?`OAuth credential revoked remotely and removed locally.`:`OAuth credential removed locally.`,a,{warnings:i}):{...r,data:{...r.data??a,oauth:n},warnings:[...r.warnings,...i]}}async function Pi(e){let t=await Me(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await Ii(t.stored):{revoked:!1};try{await Ce(e)}catch(e){return{state:`failed`,summary:E(e)}}return{state:`forgotten`,...n}}async function Fi(e){let t=Reflect.get(await ct(e),`revocation_endpoint`);return typeof t==`string`?De(t,`revocation endpoint`,!0):void 0}async function Ii(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await Fi(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:Ie(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:E(e,je(n))}}}async function Li(e,t){let n;try{n=await xe(e)}catch(e){return y(`auth logout: stored credential could not be read — ${E(e)}`)}if(n.state===`unavailable`)return{...y(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await Ri(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!t.forgetLocal)return{...y(`auth logout: remote revocation was not confirmed; local credential preserved — ${i.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:zi(r,!1,!1)};try{await we(r.host)}catch(e){return{...y(`auth logout: local credential removal failed — ${E(e,[r.credential.secret])}`,[a?"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:zi(r,a,!1)}}return x(a?`API key revoked remotely and removed locally.`:o?`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.`,zi(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function Ri(e){let t=ge(b());try{let n=await ae(t,{method:Mi.method,path:d(Mi.path,{},Mi.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},Re);return n.ok?n.data.id!==e.credential.apiKey.id||n.data.subject!==e.credential.apiKey.subject?{outcome:`unconfirmed`,summary:`remote response did not match the stored API key identity`}:n.data.status===`REVOKED`?{outcome:`revoked`,summary:`remote key revocation confirmed`}:{outcome:`unconfirmed`,summary:`remote response did not confirm REVOKED status`}:{outcome:n.problem.status===401&&n.problem.type!==`about:blank`?`rejected`:`unconfirmed`,summary:ye(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:E(t,[e.credential.secret])}}}function zi(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var Bi=`RSA_OAEP_256_A256_GCM_V1`,Vi=1,Hi=30,U=l().bin[0],Ui=`The local record remains pending and unavailable to ordinary commands. Re-run \`${U} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Wi(e){if(!Ct.isTTY)return y(`${U} auth login --key requires an interactive TTY on stdin`,[`For non-interactive automation, inject AUTH_TOKEN through the environment.`]);let t,n;try{let e=b().host;t=Be(e),n=ke(e)}catch(e){return y(`auth login --key: invalid environment configuration — ${E(e)}`)}for(;;){let e;try{e=await ze(t)}catch(e){return y(`auth login --key: credential storage could not be inspected — ${E(e)}`)}if(e.state===`unavailable`)return y(`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`){e.keyringFailure!==void 0&&P.write(Se(e.keyringFailure));break}let n=await Gi(e.stored);if(n!==null)return n}let r;try{r=await ui()}catch(e){return y(`auth login --key: ephemeral encryption key could not be created — ${E(e)}`)}let i=ci.safeParse({clientLabel:e.clientLabel?.trim()||(At().trim()||U).slice(0,120),clientPlatform:Yi(),encryptionAlgorithm:Bi,encryptionPublicKey:r.publicKey});if(!i.success)return y(`auth login --key: ${fe(i.error)}`);let a;try{a=await wi(i.data)}catch(e){return y(`auth login --key: could not start browser authorization — ${E(e)}`)}let o;try{o=be(a,n)}catch(e){return y(`auth login --key: unsafe browser authorization URL rejected — ${E(e)}`)}if(!Ji(await ve(a,n,{noBrowser:e.noBrowser}),a,o))return y(`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:[o]});let s;try{s=await qi(a)}catch(e){return y(`auth login --key: authorization did not complete — ${E(e)}`,[],{references:[o]})}if(s.algorithm!==Bi)return y(`auth login --key: broker selected an unsupported encryption algorithm`);let c;try{c=await di(r.privateKey,s)}catch(e){return y(`auth login --key: encrypted credential could not be opened — ${E(e)}`)}let l=await ji(c);if(l.state!==`verified`)return y(`auth login --key: decrypted credential was neither stored nor acknowledged — ${l.summary}`);let u;try{u=await _e(t,{apiKey:l.apiKey,secret:c},`pending`)}catch(e){return y(`auth login --key: credential could not be durably stored — ${E(e)}`)}let d;try{d=await Ki(a)}catch(e){return W(u,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${E(e,[a.pollSecret])}`,Ui)}if(d.status!==`CONSUMED`)return W(u,!0,`auth login --key: broker returned ${d.status} after acknowledgment`,Ui);let f=await ji(c);if(f.state!==`verified`||!$i(f.apiKey,u.credential.apiKey))return W(u,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${f.summary}`,Ui);try{let e=await _e(t,{apiKey:f.apiKey,secret:c},`active`);return x(`API key stored; authenticated identity and broker acknowledgment verified.`,Qi(e,!0),{ids:[e.credential.apiKey.id]})}catch(e){return W(u,!0,`auth login --key: remote acknowledgment succeeded, but local activation could not be confirmed — ${E(e)}`,Ui)}}async function Gi(e){let t=await ji(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?x(`API key is already stored and its authenticated identity was verified.`,Qi(e,!0),{ids:[e.credential.apiKey.id]}):W(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${U} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&$i(t.apiKey,e.credential.apiKey))try{let n=await _e(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return x(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,Qi(n,!0),{ids:[n.credential.apiKey.id]})}catch(t){return W(e,!0,`auth login --key: credential is valid but could not be promoted locally — ${E(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${U} auth login --key\` to retry local activation; it will recover the pending credential automatically.`)}if(t.state===`unavailable`||t.state===`verified`&&!e.credential.apiKey.expiresAt)return W(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 \`${U} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await Ri(e);if(n.outcome===`unconfirmed`)return W(e,!1,`auth login --key: a prior credential is durably stored but broker acknowledgment was not confirmed`,`Remote revocation of the stale pending key was not confirmed — ${n.summary}. Retry when the API is reachable.`);try{await we(e.host)}catch(t){return W(e,!1,`auth login --key: stale pending credential could not be removed — ${E(t,[e.credential.secret])}`)}return P.write(n.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
11
+ `)}\n`})}}function Wr(e){let[t,...n]=e.filter(e=>{let[t,n,...r]=e.cliPath;return t===`help`&&n!==void 0&&r.length===0&&Yr(e)!==void 0});return n.length===0?t:void 0}var Gr='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function Kr(e,t){let[n,...r]=e,i=v.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return x(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=_(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return x(`Resolved by route template`,{operationId:s.operationId});let c=te({method:a,path:o});return!c.ok||c.data===null?y(c.summary,[...c.warnings,Gr]):x(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function qr(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}async function Jr(e,t,n,r){let i=Yr(e);if(i===void 0)return y(`The \`${e.cliPath.join(` `)}\` operation no longer takes a single required text body; run it directly instead of \`help --ask\`.`);n!==void 0&&(process.env.API_ENV=n);let a=await En(e,{[i.optionKey]:t});return a.ok?await le({method:e.method,path:se(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:He(r)?`json`:`auto`}):a}function Yr(e){if(e.requestBody?.length!==1||e.parameters.some(e=>e.required))return;let t=(e.requestBody[0]?.parameter??[]).filter(e=>e.required);return t.length===1&&t[0]?.schemaType===`string`?t[0]:void 0}function Xr(e,t){return e.parameters.filter(e=>e.required&&t[e.optionKey]===void 0).map(e=>e.flag)}var Zr=e=>typeof e==`string`&&e.trim()===``;function Qr(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(Zr):Zr(i)))continue;let a=Array.isArray(i)?i.filter(e=>!Zr(e)):[];if(a.length>0){e.setOptionValue(r,a);continue}n.has(r)&&e.error(`error: option '${t.flags}' requires a value`),e.setOptionValue(r,void 0)}}function $r(e){return e.split(` `)[0]??e}function ei(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 ti(e,t,n){let r=t.join(` `).trim();return r.length===0?x(`No positional text`,n):n[e.optionKey]===void 0?x(`Positional text parsed`,{...n,[e.optionKey]:r}):y(`Use either the positional argument or ${$r(e.flag)}, not both.`)}function ni(e,t,n){if(e.cliPath[0]!==`lookup`||!ri(n))return null;let r=e.parameters.filter(e=>t[e.optionKey]!==void 0).map(e=>`${e.name}=${String(t[e.optionKey])}`),i=`no record for ${r.length===0?`the given input`:r.join(`, `)}`;return n.ok?y(i):y(i,[],{httpStatus:n.httpStatus,problem:n.problem})}function ri(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}var ii=w({artifact:C().nullish(),group:C().nullish(),name:C().nullish(),revision:C().nullish(),time:T({offset:!0}).nullish(),version:C().nullish()}),ai=w({build:ii});function V(e,t){let[n,r]=e.filter(e=>e.role===t);if(n===void 0||r!==void 0)throw Error(`Generated composite CLI role '${t}' is incomplete`);return n}var oi=me([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),si=me([`RSA_OAEP_256_A256_GCM_V1`]),ci=w({clientLabel:C().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:oi.nullish(),encryptionAlgorithm:si.nullish(),encryptionPublicKey:C().min(344).max(12e3).nullish()}),li=32;async function ui(){let e=await Ot.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await Ot.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function di(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=fi(n,`wrapped key`,128,1024),s=fi(r,`nonce`,12,12),c=fi(i,`ciphertext`,1,65536),l=fi(a,`authentication tag`,16,16),u;try{u=await Ot.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!==li)throw Error(`broker credential used an invalid AES-256 key`);let e=await Ot.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 Ot.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new wt(`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 fi(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 pi=me([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),mi=me([`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`]),hi=w({approvedAt:T({offset:!0}).nullish(),clientLabel:C(),clientPlatform:oi,comparisonCode:C(),consumedAt:T({offset:!0}).nullish(),createdAt:T({offset:!0}),expiresAt:T({offset:!0}),id:pe(),intervalSeconds:he().int().min(1),keyReadyAt:T({offset:!0}).nullish(),status:pi,terminalAt:T({offset:!0}).nullish(),terminalReason:mi.nullish(),updatedAt:T({offset:!0})}),gi=w({algorithm:si,authenticationTag:C(),ciphertext:C(),nonce:C(),wrappedKey:C()}),_i=w({delivery:gi.nullish(),expiresAt:T({offset:!0}),status:pi,terminalReason:mi.nullish()}),vi=w({comparisonCode:C(),expiresAt:T({offset:!0}),id:pe(),intervalSeconds:he().int().min(1),pollSecret:C(),verificationUrl:C()}),H=[{command:`auth login`,role:`oauth`,summary:`Sign In Through Your Browser`,description:`Sign in through your browser and save verified CLI access in the credential store.`,operationId:`getAuthProviderCatalog`,method:`GET`,path:`/v1/auth/providers`,bodyOption:[],localOption:[{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`},{optionKey:`providers`,flag:`--providers`,description:`Print the sign-in providers and CLI OAuth client, then exit without signing in.`}]},{command:`auth login`,role:`start`,summary:`Sign In With a Browser-Approved aVenture API Key`,description:`Creates a short-lived browser approval request and returns its poll credential once.`,operationId:`createCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations`,bodyOption:[{name:`clientLabel`,optionKey:`clientLabel`,flag:`--client-label <client-label>`,required:!1,description:`Label for this CLI installation.`}],localOption:[{optionKey:`key`,flag:`--key`,description:`Sign in with a browser-approved aVenture API key instead of OAuth; the approval URL opens on any device.`},{optionKey:`browser`,flag:`--no-browser`,description:`Print the sign-in URL without opening a browser.`}]},{command:`auth login`,role:`poll`,summary:`Poll CLI Authorization`,description:`Returns pending state, a terminal state, or an encrypted one-time credential delivery.`,operationId:`pollCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/poll`,bodyOption:[],localOption:[]},{command:`auth login`,role:`acknowledge`,summary:`Acknowledge CLI Credential Delivery`,description:`Confirms the CLI stored the delivered API key in its credential store and clears transient delivery material.`,operationId:`acknowledgeCliAuthorization`,method:`POST`,path:`/v1/auth/cli-authorizations/{cliAuthorizationId}/acknowledge`,bodyOption:[],localOption:[]},{command:`auth logout`,role:`revoke`,summary:`Sign Out: Revoke the API Key and Forget Stored OAuth`,description:`Revokes the aVenture API key authenticating this request and returns its metadata so the CLI can confirm revocation before deleting its saved copy.`,operationId:`revokeCurrentApiKey`,method:`DELETE`,path:`/v1/auth/api-key`,bodyOption:[],localOption:[{optionKey:`forgetLocal`,flag:`--forget-local`,description:`Delete the saved key even when revocation cannot be confirmed.`}]}],yi=V(H,`start`),bi=V(H,`poll`),xi=V(H,`acknowledge`),Si=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${ye(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=Oi(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},Ci=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${E(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function wi(e){let t=await ae(ge(b()),{method:yi.method,path:d(yi.path,{},yi.operationId),headers:{},contentType:`application/json`,body:e},vi);if(!t.ok)throw new Si(`start`,t.problem);return ki(t.data)}async function Ti(e,t){let n=m(bi.operationId),r=await ae(ge(b()),{method:bi.method,path:d(bi.path,{cliAuthorizationId:e},bi.operationId),headers:{[n]:t}},_i);if(!r.ok)throw new Si(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:Di(r.headers[`retry-after`])}}async function Ei(e,t){let n=m(xi.operationId),r;try{r=await ae(ge(b()),{method:xi.method,path:d(xi.path,{cliAuthorizationId:e},xi.operationId),headers:{[n]:t}},hi)}catch(e){throw new Ci(`acknowledge`,e,[t])}if(!r.ok)throw new Si(`acknowledge`,r.problem,[t]);return r.data}function Di(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function Oi(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function ki(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())})`},[Tt.custom]:{enumerable:!1,value:a}})}async function Ai(e){let t=await ji(e.credential.secret);if(t.state!==`verified`||e.activation!==`active`)return{stored:e,verification:t};try{return{stored:await _e(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`),verification:t}}catch(n){return{stored:e,verification:{state:`unavailable`,summary:`${t.summary}, but the cached metadata could not be updated — ${E(n,[e.credential.secret])}`}}}}async function ji(e){let t=ge(b()),n;try{n=await ae(t,{method:`GET`,path:se(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},Re)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${E(t,[e])}`}}return n.ok?n.data.status===`ACTIVE`?{state:`verified`,summary:`API key verified by aVenture sign-in`,apiKey:n.data}:{state:`invalid`,summary:`API key is not active`}:{state:n.problem.status===401||n.problem.status===403?`invalid`:`unavailable`,summary:`identity verification: ${ye(n.problem,[e])}`}}var Mi=V(H,`revoke`);async function Ni(e){let t;try{t=Be(b().host)}catch(e){return y(`auth logout: invalid API host — ${E(e)}`)}let n=await Pi(t),r=await Li(t,e),i=n.state===`failed`?[`OAuth credential could not be removed — ${n.summary}`]:n.state===`forgotten`&&!n.revoked?[`OAuth refresh token was not revoked remotely — ${n.summary??`no revocation endpoint`}`]:[],a={host:t,revoked:!1,forgotten:!1,oauth:n};return r===null?n.state===`missing`?x(`No CLI credential is stored for this API host.`,a):n.state===`failed`?{...y(`auth logout: ${i[0]}`),data:a}:x(n.revoked?`OAuth credential revoked remotely and removed locally.`:`OAuth credential removed locally.`,a,{warnings:i}):{...r,data:{...r.data??a,oauth:n},warnings:[...r.warnings,...i]}}async function Pi(e){let t=await Me(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await Ii(t.stored):{revoked:!1};try{await Ce(e)}catch(e){return{state:`failed`,summary:E(e)}}return{state:`forgotten`,...n}}async function Fi(e){let t=Reflect.get(await ct(e),`revocation_endpoint`);return typeof t==`string`?De(t,`revocation endpoint`,!0):void 0}async function Ii(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await Fi(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:Ie(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:E(e,je(n))}}}async function Li(e,t){let n;try{n=await xe(e)}catch(e){return y(`auth logout: stored credential could not be read — ${E(e)}`)}if(n.state===`unavailable`)return{...y(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await Ri(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!t.forgetLocal)return{...y(`auth logout: remote revocation was not confirmed; local credential preserved — ${i.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:zi(r,!1,!1)};try{await we(r.host)}catch(e){return{...y(`auth logout: local credential removal failed — ${E(e,[r.credential.secret])}`,[a?"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:zi(r,a,!1)}}return x(a?`API key revoked remotely and removed locally.`:o?`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.`,zi(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function Ri(e){let t=ge(b());try{let n=await ae(t,{method:Mi.method,path:d(Mi.path,{},Mi.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},Re);return n.ok?n.data.id!==e.credential.apiKey.id||n.data.subject!==e.credential.apiKey.subject?{outcome:`unconfirmed`,summary:`remote response did not match the stored API key identity`}:n.data.status===`REVOKED`?{outcome:`revoked`,summary:`remote key revocation confirmed`}:{outcome:`unconfirmed`,summary:`remote response did not confirm REVOKED status`}:{outcome:n.problem.status===401&&n.problem.type!==`about:blank`?`rejected`:`unconfirmed`,summary:ye(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:E(t,[e.credential.secret])}}}function zi(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var Bi=`RSA_OAEP_256_A256_GCM_V1`,Vi=1,Hi=30,U=l().bin[0],Ui=`The local record remains pending and unavailable to ordinary commands. Re-run \`${U} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Wi(e){if(!Ct.isTTY)return y(`${U} auth login --key requires an interactive TTY on stdin`,[`For non-interactive automation, inject AUTH_TOKEN through the environment.`]);let t,n;try{let e=b().host;t=Be(e),n=ke(e)}catch(e){return y(`auth login --key: invalid environment configuration — ${E(e)}`)}for(;;){let e;try{e=await ze(t)}catch(e){return y(`auth login --key: credential storage could not be inspected — ${E(e)}`)}if(e.state===`unavailable`)return y(`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`){e.keyringFailure!==void 0&&P.write(Se(e.keyringFailure));break}let n=await Gi(e.stored);if(n!==null)return n}let r;try{r=await ui()}catch(e){return y(`auth login --key: ephemeral encryption key could not be created — ${E(e)}`)}let i=ci.safeParse({clientLabel:e.clientLabel?.trim()||(At().trim()||U).slice(0,120),clientPlatform:Yi(),encryptionAlgorithm:Bi,encryptionPublicKey:r.publicKey});if(!i.success)return y(`auth login --key: ${fe(i.error)}`);let a;try{a=await wi(i.data)}catch(e){return y(`auth login --key: could not start browser authorization — ${E(e)}`)}let o;try{o=be(a,n)}catch(e){return y(`auth login --key: unsafe browser authorization URL rejected — ${E(e)}`)}if(!Ji(await ve(a,n,{noBrowser:e.noBrowser}),a,o))return y(`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:[o]});let s;try{s=await qi(a)}catch(e){return y(`auth login --key: authorization did not complete — ${E(e)}`,[],{references:[o]})}if(s.algorithm!==Bi)return y(`auth login --key: broker selected an unsupported encryption algorithm`);let c;try{c=await di(r.privateKey,s)}catch(e){return y(`auth login --key: encrypted credential could not be opened — ${E(e)}`)}let l=await ji(c);if(l.state!==`verified`)return y(`auth login --key: decrypted credential was neither stored nor acknowledged — ${l.summary}`);let u;try{u=await _e(t,{apiKey:l.apiKey,secret:c},`pending`)}catch(e){return y(`auth login --key: credential could not be durably stored — ${E(e)}`)}let d;try{d=await Ki(a)}catch(e){return W(u,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${E(e,[a.pollSecret])}`,Ui)}if(d.status!==`CONSUMED`)return W(u,!0,`auth login --key: broker returned ${d.status} after acknowledgment`,Ui);let f=await ji(c);if(f.state!==`verified`||!$i(f.apiKey,u.credential.apiKey))return W(u,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${f.summary}`,Ui);try{let e=await _e(t,{apiKey:f.apiKey,secret:c},`active`);return x(`API key stored; authenticated identity and broker acknowledgment verified.`,Qi(e,!0),{ids:[e.credential.apiKey.id]})}catch(e){return W(u,!0,`auth login --key: remote acknowledgment succeeded, but local activation could not be confirmed — ${E(e)}`,Ui)}}async function Gi(e){let t=await ji(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?x(`API key is already stored and its authenticated identity was verified.`,Qi(e,!0),{ids:[e.credential.apiKey.id]}):W(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${U} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&$i(t.apiKey,e.credential.apiKey))try{let n=await _e(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return x(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,Qi(n,!0),{ids:[n.credential.apiKey.id]})}catch(t){return W(e,!0,`auth login --key: credential is valid but could not be promoted locally — ${E(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${U} auth login --key\` to retry local activation; it will recover the pending credential automatically.`)}if(t.state===`unavailable`||t.state===`verified`&&!e.credential.apiKey.expiresAt)return W(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 \`${U} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await Ri(e);if(n.outcome===`unconfirmed`)return W(e,!1,`auth login --key: a prior credential is durably stored but broker acknowledgment was not confirmed`,`Remote revocation of the stale pending key was not confirmed — ${n.summary}. Retry when the API is reachable.`);try{await we(e.host)}catch(t){return W(e,!1,`auth login --key: stale pending credential could not be removed — ${E(t,[e.credential.secret])}`)}return P.write(n.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
12
12
  `:`Cleared a stale pending CLI credential whose remote key can no longer authenticate; starting a fresh browser authorization.
13
13
  `),null}async function Ki(e){let t=new Date(e.expiresAt).getTime(),n=Xi(e.intervalSeconds);for(;;)try{return await Ei(e.id,e.pollSecret)}catch(e){if(e instanceof Si){if(!e.retryable)throw e;n=Xi(e.retryAfterSeconds??n)}else if(!(e instanceof Ci))throw e;if(Date.now()>=t)throw e;P.write(`Broker acknowledgment was interrupted; retrying.
14
14
  `),await Zi(n,t)}}async function qi(e){let t=new Date(e.expiresAt).getTime(),n=Xi(e.intervalSeconds),r;for(P.write(`Waiting for browser approval...
@@ -25,7 +25,7 @@ import{$ as e,Bt as t,C as n,D as r,E as i,Ht as a,Rt as o,T as s,V as c,Y as l,
25
25
  `).slice(-3).join(` | `);return y(`npm ${e.join(` `)} exited ${a.status}`,[t||`no stderr`])}return x(`npm ok`,a.stdout??``)}function $a(e,t,n){let r=e===null?``:` --prefix ${JSON.stringify(e.installPrefix)}`;return[`Finish by hand: npm uninstall -g${r} ${oe}`,`then: npm install -g${r} ${t}@${n} --@aventurevc:registry=`]}function eo(e,t,n){let r;try{let n=l(j(e,`lib`,`node_modules`,...t.split(`/`),`package.json`));r=j(e,`bin`,n.bin[0])}catch(e){return y(`updated ${t} verification failed: ${ao(e)}`,[`invalid_package_metadata`])}let i=lt(process.execPath,[r,`--version`],{encoding:`utf8`});if(i.error)return y(`updated ${t} verification failed: ${i.error.message}`,[`spawn_error`]);let a=(i.stdout??``).trim();if(i.status!==0||a!==n){let e=(i.stderr??``).trim().split(`
26
26
  `).slice(-3).join(` | `);return y(`updated ${t} verification expected ${n} but active bin reported ${a||`empty output`}`,[e||`active bin: ${r}`])}return x(`active CLI version verified`,a)}function to(e){let t=`${M}lib${M}node_modules${M}${e.name.replace(`/`,M)}`,n=e.packageRoot.lastIndexOf(t);return n<0?null:{installPrefix:e.packageRoot.slice(0,n)}}function no(e,t){if(e.name!==`@aventurevc/mcp-server`)return{backup:[],backupDirectory:null};if(t===null)throw Error(`the running MCP package is not in a verifiable global npm prefix`);if(!e.entryPath.startsWith(`${e.packageRoot}${M}`))throw Error(`the running CLI entry is outside the MCP package root`);let n=e.bin.filter(e=>e===`aventure`||e===`aventure-cli`).flatMap(n=>{let r=j(t.installPrefix,`bin`,n),i=pt(r,{throwIfNoEntry:!1});if(i===void 0)return[];if(!i.isSymbolicLink())throw Error(`${r} is not a symlink`);let a;try{a=vt(r)}catch(e){throw Error(`${r} has a missing target`,{cause:e})}if(a!==e.entryPath)throw Error(`${r} is not owned by the running MCP CLI`);return{binPath:r,linkTarget:_t(r)}});if(n.length===0)return{backup:[],backupDirectory:null};let r=ht(j(t.installPrefix,`bin`,`.aventure-cli-update-`)),i=n.map(({binPath:e,linkTarget:t})=>({backupPath:j(r,ut(e)),binPath:e,linkTarget:t})),a=[];try{for(let e of i)if(yt(e.binPath,e.backupPath),a.push(e),_t(e.backupPath)!==e.linkTarget)throw Error(`${e.binPath} changed ownership while preparing the update`)}catch(e){let t=ro({backup:a,backupDirectory:r},null);throw Error(`could not displace verified MCP CLI bins${t===null?``:`; restoration failed: ${t}`}`,{cause:e})}return{backup:a,backupDirectory:r}}function ro(e,t){let n=[];for(let r of e.backup.toReversed())try{let e=pt(r.binPath,{throwIfNoEntry:!1});if(e!==void 0){if(!e.isSymbolicLink())throw Error(`${r.binPath} is not a symlink`);let n=j(A(r.binPath),_t(r.binPath));if(t===null||n!==t&&!n.startsWith(`${t}${M}`))throw Error(`${r.binPath} is not owned by the standalone CLI package`);xt(r.binPath)}yt(r.backupPath,r.binPath)}catch(e){n.push(ao(e))}if(e.backupDirectory!==null)try{bt(e.backupDirectory)}catch(e){n.push(ao(e))}return n.length===0?null:n.join(`; `)}function io(e){let t=[];for(let n of e.backup)try{xt(n.backupPath)}catch(e){t.push(ao(e))}if(e.backupDirectory!==null)try{bt(e.backupDirectory)}catch(e){t.push(ao(e))}return t.length===0?null:t.join(`; `)}function ao(e){return e instanceof Error?e.message:String(e)}function oo(){try{return Ma()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var so=[{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 its generated status operation`},{name:`auth`,purpose:`which credential scope materialized locally, never the secret`},{name:`catalog`,purpose:`this CLI knows every operation the API serves`}],co=`operationFingerprint`;function lo(e,t=l().bin[0]){O(e.command(`doctor`).summary(`One-call selftest: CLI version, schemas, API host, auth scope, command catalog`).description(["Run every environment check in one call and report `{ ok, check: [...] }`:",...so.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.`,"--json always carries the report at `.data`; --data prints the report directly when",`every check passes and the result envelope when one fails, like every other command.`].join(`
27
27
  `))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),R({mode:D(e)},await uo(t))})}async function uo(e){let t=po(),n=mo(e),[r,i]=await Promise.all([ho(e),go(t,e)]),a=[n.check,r,i.check,await vo(e),wo(t,i.servedFingerprint,n.upgradeAvailable,e)],o={pass:fo(a,`pass`),fail:fo(a,`fail`),skip:fo(a,`skip`)},s=a.filter(e=>e.status===`fail`).map(e=>e.message),c={ok:s.length===0,check:a},l=[`doctor: ${o.pass} pass, ${o.fail} fail, ${o.skip} skip`,...a.map(e=>` ${e.name} ${e.status} — ${e.message}`)].join(`
28
- `);return c.ok?x(l,c,{counts:o}):{...y(l,s,{counts:o}),data:c}}function fo(e,t){return e.filter(e=>e.status===t).length}function q(e,t,n){return{name:e,status:t,message:n}}function po(){return k.find(e=>e.intent===`status`&&e.resource===`status`)}function mo(e){let t=l(),n=Za(t,`check`);if(!n.ok||n.data===null)return{check:q(`cli-version`,`skip`,`Could not compare ${t.version} against the registry (${n.summary}); rerun \`${e} update\` with registry access.`),upgradeAvailable:null};let{targetPackage:r,currentVersion:i,latestVersion:a,upgradeAvailable:o}=n.data;return{check:o?q(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):q(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function ho(e){try{let{EntityDetailSchema:e}=await import(`./detail-D9M8QZSE.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return q(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return q(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${E(t)}.`)}}async function go(e,t){if(e===void 0)return{check:q(`api-host`,`skip`,`No status operation resolved from the generated catalog; fix the catalog check first.`),servedFingerprint:null};let n;try{n=b().host}catch(e){return{check:q(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${E(e)}.`),servedFingerprint:null}}let r=await le({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>y(E(e)));return r.ok?{check:q(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:_o(r.data)}:{check:q(`api-host`,`fail`,r.httpStatus===401?`Replace or unset the credential ${n} rejected, or run \`${t} auth login\`, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} returned ${r.summary}.`:`Point the CLI at a reachable API host with \`--environment <name>\` or API_URL, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} at ${n} returned ${r.summary}.`),servedFingerprint:null}}function _o(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[co];return typeof n==`string`&&n.length>0?n:null}async function vo(e){let t=Oe(),[n,r]=await Promise.all([yo(),bo()]);if(r.state===`unavailable`&&r.cause===`environment`)return q(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t.present;return!i&&n.state===`invalid`?q(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`):!i&&n.state===`found`&&Te(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0?q(`auth`,`fail`,`Saved OAuth access token is expired without a refresh token; run \`${e} auth login\` to sign in again.`):!i&&r.state!==`found`&&n.state===`unavailable`?q(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${u.authToken} through the environment — ${n.summary}.`):i||n.state===`found`||r.state===`found`?q(`auth`,`pass`,`Credential source available: ${xo(t,n,r)}.`):r.state===`unavailable`?q(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${u.authToken} through the environment — ${r.summary}.`):q(`auth`,`fail`,`Run \`${e} auth login\` for OAuth or \`${e} auth login --key\` for an API key. For non-interactive use, set ${u.authToken} in the environment.`)}async function yo(){let e;try{e=Ne(b().host)}catch(e){return{state:`unavailable`,summary:E(e)}}return await Pe(e)}async function bo(){let e;try{e=Be(b().host)}catch(e){return{state:`unavailable`,summary:E(e),cause:`environment`}}try{return await ze(e)}catch(e){return{state:`unavailable`,summary:E(e),cause:`storage`}}}function xo(e,t,n){return[wa(e),`oauth=${Co(t)}`,`api-key=${So(n)}`].join(` `)}function So(e){if(e.state!==`found`)return e.state===`missing`?`unset`:`unavailable`;let t=Be(b().host);return`${e.stored.activation}${la(t,e)}`}function Co(e){switch(e.state){case`found`:return Te(e.stored.credential)?`expired`:`stored`;case`missing`:return`unset`;case`invalid`:return`invalid`;case`unavailable`:return`unavailable`;default:throw Error(`Unsupported OAuth credential state`)}}function wo(e,t,n,r){let i=k.length;if(e===void 0)return q(`catalog`,`fail`,`Regenerate the command catalog with \`make mcp-generate-contracts\` and reinstall: none of its ${i} operations is the status operation.`);if(t===null)return q(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${Xe}.`);if(t===`4ff75f56bd34c7c5`)return q(`catalog`,`pass`,`${i} generated operations match the set the API serves (${Xe}).`);let a=`This catalog describes a different operation set than the API serves (${Xe} vs ${t})`;return n===!0?q(`catalog`,`fail`,`${a}: run \`${r} update\`.`):q(`catalog`,`skip`,n===!1?`${a}, 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.`:`${a}, and the registry did not answer, so it is unknown whether a newer release describes it: rerun \`${r} update\` with registry access.`)}var To=V(H,`oauth`),Eo=[V(H,`start`),V(H,`poll`),V(H,`acknowledge`)],Do=V(H,`revoke`);function Oo(e,t=l().bin[0]){let n=Mo(e);lo(n,t);let r=[`${To.description} Default method: OAuth in your browser.`,`With --key: ${Eo.map(({description:e})=>e).join(` `)}`].join(`
28
+ `);return c.ok?x(l,c,{counts:o}):{...y(l,s,{counts:o}),data:c}}function fo(e,t){return e.filter(e=>e.status===t).length}function q(e,t,n){return{name:e,status:t,message:n}}function po(){return k.find(e=>e.intent===`status`&&e.resource===`status`)}function mo(e){let t=l(),n=Za(t,`check`);if(!n.ok||n.data===null)return{check:q(`cli-version`,`skip`,`Could not compare ${t.version} against the registry (${n.summary}); rerun \`${e} update\` with registry access.`),upgradeAvailable:null};let{targetPackage:r,currentVersion:i,latestVersion:a,upgradeAvailable:o}=n.data;return{check:o?q(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):q(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function ho(e){try{let{EntityDetailSchema:e}=await import(`./detail-D9M8QZSE.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return q(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return q(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${E(t)}.`)}}async function go(e,t){if(e===void 0)return{check:q(`api-host`,`skip`,`No status operation resolved from the generated catalog; fix the catalog check first.`),servedFingerprint:null};let n;try{n=b().host}catch(e){return{check:q(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${E(e)}.`),servedFingerprint:null}}let r=await le({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>y(E(e)));return r.ok?{check:q(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:_o(r.data)}:{check:q(`api-host`,`fail`,r.httpStatus===401?`Replace or unset the credential ${n} rejected, or run \`${t} auth login\`, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} returned ${r.summary}.`:`Point the CLI at a reachable API host with \`--environment <name>\` or API_URL, then rerun \`${t} auth doctor\` — ${e.method} ${e.path} at ${n} returned ${r.summary}.`),servedFingerprint:null}}function _o(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[co];return typeof n==`string`&&n.length>0?n:null}async function vo(e){let t=Oe(),[n,r]=await Promise.all([yo(),bo()]);if(r.state===`unavailable`&&r.cause===`environment`)return q(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t.present;return!i&&n.state===`invalid`?q(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`):!i&&n.state===`found`&&Te(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0?q(`auth`,`fail`,`Saved OAuth access token is expired without a refresh token; run \`${e} auth login\` to sign in again.`):!i&&r.state!==`found`&&n.state===`unavailable`?q(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${u.authToken} through the environment — ${n.summary}.`):i||n.state===`found`||r.state===`found`?q(`auth`,`pass`,`Credential source available: ${xo(t,n,r)}.`):r.state===`unavailable`?q(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${u.authToken} through the environment — ${r.summary}.`):q(`auth`,`fail`,`Run \`${e} auth login\` for OAuth or \`${e} auth login --key\` for an API key. For non-interactive use, set ${u.authToken} in the environment.`)}async function yo(){let e;try{e=Ne(b().host)}catch(e){return{state:`unavailable`,summary:E(e)}}return await Pe(e)}async function bo(){let e;try{e=Be(b().host)}catch(e){return{state:`unavailable`,summary:E(e),cause:`environment`}}try{return await ze(e)}catch(e){return{state:`unavailable`,summary:E(e),cause:`storage`}}}function xo(e,t,n){return[wa(e),`oauth=${Co(t)}`,`api-key=${So(n)}`].join(` `)}function So(e){if(e.state!==`found`)return e.state===`missing`?`unset`:`unavailable`;let t=Be(b().host);return`${e.stored.activation}${la(t,e)}`}function Co(e){switch(e.state){case`found`:return Te(e.stored.credential)?`expired`:`stored`;case`missing`:return`unset`;case`invalid`:return`invalid`;case`unavailable`:return`unavailable`;default:throw Error(`Unsupported OAuth credential state`)}}function wo(e,t,n,r){let i=k.length;if(e===void 0)return q(`catalog`,`fail`,`Regenerate the command catalog with \`make mcp-generate-contracts\` and reinstall: none of its ${i} operations is the status operation.`);if(t===null)return q(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${Xe}.`);if(t===`d1b88f6cca4624ab`)return q(`catalog`,`pass`,`${i} generated operations match the set the API serves (${Xe}).`);let a=`This catalog describes a different operation set than the API serves (${Xe} vs ${t})`;return n===!0?q(`catalog`,`fail`,`${a}: run \`${r} update\`.`):q(`catalog`,`skip`,n===!1?`${a}, 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.`:`${a}, and the registry did not answer, so it is unknown whether a newer release describes it: rerun \`${r} update\` with registry access.`)}var To=V(H,`oauth`),Eo=[V(H,`start`),V(H,`poll`),V(H,`acknowledge`)],Do=V(H,`revoke`);function Oo(e,t=l().bin[0]){let n=Mo(e);lo(n,t);let r=[`${To.description} Default method: OAuth in your browser.`,`With --key: ${Eo.map(({description:e})=>e).join(` `)}`].join(`
29
29
  `);O(jo(n,[To,...Eo],r)).action(ko),O(jo(n,[Do],Do.description)).action(Ao),O(n.command(`status`).summary(`Keep saved credentials current and report them with API build and uptime`).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`,` - system: GET /v1/status response (uptime SLA)`,``,`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(`
30
30
  `)).addOption(new S(`--verify <scope>`,`verify one permission-probe scope`).choices([`read`,`write`]))).action(async function(e){No(this),R({mode:D(e)},await Po(t,e.verify))}),n.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: ${u.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(`
31
31
  `)).action(async function(){No(this);let e=await ta(t),n=process.env[u.authToken]?.trim();if(e.failure===null&&n!==void 0&&n.length>0){process.stdout.write(`${n}\n`);return}R({mode:`text`},e.failure===null?Ho(`auth token: no credentials resolved`,null,t,{oauth:!0,apiKey:!0}):y(`auth token: ${e.failure}`))})}async function ko(e){No(this);let t=D(e);if(e.providers===!0){R({mode:t},await Io());return}R({mode:t},e.key===!0?await Wi({noBrowser:!e.browser,clientLabel:e.clientLabel}):await st({noBrowser:!e.browser}))}async function Ao(e){No(this),R({mode:D(e)},await Ni({forgetLocal:e.forgetLocal===!0}))}function jo(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 Mo(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Sign in, sign out, and check credentials`).description([`\`${To.command}\`: ${To.summary}; \`--key\` ${Eo[0].summary.toLowerCase()}.`,`\`${Do.command}\`: ${Do.summary}.`,"`auth status` reports local credential provenance, sign-in providers, and CLI/API build and uptime.","`auth doctor` runs the one-call selftest and prints `{ ok, check: [...] }`.","`auth token` prints the bearer token the next command sends."].join(`
@@ -1 +1 @@
1
- import{a as e}from"./auth-BGCkxIpd.js";import{C as t,D as n,E as r,S as ee,T as i,_ as a,b as o,c as te,d as s,f as ne,h as re,i as ie,p as ae,s as c,u as l,v as u,x as d,y as f}from"./person-owner-9MfK4f_5.js";var oe=o({clerkPublishableKey:i().nullish(),oauthClient:e.nullish()}),se=`2025-11-25`,ce=`2025-03-26`,le=[se,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],ue=`io.modelcontextprotocol/related-task`,p=ne(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),de=r([i(),f().int()]),fe=i();u({ttl:f().optional(),pollInterval:f().optional()});var pe=o({ttl:f().optional()}),me=o({taskId:i()}),m=u({progressToken:de.optional(),[ue]:me.optional()}),h=o({_meta:m.optional()}),g=h.extend({task:pe.optional()}),he=e=>g.safeParse(e).success,_=o({method:i(),params:h.loose().optional()}),v=o({_meta:m.optional()}),y=o({method:i(),params:v.loose().optional()}),b=u({_meta:m.optional()}),x=r([i(),f().int()]),ge=o({jsonrpc:a(`2.0`),id:x,..._.shape}).strict(),_e=e=>ge.safeParse(e).success,ve=o({jsonrpc:a(`2.0`),...y.shape}).strict(),ye=e=>ve.safeParse(e).success,S=o({jsonrpc:a(`2.0`),id:x,result:b}).strict(),be=e=>S.safeParse(e).success,C;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(C||={});var w=o({jsonrpc:a(`2.0`),id:x.optional(),error:o({code:f().int(),message:i(),data:n().optional()})}).strict(),xe=e=>w.safeParse(e).success,Se=r([ge,ve,S,w]);r([S,w]);var T=b.strict(),Ce=v.extend({requestId:x.optional(),reason:i().optional()}),E=y.extend({method:a(`notifications/cancelled`),params:Ce}),we=o({src:i(),mimeType:i().optional(),sizes:l(i()).optional(),theme:c([`light`,`dark`]).optional()}),D=o({icons:l(we).optional()}),O=o({name:i(),title:i().optional()}),Te=O.extend({...O.shape,...D.shape,version:i(),websiteUrl:i().optional(),description:i().optional()}),Ee=re(o({applyDefaults:s().optional()}),t(i(),n())),De=ee(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,re(o({form:Ee.optional(),url:p.optional()}),t(i(),n()).optional())),Oe=u({list:p.optional(),cancel:p.optional(),requests:u({sampling:u({createMessage:p.optional()}).optional(),elicitation:u({create:p.optional()}).optional()}).optional()}),ke=u({list:p.optional(),cancel:p.optional(),requests:u({tools:u({call:p.optional()}).optional()}).optional()}),Ae=o({experimental:t(i(),p).optional(),sampling:o({context:p.optional(),tools:p.optional()}).optional(),elicitation:De.optional(),roots:o({listChanged:s().optional()}).optional(),tasks:Oe.optional(),extensions:t(i(),p).optional()}),je=h.extend({protocolVersion:i(),capabilities:Ae,clientInfo:Te}),k=_.extend({method:a(`initialize`),params:je}),Me=e=>k.safeParse(e).success,Ne=o({experimental:t(i(),p).optional(),logging:p.optional(),completions:p.optional(),prompts:o({listChanged:s().optional()}).optional(),resources:o({subscribe:s().optional(),listChanged:s().optional()}).optional(),tools:o({listChanged:s().optional()}).optional(),tasks:ke.optional(),extensions:t(i(),p).optional()}),Pe=b.extend({protocolVersion:i(),capabilities:Ne,serverInfo:Te,instructions:i().optional()}),Fe=y.extend({method:a(`notifications/initialized`),params:v.optional()}),A=_.extend({method:a(`ping`),params:h.optional()}),Ie=o({progress:f(),total:d(f()),message:d(i())}),Le=o({...v.shape,...Ie.shape,progressToken:de}),j=y.extend({method:a(`notifications/progress`),params:Le}),Re=h.extend({cursor:fe.optional()}),M=_.extend({params:Re.optional()}),N=b.extend({nextCursor:fe.optional()}),ze=c([`working`,`input_required`,`completed`,`failed`,`cancelled`]),P=o({taskId:i(),status:ze,ttl:r([f(),te()]),createdAt:i(),lastUpdatedAt:i(),pollInterval:d(f()),statusMessage:d(i())}),F=b.extend({task:P}),Be=v.merge(P),I=y.extend({method:a(`notifications/tasks/status`),params:Be}),L=_.extend({method:a(`tasks/get`),params:h.extend({taskId:i()})}),R=b.merge(P),z=_.extend({method:a(`tasks/result`),params:h.extend({taskId:i()})});b.loose();var B=M.extend({method:a(`tasks/list`)}),V=N.extend({tasks:l(P)}),H=_.extend({method:a(`tasks/cancel`),params:h.extend({taskId:i()})}),Ve=b.merge(P),He=o({uri:i(),mimeType:d(i()),_meta:t(i(),n()).optional()}),Ue=He.extend({text:i()}),U=i().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),We=He.extend({blob:U}),W=c([`user`,`assistant`]),G=o({audience:l(W).optional(),priority:f().min(0).max(1).optional(),lastModified:ie({offset:!0}).optional()}),Ge=o({...O.shape,...D.shape,uri:i(),description:d(i()),mimeType:d(i()),size:d(f()),annotations:G.optional(),_meta:d(u({}))}),Ke=o({...O.shape,...D.shape,uriTemplate:i(),description:d(i()),mimeType:d(i()),annotations:G.optional(),_meta:d(u({}))}),qe=M.extend({method:a(`resources/list`)}),Je=N.extend({resources:l(Ge)}),Ye=M.extend({method:a(`resources/templates/list`)}),Xe=N.extend({resourceTemplates:l(Ke)}),K=h.extend({uri:i()}),Ze=K,Qe=_.extend({method:a(`resources/read`),params:Ze}),$e=b.extend({contents:l(r([Ue,We]))}),et=y.extend({method:a(`notifications/resources/list_changed`),params:v.optional()}),tt=K,nt=_.extend({method:a(`resources/subscribe`),params:tt}),rt=K,it=_.extend({method:a(`resources/unsubscribe`),params:rt}),at=v.extend({uri:i()}),ot=y.extend({method:a(`notifications/resources/updated`),params:at}),st=o({name:i(),description:d(i()),required:d(s())}),ct=o({...O.shape,...D.shape,description:d(i()),arguments:d(l(st)),_meta:d(u({}))}),lt=M.extend({method:a(`prompts/list`)}),ut=N.extend({prompts:l(ct)}),dt=h.extend({name:i(),arguments:t(i(),i()).optional()}),ft=_.extend({method:a(`prompts/get`),params:dt}),q=o({type:a(`text`),text:i(),annotations:G.optional(),_meta:t(i(),n()).optional()}),J=o({type:a(`image`),data:U,mimeType:i(),annotations:G.optional(),_meta:t(i(),n()).optional()}),Y=o({type:a(`audio`),data:U,mimeType:i(),annotations:G.optional(),_meta:t(i(),n()).optional()}),pt=o({type:a(`tool_use`),name:i(),id:i(),input:t(i(),n()),_meta:t(i(),n()).optional()}),mt=o({type:a(`resource`),resource:r([Ue,We]),annotations:G.optional(),_meta:t(i(),n()).optional()}),ht=Ge.extend({type:a(`resource_link`)}),X=r([q,J,Y,ht,mt]),gt=o({role:W,content:X}),_t=b.extend({description:i().optional(),messages:l(gt)}),vt=y.extend({method:a(`notifications/prompts/list_changed`),params:v.optional()}),yt=o({title:i().optional(),readOnlyHint:s().optional(),destructiveHint:s().optional(),idempotentHint:s().optional(),openWorldHint:s().optional()}),bt=o({taskSupport:c([`required`,`optional`,`forbidden`]).optional()}),xt=o({...O.shape,...D.shape,description:i().optional(),inputSchema:o({type:a(`object`),properties:t(i(),p).optional(),required:l(i()).optional()}).catchall(n()),outputSchema:o({type:a(`object`),properties:t(i(),p).optional(),required:l(i()).optional()}).catchall(n()).optional(),annotations:yt.optional(),execution:bt.optional(),_meta:t(i(),n()).optional()}),St=M.extend({method:a(`tools/list`)}),Ct=N.extend({tools:l(xt)}),Z=b.extend({content:l(X).default([]),structuredContent:t(i(),n()).optional(),isError:s().optional()});Z.or(b.extend({toolResult:n()}));var wt=g.extend({name:i(),arguments:t(i(),n()).optional()}),Tt=_.extend({method:a(`tools/call`),params:wt}),Et=y.extend({method:a(`notifications/tools/list_changed`),params:v.optional()});o({autoRefresh:s().default(!0),debounceMs:f().int().nonnegative().default(300)});var Q=c([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Dt=h.extend({level:Q}),Ot=_.extend({method:a(`logging/setLevel`),params:Dt}),kt=v.extend({level:Q,logger:i().optional(),data:n()}),At=y.extend({method:a(`notifications/message`),params:kt}),jt=o({name:i().optional()}),Mt=o({hints:l(jt).optional(),costPriority:f().min(0).max(1).optional(),speedPriority:f().min(0).max(1).optional(),intelligencePriority:f().min(0).max(1).optional()}),Nt=o({mode:c([`auto`,`required`,`none`]).optional()}),Pt=o({type:a(`tool_result`),toolUseId:i().describe(`The unique identifier for the corresponding tool call.`),content:l(X).default([]),structuredContent:o({}).loose().optional(),isError:s().optional(),_meta:t(i(),n()).optional()}),Ft=ae(`type`,[q,J,Y]),$=ae(`type`,[q,J,Y,pt,Pt]),It=o({role:W,content:r([$,l($)]),_meta:t(i(),n()).optional()}),Lt=g.extend({messages:l(It),modelPreferences:Mt.optional(),systemPrompt:i().optional(),includeContext:c([`none`,`thisServer`,`allServers`]).optional(),temperature:f().optional(),maxTokens:f().int(),stopSequences:l(i()).optional(),metadata:p.optional(),tools:l(xt).optional(),toolChoice:Nt.optional()}),Rt=_.extend({method:a(`sampling/createMessage`),params:Lt}),zt=b.extend({model:i(),stopReason:d(c([`endTurn`,`stopSequence`,`maxTokens`]).or(i())),role:W,content:Ft}),Bt=b.extend({model:i(),stopReason:d(c([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(i())),role:W,content:r([$,l($)])}),Vt=o({type:a(`boolean`),title:i().optional(),description:i().optional(),default:s().optional()}),Ht=o({type:a(`string`),title:i().optional(),description:i().optional(),minLength:f().optional(),maxLength:f().optional(),format:c([`email`,`uri`,`date`,`date-time`]).optional(),default:i().optional()}),Ut=o({type:c([`number`,`integer`]),title:i().optional(),description:i().optional(),minimum:f().optional(),maximum:f().optional(),default:f().optional()}),Wt=o({type:a(`string`),title:i().optional(),description:i().optional(),enum:l(i()),default:i().optional()}),Gt=o({type:a(`string`),title:i().optional(),description:i().optional(),oneOf:l(o({const:i(),title:i()})),default:i().optional()}),Kt=o({type:a(`string`),title:i().optional(),description:i().optional(),enum:l(i()),enumNames:l(i()).optional(),default:i().optional()}),qt=r([Wt,Gt]),Jt=o({type:a(`array`),title:i().optional(),description:i().optional(),minItems:f().optional(),maxItems:f().optional(),items:o({type:a(`string`),enum:l(i())}),default:l(i()).optional()}),Yt=o({type:a(`array`),title:i().optional(),description:i().optional(),minItems:f().optional(),maxItems:f().optional(),items:o({anyOf:l(o({const:i(),title:i()}))}),default:l(i()).optional()}),Xt=r([Jt,Yt]),Zt=r([Kt,qt,Xt]),Qt=r([Zt,Vt,Ht,Ut]),$t=g.extend({mode:a(`form`).optional(),message:i(),requestedSchema:o({type:a(`object`),properties:t(i(),Qt),required:l(i()).optional()})}),en=g.extend({mode:a(`url`),message:i(),elicitationId:i(),url:i().url()}),tn=r([$t,en]),nn=_.extend({method:a(`elicitation/create`),params:tn}),rn=v.extend({elicitationId:i()}),an=y.extend({method:a(`notifications/elicitation/complete`),params:rn}),on=b.extend({action:c([`accept`,`decline`,`cancel`]),content:ee(e=>e===null?void 0:e,t(i(),r([i(),f(),s(),l(i())])).optional())}),sn=o({type:a(`ref/resource`),uri:i()}),cn=o({type:a(`ref/prompt`),name:i()}),ln=h.extend({ref:r([cn,sn]),argument:o({name:i(),value:i()}),context:o({arguments:t(i(),i()).optional()}).optional()}),un=_.extend({method:a(`completion/complete`),params:ln});function dn(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function fn(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var pn=b.extend({completion:u({values:l(i()).max(100),total:d(f().int()),hasMore:d(s())})}),mn=o({uri:i().startsWith(`file://`),name:i().optional(),_meta:t(i(),n()).optional()}),hn=_.extend({method:a(`roots/list`),params:h.optional()}),gn=b.extend({roots:l(mn)}),_n=y.extend({method:a(`notifications/roots/list_changed`),params:v.optional()});r([A,k,un,Ot,ft,lt,qe,Ye,Qe,nt,it,Tt,St,L,z,B,H]),r([E,j,Fe,_n,I]),r([T,zt,Bt,on,gn,R,V,F]),r([A,Rt,nn,hn,L,z,B,H]),r([E,j,At,ot,et,Et,vt,I,an]),r([T,Pe,pn,_t,ut,Je,Xe,$e,Z,Ct,R,V,F]);var vn=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===C.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new yn(e.elicitations,n)}return new e(t,n,r)}},yn=class extends vn{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(C.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},bn=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function xn(e){return(await bn).getRandomValues(new Uint8Array(e))}async function Sn(e){let t=``;for(;t.length<e;){let n=await xn(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function Cn(e){return await Sn(e)}async function wn(e){let t=await(await bn).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function Tn(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Cn(e);return{code_verifier:t,code_challenge:await wn(t)}}export{Q as A,fn as B,lt as C,B as D,gn as E,Qe as F,be as G,xe as H,le as I,he as K,Ot as L,A as M,j as N,V as O,ue as P,I as R,se as S,qe as T,ye as U,Me as V,_e as W,L as _,Ve as a,Fe as b,zt as c,ce as d,on as f,z as g,ft as h,H as i,vn as j,St as k,Bt as l,C as m,Tt as n,E as o,T as p,oe as q,Z as r,un as s,Tn as t,F as u,R as v,Ye as w,Se as x,k as y,dn as z};
1
+ import{a as e}from"./auth-o0Bk3f3c.js";import{C as t,D as n,E as r,S as ee,T as i,_ as a,b as o,c as te,d as s,f as ne,h as re,i as ie,p as ae,s as c,u as l,v as u,x as d,y as f}from"./person-owner-9MfK4f_5.js";var oe=o({clerkPublishableKey:i().nullish(),oauthClient:e.nullish()}),se=`2025-11-25`,ce=`2025-03-26`,le=[se,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],ue=`io.modelcontextprotocol/related-task`,p=ne(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),de=r([i(),f().int()]),fe=i();u({ttl:f().optional(),pollInterval:f().optional()});var pe=o({ttl:f().optional()}),me=o({taskId:i()}),m=u({progressToken:de.optional(),[ue]:me.optional()}),h=o({_meta:m.optional()}),g=h.extend({task:pe.optional()}),he=e=>g.safeParse(e).success,_=o({method:i(),params:h.loose().optional()}),v=o({_meta:m.optional()}),y=o({method:i(),params:v.loose().optional()}),b=u({_meta:m.optional()}),x=r([i(),f().int()]),ge=o({jsonrpc:a(`2.0`),id:x,..._.shape}).strict(),_e=e=>ge.safeParse(e).success,ve=o({jsonrpc:a(`2.0`),...y.shape}).strict(),ye=e=>ve.safeParse(e).success,S=o({jsonrpc:a(`2.0`),id:x,result:b}).strict(),be=e=>S.safeParse(e).success,C;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(C||={});var w=o({jsonrpc:a(`2.0`),id:x.optional(),error:o({code:f().int(),message:i(),data:n().optional()})}).strict(),xe=e=>w.safeParse(e).success,Se=r([ge,ve,S,w]);r([S,w]);var T=b.strict(),Ce=v.extend({requestId:x.optional(),reason:i().optional()}),E=y.extend({method:a(`notifications/cancelled`),params:Ce}),we=o({src:i(),mimeType:i().optional(),sizes:l(i()).optional(),theme:c([`light`,`dark`]).optional()}),D=o({icons:l(we).optional()}),O=o({name:i(),title:i().optional()}),Te=O.extend({...O.shape,...D.shape,version:i(),websiteUrl:i().optional(),description:i().optional()}),Ee=re(o({applyDefaults:s().optional()}),t(i(),n())),De=ee(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,re(o({form:Ee.optional(),url:p.optional()}),t(i(),n()).optional())),Oe=u({list:p.optional(),cancel:p.optional(),requests:u({sampling:u({createMessage:p.optional()}).optional(),elicitation:u({create:p.optional()}).optional()}).optional()}),ke=u({list:p.optional(),cancel:p.optional(),requests:u({tools:u({call:p.optional()}).optional()}).optional()}),Ae=o({experimental:t(i(),p).optional(),sampling:o({context:p.optional(),tools:p.optional()}).optional(),elicitation:De.optional(),roots:o({listChanged:s().optional()}).optional(),tasks:Oe.optional(),extensions:t(i(),p).optional()}),je=h.extend({protocolVersion:i(),capabilities:Ae,clientInfo:Te}),k=_.extend({method:a(`initialize`),params:je}),Me=e=>k.safeParse(e).success,Ne=o({experimental:t(i(),p).optional(),logging:p.optional(),completions:p.optional(),prompts:o({listChanged:s().optional()}).optional(),resources:o({subscribe:s().optional(),listChanged:s().optional()}).optional(),tools:o({listChanged:s().optional()}).optional(),tasks:ke.optional(),extensions:t(i(),p).optional()}),Pe=b.extend({protocolVersion:i(),capabilities:Ne,serverInfo:Te,instructions:i().optional()}),Fe=y.extend({method:a(`notifications/initialized`),params:v.optional()}),A=_.extend({method:a(`ping`),params:h.optional()}),Ie=o({progress:f(),total:d(f()),message:d(i())}),Le=o({...v.shape,...Ie.shape,progressToken:de}),j=y.extend({method:a(`notifications/progress`),params:Le}),Re=h.extend({cursor:fe.optional()}),M=_.extend({params:Re.optional()}),N=b.extend({nextCursor:fe.optional()}),ze=c([`working`,`input_required`,`completed`,`failed`,`cancelled`]),P=o({taskId:i(),status:ze,ttl:r([f(),te()]),createdAt:i(),lastUpdatedAt:i(),pollInterval:d(f()),statusMessage:d(i())}),F=b.extend({task:P}),Be=v.merge(P),I=y.extend({method:a(`notifications/tasks/status`),params:Be}),L=_.extend({method:a(`tasks/get`),params:h.extend({taskId:i()})}),R=b.merge(P),z=_.extend({method:a(`tasks/result`),params:h.extend({taskId:i()})});b.loose();var B=M.extend({method:a(`tasks/list`)}),V=N.extend({tasks:l(P)}),H=_.extend({method:a(`tasks/cancel`),params:h.extend({taskId:i()})}),Ve=b.merge(P),He=o({uri:i(),mimeType:d(i()),_meta:t(i(),n()).optional()}),Ue=He.extend({text:i()}),U=i().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),We=He.extend({blob:U}),W=c([`user`,`assistant`]),G=o({audience:l(W).optional(),priority:f().min(0).max(1).optional(),lastModified:ie({offset:!0}).optional()}),Ge=o({...O.shape,...D.shape,uri:i(),description:d(i()),mimeType:d(i()),size:d(f()),annotations:G.optional(),_meta:d(u({}))}),Ke=o({...O.shape,...D.shape,uriTemplate:i(),description:d(i()),mimeType:d(i()),annotations:G.optional(),_meta:d(u({}))}),qe=M.extend({method:a(`resources/list`)}),Je=N.extend({resources:l(Ge)}),Ye=M.extend({method:a(`resources/templates/list`)}),Xe=N.extend({resourceTemplates:l(Ke)}),K=h.extend({uri:i()}),Ze=K,Qe=_.extend({method:a(`resources/read`),params:Ze}),$e=b.extend({contents:l(r([Ue,We]))}),et=y.extend({method:a(`notifications/resources/list_changed`),params:v.optional()}),tt=K,nt=_.extend({method:a(`resources/subscribe`),params:tt}),rt=K,it=_.extend({method:a(`resources/unsubscribe`),params:rt}),at=v.extend({uri:i()}),ot=y.extend({method:a(`notifications/resources/updated`),params:at}),st=o({name:i(),description:d(i()),required:d(s())}),ct=o({...O.shape,...D.shape,description:d(i()),arguments:d(l(st)),_meta:d(u({}))}),lt=M.extend({method:a(`prompts/list`)}),ut=N.extend({prompts:l(ct)}),dt=h.extend({name:i(),arguments:t(i(),i()).optional()}),ft=_.extend({method:a(`prompts/get`),params:dt}),q=o({type:a(`text`),text:i(),annotations:G.optional(),_meta:t(i(),n()).optional()}),J=o({type:a(`image`),data:U,mimeType:i(),annotations:G.optional(),_meta:t(i(),n()).optional()}),Y=o({type:a(`audio`),data:U,mimeType:i(),annotations:G.optional(),_meta:t(i(),n()).optional()}),pt=o({type:a(`tool_use`),name:i(),id:i(),input:t(i(),n()),_meta:t(i(),n()).optional()}),mt=o({type:a(`resource`),resource:r([Ue,We]),annotations:G.optional(),_meta:t(i(),n()).optional()}),ht=Ge.extend({type:a(`resource_link`)}),X=r([q,J,Y,ht,mt]),gt=o({role:W,content:X}),_t=b.extend({description:i().optional(),messages:l(gt)}),vt=y.extend({method:a(`notifications/prompts/list_changed`),params:v.optional()}),yt=o({title:i().optional(),readOnlyHint:s().optional(),destructiveHint:s().optional(),idempotentHint:s().optional(),openWorldHint:s().optional()}),bt=o({taskSupport:c([`required`,`optional`,`forbidden`]).optional()}),xt=o({...O.shape,...D.shape,description:i().optional(),inputSchema:o({type:a(`object`),properties:t(i(),p).optional(),required:l(i()).optional()}).catchall(n()),outputSchema:o({type:a(`object`),properties:t(i(),p).optional(),required:l(i()).optional()}).catchall(n()).optional(),annotations:yt.optional(),execution:bt.optional(),_meta:t(i(),n()).optional()}),St=M.extend({method:a(`tools/list`)}),Ct=N.extend({tools:l(xt)}),Z=b.extend({content:l(X).default([]),structuredContent:t(i(),n()).optional(),isError:s().optional()});Z.or(b.extend({toolResult:n()}));var wt=g.extend({name:i(),arguments:t(i(),n()).optional()}),Tt=_.extend({method:a(`tools/call`),params:wt}),Et=y.extend({method:a(`notifications/tools/list_changed`),params:v.optional()});o({autoRefresh:s().default(!0),debounceMs:f().int().nonnegative().default(300)});var Q=c([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Dt=h.extend({level:Q}),Ot=_.extend({method:a(`logging/setLevel`),params:Dt}),kt=v.extend({level:Q,logger:i().optional(),data:n()}),At=y.extend({method:a(`notifications/message`),params:kt}),jt=o({name:i().optional()}),Mt=o({hints:l(jt).optional(),costPriority:f().min(0).max(1).optional(),speedPriority:f().min(0).max(1).optional(),intelligencePriority:f().min(0).max(1).optional()}),Nt=o({mode:c([`auto`,`required`,`none`]).optional()}),Pt=o({type:a(`tool_result`),toolUseId:i().describe(`The unique identifier for the corresponding tool call.`),content:l(X).default([]),structuredContent:o({}).loose().optional(),isError:s().optional(),_meta:t(i(),n()).optional()}),Ft=ae(`type`,[q,J,Y]),$=ae(`type`,[q,J,Y,pt,Pt]),It=o({role:W,content:r([$,l($)]),_meta:t(i(),n()).optional()}),Lt=g.extend({messages:l(It),modelPreferences:Mt.optional(),systemPrompt:i().optional(),includeContext:c([`none`,`thisServer`,`allServers`]).optional(),temperature:f().optional(),maxTokens:f().int(),stopSequences:l(i()).optional(),metadata:p.optional(),tools:l(xt).optional(),toolChoice:Nt.optional()}),Rt=_.extend({method:a(`sampling/createMessage`),params:Lt}),zt=b.extend({model:i(),stopReason:d(c([`endTurn`,`stopSequence`,`maxTokens`]).or(i())),role:W,content:Ft}),Bt=b.extend({model:i(),stopReason:d(c([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(i())),role:W,content:r([$,l($)])}),Vt=o({type:a(`boolean`),title:i().optional(),description:i().optional(),default:s().optional()}),Ht=o({type:a(`string`),title:i().optional(),description:i().optional(),minLength:f().optional(),maxLength:f().optional(),format:c([`email`,`uri`,`date`,`date-time`]).optional(),default:i().optional()}),Ut=o({type:c([`number`,`integer`]),title:i().optional(),description:i().optional(),minimum:f().optional(),maximum:f().optional(),default:f().optional()}),Wt=o({type:a(`string`),title:i().optional(),description:i().optional(),enum:l(i()),default:i().optional()}),Gt=o({type:a(`string`),title:i().optional(),description:i().optional(),oneOf:l(o({const:i(),title:i()})),default:i().optional()}),Kt=o({type:a(`string`),title:i().optional(),description:i().optional(),enum:l(i()),enumNames:l(i()).optional(),default:i().optional()}),qt=r([Wt,Gt]),Jt=o({type:a(`array`),title:i().optional(),description:i().optional(),minItems:f().optional(),maxItems:f().optional(),items:o({type:a(`string`),enum:l(i())}),default:l(i()).optional()}),Yt=o({type:a(`array`),title:i().optional(),description:i().optional(),minItems:f().optional(),maxItems:f().optional(),items:o({anyOf:l(o({const:i(),title:i()}))}),default:l(i()).optional()}),Xt=r([Jt,Yt]),Zt=r([Kt,qt,Xt]),Qt=r([Zt,Vt,Ht,Ut]),$t=g.extend({mode:a(`form`).optional(),message:i(),requestedSchema:o({type:a(`object`),properties:t(i(),Qt),required:l(i()).optional()})}),en=g.extend({mode:a(`url`),message:i(),elicitationId:i(),url:i().url()}),tn=r([$t,en]),nn=_.extend({method:a(`elicitation/create`),params:tn}),rn=v.extend({elicitationId:i()}),an=y.extend({method:a(`notifications/elicitation/complete`),params:rn}),on=b.extend({action:c([`accept`,`decline`,`cancel`]),content:ee(e=>e===null?void 0:e,t(i(),r([i(),f(),s(),l(i())])).optional())}),sn=o({type:a(`ref/resource`),uri:i()}),cn=o({type:a(`ref/prompt`),name:i()}),ln=h.extend({ref:r([cn,sn]),argument:o({name:i(),value:i()}),context:o({arguments:t(i(),i()).optional()}).optional()}),un=_.extend({method:a(`completion/complete`),params:ln});function dn(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function fn(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var pn=b.extend({completion:u({values:l(i()).max(100),total:d(f().int()),hasMore:d(s())})}),mn=o({uri:i().startsWith(`file://`),name:i().optional(),_meta:t(i(),n()).optional()}),hn=_.extend({method:a(`roots/list`),params:h.optional()}),gn=b.extend({roots:l(mn)}),_n=y.extend({method:a(`notifications/roots/list_changed`),params:v.optional()});r([A,k,un,Ot,ft,lt,qe,Ye,Qe,nt,it,Tt,St,L,z,B,H]),r([E,j,Fe,_n,I]),r([T,zt,Bt,on,gn,R,V,F]),r([A,Rt,nn,hn,L,z,B,H]),r([E,j,At,ot,et,Et,vt,I,an]),r([T,Pe,pn,_t,ut,Je,Xe,$e,Z,Ct,R,V,F]);var vn=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===C.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new yn(e.elicitations,n)}return new e(t,n,r)}},yn=class extends vn{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(C.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},bn=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function xn(e){return(await bn).getRandomValues(new Uint8Array(e))}async function Sn(e){let t=``;for(;t.length<e;){let n=await xn(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function Cn(e){return await Sn(e)}async function wn(e){let t=await(await bn).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function Tn(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Cn(e);return{code_verifier:t,code_challenge:await wn(t)}}export{Q as A,fn as B,lt as C,B as D,gn as E,Qe as F,be as G,xe as H,le as I,he as K,Ot as L,A as M,j as N,V as O,ue as P,I as R,se as S,qe as T,ye as U,Me as V,_e as W,L as _,Ve as a,Fe as b,zt as c,ce as d,on as f,z as g,ft as h,H as i,vn as j,St as k,Bt as l,C as m,Tt as n,E as o,T as p,oe as q,Z as r,un as s,Tn as t,F as u,R as v,Ye as w,Se as x,k as y,dn as z};
@@ -1,4 +1,4 @@
1
- import{F as e,M as t,N as n,R as r,V as i,Y as a,Z as o,a as s,d as c,j as l,m as u,r as d,rt as f}from"./auth-BGCkxIpd.js";import{T as p,b as m,i as h,s as ee,u as te}from"./person-owner-9MfK4f_5.js";import{execFile as ne}from"node:child_process";import{dirname as g,join as _}from"node:path";import{chmod as re,mkdir as v,readFile as y,rename as b,rm as x,stat as ie,writeFile as ae}from"node:fs/promises";import{AsyncLocalStorage as oe}from"node:async_hooks";import{randomUUID as S}from"node:crypto";import{homedir as se,platform as C}from"node:os";import{setTimeout as ce}from"node:timers/promises";function w(e,t=[]){let n=e instanceof Error?e.message:String(e);return u(n,t)}function le(e,t=[]){let n=u(e.title,t),r=u(e.detail?.trim()??``,t);return`${e.status} ${n}${r?` — ${r}`:``}`}function ue(){if(C()===`win32`){let e=process.env.APPDATA??_(se(),`AppData`,`Roaming`);return _(e,`aventure`,`config.json`)}let e=process.env.XDG_CONFIG_HOME??_(se(),`.config`);return _(e,`aventure`,`config.json`)}function de(){let e=process.env[o.authToken];return typeof e==`string`&&e.length>0?{present:!0,source:`env`}:{present:!1,source:null}}function T(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}function E(e){let t=e.trim();if(t.length===0)throw Error(`API host must not be blank`);let n=new URL(me(t)?t:`${he(t)}://${t}`),r=D(n.hostname);if(n.protocol!==`https:`&&n.protocol!==`http:`||n.username.length>0||n.password.length>0||n.pathname!==`/`&&n.pathname!==``||n.search.length>0||n.hash.length>0)throw Error(`API host must contain only an HTTP(S) host and optional port`);if(n.protocol===`http:`&&!r)throw Error(`stored credentials require HTTPS except for loopback API hosts`);return{host:n.host.toLowerCase(),origin:n.origin,isLoopback:r}}function fe(e){return{...e,host:E(e.host).origin}}function pe(e){let t=E(e);if(t.isLoopback)return`http://localhost:3000`;if(t.host===`api.aventure.vc`)return`https://aventure.vc`;throw Error(`no first-party browser origin is configured for API host ${t.host}`)}function me(e){return/^[a-z][a-z\d+.-]*:\/\//iu.test(e)}function he(e){let t=e.split(`/`,1)[0]?.toLowerCase()??``;try{return D(new URL(`http://${t}`).hostname)?`http`:`https`}catch{return`https`}}function D(e){let t=e.toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`0.0.0.0`||t===`[::1]`}var ge=2;function _e(e,t){return k(e,t).redactedUrl}async function ve(e,t,n){let r=k(e,t);return await O(new URL(r.openerUrl),n)}async function O(e,t){let n=t.environment??process.env,r=t.operatingSystem??C(),i=ye(t.noBrowser,n,r);if(i!==null)return{state:`skipped`,reason:i};let a=be(r,e.toString());if(a===null)return{state:`failed`,reason:`unsupported browser-opening platform: ${r}`};try{return await xe(a.command,a.arguments),{state:`opened`,reason:null}}catch{return{state:`failed`,reason:`browser opener failed`}}}function k(e,t){let{id:n,verificationUrl:r,pollSecret:i}=e,a,o;try{a=new URL(r),o=new URL(t)}catch{throw Error(`broker returned an invalid browser verification URL`)}if(o.username.length>0||o.password.length>0||o.pathname!==`/`||o.search.length>0||o.hash.length>0)throw Error(`configured browser origin must contain only an origin`);let s=D(o.hostname);if(o.protocol!==`https:`&&!(o.protocol===`http:`&&s))throw Error(`configured browser origin must use HTTPS except for loopback development`);let c=new URLSearchParams(a.hash.slice(1)),l=[...c.keys()],u=c.getAll(`cliAuthorizationId`),d=c.getAll(`browserSecret`),f=d[0]??``;if(a.origin!==o.origin||a.protocol!==o.protocol||a.username.length>0||a.password.length>0||a.pathname!==`/settings/developer`||a.search.length>0||l.length!==ge||u.length!==1||u[0]!==n||d.length!==1||f.length===0||i.length===0||f===i)throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let p;try{p=decodeURIComponent(r)}catch{throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`)}if(r.includes(i)||p.includes(i))throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let m=new URL(a);return m.hash=new URLSearchParams({cliAuthorizationId:n,browserSecret:`<redacted>`}).toString(),{openerUrl:r,redactedUrl:m.toString()}}function ye(e,t,n){return e?`--no-browser was set`:n===`darwin`&&t.CODEX_SESSION_ID?`macOS Codex browser process boundary`:t.SSH_CONNECTION||t.SSH_CLIENT||t.SSH_TTY?`SSH/headless session detected`:(n===`linux`||n===`freebsd`)&&!t.DISPLAY&&!t.WAYLAND_DISPLAY?`no graphical display detected`:null}function be(e,t){return e===`darwin`?{command:`open`,arguments:[t]}:e===`win32`?{command:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,t]}:e===`linux`||e===`freebsd`?{command:`xdg-open`,arguments:[t]}:null}function xe(e,t){return new Promise((n,r)=>{ne(e,[...t],{timeout:5e3,windowsHide:!0},e=>e?r(e):n())})}var Se=100,Ce=3e4,we=6e4,Te=new oe;function A(){return _(g(ue()),`credentials.json`)}function Ee(e){return`OS keyring is unusable (${e}); the credential will be stored in ${A()} (mode 0600).\n`}async function De(e,t){let n=(await P())[e]?.[t];if(n!==void 0)return{record:{provider:`file`,value:n}};try{let n=await(await N(e,t)).getPassword()??void 0;return n===void 0?{}:{record:{provider:`keyring`,value:n}}}catch(e){return{keyringFailure:M(e)}}}async function Oe(e,t,n){if((await P())[e]?.[t]!==void 0)return await ke(e,t,n,`file store holds this account`);let r;try{let i=await N(e,t);if(await i.setPassword(n),await i.getPassword()===n)return await L(e,t,void 0),`keyring`;r=`Error: keyring readback did not match`}catch(e){r=M(e,[n])}return await ke(e,t,n,r)}async function ke(e,t,n,r){if(await L(e,t,n),(await P())[e]?.[t]!==n)throw Error(`credential storage did not confirm a durable write (keyring: ${r}; file: readback did not match)`);return`file`}async function Ae(e,t){try{let n=await N(e,t),r;try{await n.deleteCredential()}catch(e){r=e}let i;try{i=await n.getPassword()??void 0}catch(e){throw Error(`OS keyring removal outcome is unknown (${M(r??e)})`,{cause:e})}if(i!==void 0)throw Error(`OS keyring did not confirm removal (${M(r)})`,r===void 0?void 0:{cause:r})}finally{await L(e,t,void 0)}}async function j(e,t){let n=`${t}:probe:${S()}`,r=`aventure-cli-credential-probe:${S()}`,i;try{let t=await N(e,n);await t.setPassword(r);let a=await(await N(e,n)).getPassword(),o=await t.deleteCredential(),s=await(await N(e,n)).getPassword()??void 0;if(a!==r)i=`Error: probe readback did not match`;else if(!o||s!==void 0)i=`Error: probe cleanup was not confirmed`;else return{provider:`keyring`}}catch(e){i=M(e,[r])}try{await I(async()=>{await L(e,n,r);let t=(await P())[e]?.[n];if(await L(e,n,void 0),t!==r)throw Error(`probe readback did not match`)})}catch(e){throw Error(`credential storage is unavailable (keyring: ${i}; file ${A()}: ${M(e,[r])})`,{cause:e})}return{provider:`file`,keyringFailure:i}}function M(e,t=[]){if(!(e instanceof Error))return`Error`;let n=e.name||`Error`,[r=``]=w(e,t).trim().split(`
1
+ import{F as e,M as t,N as n,R as r,V as i,Y as a,Z as o,a as s,d as c,j as l,m as u,r as d,rt as f}from"./auth-o0Bk3f3c.js";import{T as p,b as m,i as h,s as ee,u as te}from"./person-owner-9MfK4f_5.js";import{execFile as ne}from"node:child_process";import{dirname as g,join as _}from"node:path";import{chmod as re,mkdir as v,readFile as y,rename as b,rm as x,stat as ie,writeFile as ae}from"node:fs/promises";import{AsyncLocalStorage as oe}from"node:async_hooks";import{randomUUID as S}from"node:crypto";import{homedir as se,platform as C}from"node:os";import{setTimeout as ce}from"node:timers/promises";function w(e,t=[]){let n=e instanceof Error?e.message:String(e);return u(n,t)}function le(e,t=[]){let n=u(e.title,t),r=u(e.detail?.trim()??``,t);return`${e.status} ${n}${r?` — ${r}`:``}`}function ue(){if(C()===`win32`){let e=process.env.APPDATA??_(se(),`AppData`,`Roaming`);return _(e,`aventure`,`config.json`)}let e=process.env.XDG_CONFIG_HOME??_(se(),`.config`);return _(e,`aventure`,`config.json`)}function de(){let e=process.env[o.authToken];return typeof e==`string`&&e.length>0?{present:!0,source:`env`}:{present:!1,source:null}}function T(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}function E(e){let t=e.trim();if(t.length===0)throw Error(`API host must not be blank`);let n=new URL(me(t)?t:`${he(t)}://${t}`),r=D(n.hostname);if(n.protocol!==`https:`&&n.protocol!==`http:`||n.username.length>0||n.password.length>0||n.pathname!==`/`&&n.pathname!==``||n.search.length>0||n.hash.length>0)throw Error(`API host must contain only an HTTP(S) host and optional port`);if(n.protocol===`http:`&&!r)throw Error(`stored credentials require HTTPS except for loopback API hosts`);return{host:n.host.toLowerCase(),origin:n.origin,isLoopback:r}}function fe(e){return{...e,host:E(e.host).origin}}function pe(e){let t=E(e);if(t.isLoopback)return`http://localhost:3000`;if(t.host===`api.aventure.vc`)return`https://aventure.vc`;throw Error(`no first-party browser origin is configured for API host ${t.host}`)}function me(e){return/^[a-z][a-z\d+.-]*:\/\//iu.test(e)}function he(e){let t=e.split(`/`,1)[0]?.toLowerCase()??``;try{return D(new URL(`http://${t}`).hostname)?`http`:`https`}catch{return`https`}}function D(e){let t=e.toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`0.0.0.0`||t===`[::1]`}var ge=2;function _e(e,t){return k(e,t).redactedUrl}async function ve(e,t,n){let r=k(e,t);return await O(new URL(r.openerUrl),n)}async function O(e,t){let n=t.environment??process.env,r=t.operatingSystem??C(),i=ye(t.noBrowser,n,r);if(i!==null)return{state:`skipped`,reason:i};let a=be(r,e.toString());if(a===null)return{state:`failed`,reason:`unsupported browser-opening platform: ${r}`};try{return await xe(a.command,a.arguments),{state:`opened`,reason:null}}catch{return{state:`failed`,reason:`browser opener failed`}}}function k(e,t){let{id:n,verificationUrl:r,pollSecret:i}=e,a,o;try{a=new URL(r),o=new URL(t)}catch{throw Error(`broker returned an invalid browser verification URL`)}if(o.username.length>0||o.password.length>0||o.pathname!==`/`||o.search.length>0||o.hash.length>0)throw Error(`configured browser origin must contain only an origin`);let s=D(o.hostname);if(o.protocol!==`https:`&&!(o.protocol===`http:`&&s))throw Error(`configured browser origin must use HTTPS except for loopback development`);let c=new URLSearchParams(a.hash.slice(1)),l=[...c.keys()],u=c.getAll(`cliAuthorizationId`),d=c.getAll(`browserSecret`),f=d[0]??``;if(a.origin!==o.origin||a.protocol!==o.protocol||a.username.length>0||a.password.length>0||a.pathname!==`/settings/developer`||a.search.length>0||l.length!==ge||u.length!==1||u[0]!==n||d.length!==1||f.length===0||i.length===0||f===i)throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let p;try{p=decodeURIComponent(r)}catch{throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`)}if(r.includes(i)||p.includes(i))throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let m=new URL(a);return m.hash=new URLSearchParams({cliAuthorizationId:n,browserSecret:`<redacted>`}).toString(),{openerUrl:r,redactedUrl:m.toString()}}function ye(e,t,n){return e?`--no-browser was set`:n===`darwin`&&t.CODEX_SESSION_ID?`macOS Codex browser process boundary`:t.SSH_CONNECTION||t.SSH_CLIENT||t.SSH_TTY?`SSH/headless session detected`:(n===`linux`||n===`freebsd`)&&!t.DISPLAY&&!t.WAYLAND_DISPLAY?`no graphical display detected`:null}function be(e,t){return e===`darwin`?{command:`open`,arguments:[t]}:e===`win32`?{command:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,t]}:e===`linux`||e===`freebsd`?{command:`xdg-open`,arguments:[t]}:null}function xe(e,t){return new Promise((n,r)=>{ne(e,[...t],{timeout:5e3,windowsHide:!0},e=>e?r(e):n())})}var Se=100,Ce=3e4,we=6e4,Te=new oe;function A(){return _(g(ue()),`credentials.json`)}function Ee(e){return`OS keyring is unusable (${e}); the credential will be stored in ${A()} (mode 0600).\n`}async function De(e,t){let n=(await P())[e]?.[t];if(n!==void 0)return{record:{provider:`file`,value:n}};try{let n=await(await N(e,t)).getPassword()??void 0;return n===void 0?{}:{record:{provider:`keyring`,value:n}}}catch(e){return{keyringFailure:M(e)}}}async function Oe(e,t,n){if((await P())[e]?.[t]!==void 0)return await ke(e,t,n,`file store holds this account`);let r;try{let i=await N(e,t);if(await i.setPassword(n),await i.getPassword()===n)return await L(e,t,void 0),`keyring`;r=`Error: keyring readback did not match`}catch(e){r=M(e,[n])}return await ke(e,t,n,r)}async function ke(e,t,n,r){if(await L(e,t,n),(await P())[e]?.[t]!==n)throw Error(`credential storage did not confirm a durable write (keyring: ${r}; file: readback did not match)`);return`file`}async function Ae(e,t){try{let n=await N(e,t),r;try{await n.deleteCredential()}catch(e){r=e}let i;try{i=await n.getPassword()??void 0}catch(e){throw Error(`OS keyring removal outcome is unknown (${M(r??e)})`,{cause:e})}if(i!==void 0)throw Error(`OS keyring did not confirm removal (${M(r)})`,r===void 0?void 0:{cause:r})}finally{await L(e,t,void 0)}}async function j(e,t){let n=`${t}:probe:${S()}`,r=`aventure-cli-credential-probe:${S()}`,i;try{let t=await N(e,n);await t.setPassword(r);let a=await(await N(e,n)).getPassword(),o=await t.deleteCredential(),s=await(await N(e,n)).getPassword()??void 0;if(a!==r)i=`Error: probe readback did not match`;else if(!o||s!==void 0)i=`Error: probe cleanup was not confirmed`;else return{provider:`keyring`}}catch(e){i=M(e,[r])}try{await I(async()=>{await L(e,n,r);let t=(await P())[e]?.[n];if(await L(e,n,void 0),t!==r)throw Error(`probe readback did not match`)})}catch(e){throw Error(`credential storage is unavailable (keyring: ${i}; file ${A()}: ${M(e,[r])})`,{cause:e})}return{provider:`file`,keyringFailure:i}}function M(e,t=[]){if(!(e instanceof Error))return`Error`;let n=e.name||`Error`,[r=``]=w(e,t).trim().split(`
2
2
  `,1);return r&&r!==n?`${n}: ${r}`:n}async function N(e,t){let n=C(),r=n===`linux`||n===`freebsd`?ye(!1,process.env,n):null;if(r!==null)throw Error(`OS keyring unlock prompt is unreachable (${r})`);let{AsyncEntry:i}=await import(`@napi-rs/keyring`);return new i(e,t)}async function P(){let e=A(),t;try{t=await y(e,`utf8`)}catch(e){if(T(e,`ENOENT`))return{};throw e}let n;try{n=JSON.parse(t)}catch(t){return await F(e,t)}return Me(n)?n:await F(e,void 0)}async function F(e,t){let n=`${e}.corrupt-${new Date().toISOString().replace(/[:.]/gu,`-`)}`;try{await b(e,n)}catch(t){if(T(t,`ENOENT`))return{};throw Error(`${e} is not a valid credential file and could not be moved aside`,{cause:t})}return i({component:a().bin[0],event:`credential_file_quarantined`,message:`${e} is not a valid credential file; moved it to ${n} and continuing with an empty file store`,...t===void 0?{}:{error:t}}),{}}async function I(e){if(Te.getStore()===!0)return await e();let t=`${A()}.lock`;await v(g(t),{recursive:!0,mode:448});let n=Date.now()+Ce,r=S();for(;;){try{await ae(t,r,{flag:`wx`,mode:384});break}catch(e){if(!T(e,`EEXIST`))throw e}if(await ie(t).then(e=>Date.now()-e.mtimeMs,()=>0)>we)await x(t,{force:!0});else if(Date.now()>n)throw Error(`credential store is locked by another CLI process (${t})`);else await ce(Se)}try{return await Te.run(!0,e)}finally{await y(t,`utf8`).catch(()=>``)===r&&await x(t,{force:!0})}}async function L(e,t,n){await I(async()=>await je(e,t,n))}async function je(e,t,n){let r=A(),i=await P(),a={...i[e]};if(n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,Object.keys(i).length===0){await x(r,{force:!0});return}await v(g(r),{recursive:!0,mode:448});let o=`${r}.${S()}.tmp`;await ae(o,`${JSON.stringify(i,null,2)}\n`,{mode:384}),await re(o,384),await b(o,r)}function Me(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`string`))}var R=m({createdAt:h({offset:!0}),description:p().nullish(),expiresAt:h({offset:!0}).nullish(),id:p().regex(/^ak_[0-9A-Fa-f]{32}$/),lastUsedAt:h({offset:!0}).nullish(),name:p(),revocationReason:p().nullish(),scopes:te(p()),status:ee([`ACTIVE`,`REVOKED`,`EXPIRED`]),subject:p(),updatedAt:h({offset:!0})}),z=`vc.aventure.aventure-cli`,B=`aventure-cli-personal-v1`;async function Ne(e,t,n){let r=H(e),i=Le(t,n),a;try{a=await Oe(z,r,i)}catch(e){throw Error(`${w(e,[i,t.secret])}; broker acknowledgment was withheld. Re-run auth status before retrying.`,{cause:e})}return{host:r,provider:a,activation:n,credential:t}}async function V(e){let t=H(e),n;try{n=await De(z,t)}catch(e){return Ie(w(e))}let{record:r,keyringFailure:i}=n;return r===void 0?i===void 0?{state:`missing`}:{state:`missing`,keyringFailure:i}:{state:`found`,stored:{host:t,provider:r.provider,...Re(r.value)}}}async function Pe(e){let t=await V(e);if(t.state!==`missing`)return t;try{let{keyringFailure:t}=await j(z,H(e));return t===void 0?{state:`missing`}:{state:`missing`,keyringFailure:t}}catch(e){return Ie(w(e))}}async function Fe(e){await Ae(z,H(e))}function H(e){return E(e).host}function Ie(e){return{state:`unavailable`,summary:e,cause:`storage`}}function Le(e,t){return`${B}:${t}\n${JSON.stringify(e.apiKey)}\n${e.secret}`}function Re(e){let t=e.indexOf(`
3
3
  `),n=t<0?-1:e.indexOf(`
4
- `,t+1),r=t<0?e:e.slice(0,t),i=r===`${B}:active`?`active`:`pending`;if(t<0||n<0||r!==`${B}:pending`&&r!==`${B}:active`)throw Error(`OS credential entry has an unsupported format`);let a=e.slice(n+1);if(a.length===0)throw Error(`OS credential entry has an empty secret`);let o;try{o=JSON.parse(e.slice(t+1,n))}catch(e){throw Error(`OS credential entry failed canonical schema validation`,{cause:e})}let s=R.safeParse(o);if(!s.success)throw Error(`OS credential entry failed canonical schema validation`,{cause:s.error});return{activation:i,credential:{apiKey:s.data,secret:a}}}async function ze(e){if(Be())return;let t=H(f().host);try{let n=await V(t);if(n.state===`unavailable`){r(Ve(`keyring`,Error(n.summary)));return}n.state===`found`&&n.stored.activation===`active`&&!Be()&&(process.env[o.authToken]=n.stored.credential.secret,e?.(`api-key`))}catch(e){i(Ve(`parse`,e))}}function Be(){return(process.env[o.authToken]?.trim().length??0)>0}function Ve(e,t){return{component:a().bin[0],event:`api_key_materialization_unavailable`,message:`saved API key could not be loaded; continuing with environment auth`,fields:{source:e},error:t}}var He=s.omit({mcpResource:!0}),U=`vc.aventure.aventure-cli.oauth`,Ue=`oauth:`,We=6e4;function Ge(e,t){let n=Z(t);return{client:e,expiresAt:ct(st(n)),tokens:n}}async function W(e,t){let n=q(e),r=nt(n,t),i;try{i=await Oe(U,X(n),r)}catch(e){throw Error(`OAuth credential could not be stored — ${w(e,[r,...Y(t.tokens)])}`,{cause:e})}return{host:n,provider:i,credential:rt(n,r)}}async function G(e){let t=q(e),n;try{n=await De(U,X(t))}catch(e){return{state:`unavailable`,summary:w(e)}}let{record:r,keyringFailure:i}=n;return r===void 0?i===void 0?{state:`missing`}:{state:`missing`,keyringFailure:i}:{state:`found`,stored:{host:t,provider:r.provider,credential:rt(t,r.value)}}}async function Ke(e){await Ae(U,X(q(e)))}async function qe(e){try{return await G(e)}catch(e){return{state:`invalid`,summary:w(e)}}}async function Je(e){let t=await qe(e);if(t.state!==`missing`)return t;let n=await Ye(e);return n.state===`unavailable`?n:n.keyringFailure===void 0?{state:`missing`}:{state:`missing`,keyringFailure:n.keyringFailure}}async function Ye(e){let t=q(e);try{return{state:`available`,...await j(U,X(t))}}catch(e){return{state:`unavailable`,summary:w(e)}}}function Xe(e){return K(e.authorizationServer,`authorization server`)}function Ze(e){if(URL.canParse(e.resource)&&new URL(e.resource).protocol===`http:`){let t=E(e.resource);if(t.isLoopback)return new URL(t.origin)}return K(e.resource,`resource`)}function Qe(e){if(e.clientId.trim()!==e.clientId||e.clientId.length===0)throw Error(`OAuth client ID must not be blank`);return e.clientId}function $e(e){if(e.scope.length===0||e.scope.some(e=>e.trim()!==e||e.length===0)||new Set(e.scope).size!==e.scope.length)throw Error(`OAuth scope must contain unique non-blank values`);return e.scope}function K(e,t,n=!1){let r;try{r=new URL(e)}catch(e){throw Error(`OAuth ${t} is not a valid URL`,{cause:e})}if(r.protocol!==`https:`||r.username.length>0||r.password.length>0||!n&&r.search.length>0||r.hash.length>0)throw Error(`OAuth ${t} must be an HTTPS URL without credentials${n?``:`, query`} or fragment`);return r}function q(e){return E(e).host}function J(e){return new Date(e.expiresAt).getTime()-We<=Date.now()}function et(e){let t=tt(e.tokens.id_token)??tt(e.tokens.access_token),n=t?.email;return{subject:t?.sub??null,email:typeof n==`string`?n:null}}function tt(e){if(e!==void 0)try{return l(e)}catch{return}}function Y(e){return[e.access_token,e.refresh_token,e.id_token]}function X(e){return`${Ue}${e}`}function nt(e,t){return JSON.stringify({client:it(e,t.client),expiresAt:lt(t.expiresAt),tokens:Z(t.tokens)})}function rt(e,t){let n;try{n=JSON.parse(t)}catch(e){throw Error(`OS OAuth credential entry failed schema validation`,{cause:e})}if(!dt(n))throw Error(`OS OAuth credential entry failed schema validation`);return{client:it(e,at(n.client)),expiresAt:lt(n.expiresAt),tokens:Z(ot(n.tokens))}}function it(e,t){if(q(t.resource)!==e)throw Error(`OAuth client resource must match the credential API host`);return t}function at(e){let t=He.safeParse(e);if(!t.success)throw Error(`OS OAuth credential entry failed canonical client validation`,{cause:t.error});return t.data}function ot(e){let t=d.safeParse(e);if(!t.success)throw Error(`OS OAuth credential entry failed OAuth token validation`,{cause:t.error});return t.data}function Z(e){if(!ut(e.access_token)||e.token_type.trim().toLowerCase()!==`bearer`)throw Error(`OAuth token response must contain a bearer access token`);if(e.refresh_token!==void 0&&!ut(e.refresh_token))throw Error(`OAuth token response has an invalid refresh token`);return st(e),e}function st(e){let t=e.expires_in;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<=0)throw Error(`OAuth token response must contain a positive expires_in`);return t}function ct(e){let t=new Date(Date.now()+e*1e3);if(!Number.isFinite(t.getTime()))throw Error(`OAuth token response has an expiry outside the supported date range`);return t.toISOString()}function lt(e){if(typeof e!=`string`)throw Error(`OS OAuth credential entry has an invalid absolute expiry`);let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw Error(`OS OAuth credential entry has an invalid absolute expiry`);return e}function ut(e){return e.trim()===e&&e.length>0}function dt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function ft(r,s){if($())return;let l=async(e,t,n,o=!1)=>{if(await ze(s),!$())throw o?t:mt(e,r,t,n);i({component:r??a().bin[0],event:`oauth_credential_bypassed`,message:`OAuth sign-in is unavailable (${e}); using the stored API key.`,...t===void 0?{}:{error:Error(w(t,Q(n)))}})},u=async(e,t,n)=>{let o=await G(e.host).catch(()=>void 0);if(o?.state===`found`&&o.stored.credential.tokens.access_token!==e.credential.tokens.access_token)return await d(o.stored,!1);try{await Ke(e.host)}catch(n){i({component:r??a().bin[0],event:`oauth_credential_retire_failed`,message:`the saved OAuth credential is dead (${t}) but could not be removed`,error:Error(w(n,Q(e)))})}await l(t,n,e)},d=async(r,i)=>{let a=(e,t)=>i?u(r,e,t):l(e,t,r),d=r.credential;if(J(d)){if(d.tokens.refresh_token===void 0)return await a(`the saved OAuth credential has expired`);try{d=await pt(r)}catch(t){return t instanceof n?await a(`aVenture sign-in rejected the saved refresh token`,t):await l(`the saved OAuth credential could not be renewed`,t,r,!(t instanceof e))}}let f;try{f=await c(d.tokens.access_token,new URL(d.client.resource))!==null}catch(e){return e instanceof t?await a(`the saved OAuth credential is malformed`,e):await l(`the saved OAuth credential could not be verified`,e,r,!0)}if(!f)return await a(`the saved OAuth credential was rejected`);$()||(process.env[o.authToken]=d.tokens.access_token,s?.(`oauth`))},p;try{p=q(f().host)}catch(e){throw mt(`the API host could not select its OAuth credential`,r,e)}let m;try{m=await G(p)}catch(e){return await l(`the saved OAuth credential is invalid or expired`,e)}if(m.state!==`missing`){if(m.state===`unavailable`)return await l(`the saved OAuth credential could not be read`,Error(m.summary));await d(m.stored,!0)}}async function pt(e){return await I(async()=>{let t=await G(e.host),n=t.state===`found`?t.stored:e;if(!J(n.credential))return n.credential;let{renewOAuthTokens:r}=await import(`./oauth-login-Be_T8wJV.js`),o=Ge(n.credential.client,await r(n));try{await W(e.host,o)}catch(e){i({component:a().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(w(e,Y(o.tokens)))})}return o})}function Q(e){return e===void 0?[]:Y(e.credential.tokens)}function $(){return(process.env[o.authToken]?.trim().length??0)>0}function mt(e,t,n,r){let i=n===void 0?``:` — ${w(n,Q(r))}`,o=t??a().bin[0];return Error(`OAuth sign-in is required: ${e}. Run \`${o} auth login\` before retrying.${i}`)}export{fe as A,Ne as C,ve as D,O as E,w as M,le as N,_e as O,V as S,Ee as T,W as _,Ke as a,Fe as b,J as c,et as d,Ze as f,K as g,Ye as h,Ge as i,de as j,pe as k,Xe as l,Y as m,pt as n,qe as o,$e as p,q as r,Je as s,ft as t,Qe as u,ze as v,R as w,Pe as x,H as y};
4
+ `,t+1),r=t<0?e:e.slice(0,t),i=r===`${B}:active`?`active`:`pending`;if(t<0||n<0||r!==`${B}:pending`&&r!==`${B}:active`)throw Error(`OS credential entry has an unsupported format`);let a=e.slice(n+1);if(a.length===0)throw Error(`OS credential entry has an empty secret`);let o;try{o=JSON.parse(e.slice(t+1,n))}catch(e){throw Error(`OS credential entry failed canonical schema validation`,{cause:e})}let s=R.safeParse(o);if(!s.success)throw Error(`OS credential entry failed canonical schema validation`,{cause:s.error});return{activation:i,credential:{apiKey:s.data,secret:a}}}async function ze(e){if(Be())return;let t=H(f().host);try{let n=await V(t);if(n.state===`unavailable`){r(Ve(`keyring`,Error(n.summary)));return}n.state===`found`&&n.stored.activation===`active`&&!Be()&&(process.env[o.authToken]=n.stored.credential.secret,e?.(`api-key`))}catch(e){i(Ve(`parse`,e))}}function Be(){return(process.env[o.authToken]?.trim().length??0)>0}function Ve(e,t){return{component:a().bin[0],event:`api_key_materialization_unavailable`,message:`saved API key could not be loaded; continuing with environment auth`,fields:{source:e},error:t}}var He=s.omit({mcpResource:!0}),U=`vc.aventure.aventure-cli.oauth`,Ue=`oauth:`,We=6e4;function Ge(e,t){let n=Z(t);return{client:e,expiresAt:ct(st(n)),tokens:n}}async function W(e,t){let n=q(e),r=nt(n,t),i;try{i=await Oe(U,X(n),r)}catch(e){throw Error(`OAuth credential could not be stored — ${w(e,[r,...Y(t.tokens)])}`,{cause:e})}return{host:n,provider:i,credential:rt(n,r)}}async function G(e){let t=q(e),n;try{n=await De(U,X(t))}catch(e){return{state:`unavailable`,summary:w(e)}}let{record:r,keyringFailure:i}=n;return r===void 0?i===void 0?{state:`missing`}:{state:`missing`,keyringFailure:i}:{state:`found`,stored:{host:t,provider:r.provider,credential:rt(t,r.value)}}}async function Ke(e){await Ae(U,X(q(e)))}async function qe(e){try{return await G(e)}catch(e){return{state:`invalid`,summary:w(e)}}}async function Je(e){let t=await qe(e);if(t.state!==`missing`)return t;let n=await Ye(e);return n.state===`unavailable`?n:n.keyringFailure===void 0?{state:`missing`}:{state:`missing`,keyringFailure:n.keyringFailure}}async function Ye(e){let t=q(e);try{return{state:`available`,...await j(U,X(t))}}catch(e){return{state:`unavailable`,summary:w(e)}}}function Xe(e){return K(e.authorizationServer,`authorization server`)}function Ze(e){if(URL.canParse(e.resource)&&new URL(e.resource).protocol===`http:`){let t=E(e.resource);if(t.isLoopback)return new URL(t.origin)}return K(e.resource,`resource`)}function Qe(e){if(e.clientId.trim()!==e.clientId||e.clientId.length===0)throw Error(`OAuth client ID must not be blank`);return e.clientId}function $e(e){if(e.scope.length===0||e.scope.some(e=>e.trim()!==e||e.length===0)||new Set(e.scope).size!==e.scope.length)throw Error(`OAuth scope must contain unique non-blank values`);return e.scope}function K(e,t,n=!1){let r;try{r=new URL(e)}catch(e){throw Error(`OAuth ${t} is not a valid URL`,{cause:e})}if(r.protocol!==`https:`||r.username.length>0||r.password.length>0||!n&&r.search.length>0||r.hash.length>0)throw Error(`OAuth ${t} must be an HTTPS URL without credentials${n?``:`, query`} or fragment`);return r}function q(e){return E(e).host}function J(e){return new Date(e.expiresAt).getTime()-We<=Date.now()}function et(e){let t=tt(e.tokens.id_token)??tt(e.tokens.access_token),n=t?.email;return{subject:t?.sub??null,email:typeof n==`string`?n:null}}function tt(e){if(e!==void 0)try{return l(e)}catch{return}}function Y(e){return[e.access_token,e.refresh_token,e.id_token]}function X(e){return`${Ue}${e}`}function nt(e,t){return JSON.stringify({client:it(e,t.client),expiresAt:lt(t.expiresAt),tokens:Z(t.tokens)})}function rt(e,t){let n;try{n=JSON.parse(t)}catch(e){throw Error(`OS OAuth credential entry failed schema validation`,{cause:e})}if(!dt(n))throw Error(`OS OAuth credential entry failed schema validation`);return{client:it(e,at(n.client)),expiresAt:lt(n.expiresAt),tokens:Z(ot(n.tokens))}}function it(e,t){if(q(t.resource)!==e)throw Error(`OAuth client resource must match the credential API host`);return t}function at(e){let t=He.safeParse(e);if(!t.success)throw Error(`OS OAuth credential entry failed canonical client validation`,{cause:t.error});return t.data}function ot(e){let t=d.safeParse(e);if(!t.success)throw Error(`OS OAuth credential entry failed OAuth token validation`,{cause:t.error});return t.data}function Z(e){if(!ut(e.access_token)||e.token_type.trim().toLowerCase()!==`bearer`)throw Error(`OAuth token response must contain a bearer access token`);if(e.refresh_token!==void 0&&!ut(e.refresh_token))throw Error(`OAuth token response has an invalid refresh token`);return st(e),e}function st(e){let t=e.expires_in;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<=0)throw Error(`OAuth token response must contain a positive expires_in`);return t}function ct(e){let t=new Date(Date.now()+e*1e3);if(!Number.isFinite(t.getTime()))throw Error(`OAuth token response has an expiry outside the supported date range`);return t.toISOString()}function lt(e){if(typeof e!=`string`)throw Error(`OS OAuth credential entry has an invalid absolute expiry`);let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw Error(`OS OAuth credential entry has an invalid absolute expiry`);return e}function ut(e){return e.trim()===e&&e.length>0}function dt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function ft(r,s){if($())return;let l=async(e,t,n,o=!1)=>{if(await ze(s),!$())throw o?t:mt(e,r,t,n);i({component:r??a().bin[0],event:`oauth_credential_bypassed`,message:`OAuth sign-in is unavailable (${e}); using the stored API key.`,...t===void 0?{}:{error:Error(w(t,Q(n)))}})},u=async(e,t,n)=>{let o=await G(e.host).catch(()=>void 0);if(o?.state===`found`&&o.stored.credential.tokens.access_token!==e.credential.tokens.access_token)return await d(o.stored,!1);try{await Ke(e.host)}catch(n){i({component:r??a().bin[0],event:`oauth_credential_retire_failed`,message:`the saved OAuth credential is dead (${t}) but could not be removed`,error:Error(w(n,Q(e)))})}await l(t,n,e)},d=async(r,i)=>{let a=(e,t)=>i?u(r,e,t):l(e,t,r),d=r.credential;if(J(d)){if(d.tokens.refresh_token===void 0)return await a(`the saved OAuth credential has expired`);try{d=await pt(r)}catch(t){return t instanceof n?await a(`aVenture sign-in rejected the saved refresh token`,t):await l(`the saved OAuth credential could not be renewed`,t,r,!(t instanceof e))}}let f;try{f=await c(d.tokens.access_token,new URL(d.client.resource))!==null}catch(e){return e instanceof t?await a(`the saved OAuth credential is malformed`,e):await l(`the saved OAuth credential could not be verified`,e,r,!0)}if(!f)return await a(`the saved OAuth credential was rejected`);$()||(process.env[o.authToken]=d.tokens.access_token,s?.(`oauth`))},p;try{p=q(f().host)}catch(e){throw mt(`the API host could not select its OAuth credential`,r,e)}let m;try{m=await G(p)}catch(e){return await l(`the saved OAuth credential is invalid or expired`,e)}if(m.state!==`missing`){if(m.state===`unavailable`)return await l(`the saved OAuth credential could not be read`,Error(m.summary));await d(m.stored,!0)}}async function pt(e){return await I(async()=>{let t=await G(e.host),n=t.state===`found`?t.stored:e;if(!J(n.credential))return n.credential;let{renewOAuthTokens:r}=await import(`./oauth-login-BiCvRHKa.js`),o=Ge(n.credential.client,await r(n));try{await W(e.host,o)}catch(e){i({component:a().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(w(e,Y(o.tokens)))})}return o})}function Q(e){return e===void 0?[]:Y(e.credential.tokens)}function $(){return(process.env[o.authToken]?.trim().length??0)>0}function mt(e,t,n,r){let i=n===void 0?``:` — ${w(n,Q(r))}`,o=t??a().bin[0];return Error(`OAuth sign-in is required: ${e}. Run \`${o} auth login\` before retrying.${i}`)}export{fe as A,Ne as C,ve as D,O as E,w as M,le as N,_e as O,V as S,Ee as T,W as _,Ke as a,Fe as b,J as c,et as d,Ze as f,K as g,Ye as h,Ge as i,de as j,pe as k,Xe as l,Y as m,pt as n,qe as o,$e as p,q as r,Je as s,ft as t,Qe as u,ze as v,R as w,Pe as x,H as y};
@@ -0,0 +1 @@
1
+ import{i as e}from"./oauth-login-CP2Hh0U0.js";export{e as renewOAuthTokens};
@@ -1,4 +1,4 @@
1
- import{I as e,M as t,P as n,d as r,i,n as a,ot as o,p as s,r as c,rt as l,s as u,st as d,t as f}from"./auth-BGCkxIpd.js";import{A as ee,E as te,M as p,N as ne,T as re,_ as ie,c as ae,f as m,g as h,h as g,i as oe,l as _,m as v,n as y,o as b,p as x,r as se,u as S}from"./oauth-bearer-credential-C6qZqSzH.js";import{S as ce,q as le,t as ue}from"./index.node-h9yDhQev.js";import{once as de}from"node:events";import{stderr as C}from"node:process";import{createServer as fe}from"node:http";import{randomBytes as pe,timingSafeEqual as me}from"node:crypto";import{setTimeout as he}from"node:timers/promises";function ge(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var w=`code`,T=`S256`;function E(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&ge(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function D(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:O(i,a,n);return;case`client_secret_post`:k(i,a,r);return;case`none`:A(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function O(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function k(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function A(e,t){t.set(`client_id`,e)}async function j(t){let r=t instanceof Response?t.status:void 0,i=t instanceof Response?await t.text():t;try{let{error:t,error_description:r,error_uri:a}=f.parse(JSON.parse(i));return new(n[t]||e)(r||``,a)}catch(t){let n=`${r?`HTTP ${r}: `:``}Invalid OAuth error response: ${t}. Raw body: ${i}`;return new e(n)}}async function M(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?M(e,void 0,n):void 0;throw r}}function N(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function P(e,{fetchFn:t=fetch,protocolVersion:n=ce}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},o=N(e);for(let{url:e,type:n}of o){let o=await M(e,r,t);if(o){if(!o.ok){if(await o.body?.cancel(),o.status>=400&&o.status<500)continue;throw Error(`HTTP ${o.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?a.parse(await o.json()):i.parse(await o.json())}}}function F(e){return typeof e==`string`?e:e.href}async function I(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(w))throw Error(`Incompatible auth server: does not support response type ${w}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(T))throw Error(`Incompatible auth server: does not support code challenge method ${T}`)}else s=new URL(`/authorize`,e);let c=await ue(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,w),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,T),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,F(o)),{authorizationUrl:s,codeVerifier:l}}function L(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function R(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,F(a)),i?await i(l,n,s,t):r&&D(E(r,t?.token_endpoint_auth_methods_supported??[]),r,l,n);let u=await(o??fetch)(s,{method:`POST`,headers:l,body:n});if(!u.ok)throw await j(u);return c.parse(await u.json())}async function _e(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){return R(e,{metadata:t,tokenRequestParams:L(r,i,a),clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:c})}async function ve(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await R(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}var ye=5e3,be=500,z=`Approval poll was interrupted; retrying.
1
+ import{I as e,M as t,P as n,d as r,i,n as a,ot as o,p as s,r as c,rt as l,s as u,st as d,t as f}from"./auth-o0Bk3f3c.js";import{A as ee,E as te,M as p,N as ne,T as re,_ as ie,c as ae,f as m,g as h,h as g,i as oe,l as _,m as v,n as y,o as b,p as x,r as se,u as S}from"./oauth-bearer-credential-boAXSRDY.js";import{S as ce,q as le,t as ue}from"./index.node-Dm8yE-MM.js";import{once as de}from"node:events";import{stderr as C}from"node:process";import{createServer as fe}from"node:http";import{randomBytes as pe,timingSafeEqual as me}from"node:crypto";import{setTimeout as he}from"node:timers/promises";function ge(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var w=`code`,T=`S256`;function E(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&ge(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function D(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:O(i,a,n);return;case`client_secret_post`:k(i,a,r);return;case`none`:A(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function O(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function k(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function A(e,t){t.set(`client_id`,e)}async function j(t){let r=t instanceof Response?t.status:void 0,i=t instanceof Response?await t.text():t;try{let{error:t,error_description:r,error_uri:a}=f.parse(JSON.parse(i));return new(n[t]||e)(r||``,a)}catch(t){let n=`${r?`HTTP ${r}: `:``}Invalid OAuth error response: ${t}. Raw body: ${i}`;return new e(n)}}async function M(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?M(e,void 0,n):void 0;throw r}}function N(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function P(e,{fetchFn:t=fetch,protocolVersion:n=ce}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},o=N(e);for(let{url:e,type:n}of o){let o=await M(e,r,t);if(o){if(!o.ok){if(await o.body?.cancel(),o.status>=400&&o.status<500)continue;throw Error(`HTTP ${o.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?a.parse(await o.json()):i.parse(await o.json())}}}function F(e){return typeof e==`string`?e:e.href}async function I(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(w))throw Error(`Incompatible auth server: does not support response type ${w}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(T))throw Error(`Incompatible auth server: does not support code challenge method ${T}`)}else s=new URL(`/authorize`,e);let c=await ue(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,w),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,T),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,F(o)),{authorizationUrl:s,codeVerifier:l}}function L(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function R(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,F(a)),i?await i(l,n,s,t):r&&D(E(r,t?.token_endpoint_auth_methods_supported??[]),r,l,n);let u=await(o??fetch)(s,{method:`POST`,headers:l,body:n});if(!u.ok)throw await j(u);return c.parse(await u.json())}async function _e(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){return R(e,{metadata:t,tokenRequestParams:L(r,i,a),clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:c})}async function ve(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await R(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}var ye=5e3,be=500,z=`Approval poll was interrupted; retrying.
2
2
  `,xe=`urn:ietf:params:oauth:grant-type:device_code`;function B(e){let t=Reflect.get(e,`device_authorization_endpoint`);if(typeof t!=`string`)throw Error(`OAuth authorization-server metadata lacks device_authorization_endpoint`);return h(t,`device authorization endpoint`,!0)}async function Se(e,t){let n=await fetch(B(t),{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:S(e),scope:x(e).join(` `),resource:m(e).toString()})});if(!n.ok)throw Error(`device authorization endpoint answered ${n.status}`);return Ce(await V(n,`device authorization`),Date.now())}async function V(e,t){try{return await e.json()}catch(n){throw Error(`${t} endpoint answered ${e.status} without a JSON body`,{cause:n})}}function Ce(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:h(c,`verification URI`,!0),expiresAt:t+o*1e3,intervalMilliseconds:(typeof s==`number`&&s>=0?s:5)*1e3}}async function we(e,t,n){let r=h(t.token_endpoint,`token endpoint`,!0),i=n.intervalMilliseconds,a=null;for(;Date.now()<n.expiresAt;){await he(i);let t;try{t=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:S(e),grant_type:xe,device_code:n.deviceCode})})}catch(e){a=`the token endpoint was unreachable — ${p(e)}`,C.write(z);continue}if(t.status>=be){await t.body?.cancel(),a=`the token endpoint answered ${t.status}`,C.write(z);continue}a=null;let o=await V(t,`token`);if(t.ok){let e=c.safeParse(o);if(!e.success)throw Error(`token endpoint returned an invalid token response`);return e.data}let s=f.safeParse(o),l=s.success?s.data.error:`HTTP ${t.status}`;if(l!==`authorization_pending`){if(l===`slow_down`){i+=ye;continue}throw Error(l===`access_denied`?`the sign-in was denied in the browser`:l===`expired_token`?`the device code expired before approval`:`token endpoint answered ${l}`)}}throw Error(a===null?`the device code expired before approval`:`the device code expired before approval — last failure: ${a}`)}var Te=3e5;function Ee(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 De(e,t){let n,r=new Promise(e=>{n=e}),i=fe((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||!me(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}i.statusCode=200,i.end(`OAuth authorization completed. Return to the CLI.`),n({state:`code`,authorizationCode:u})});i.on(`error`,e=>n({state:`failed`,message:`OAuth callback listener failed: ${p(e)}`}));try{let t=de(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`}),Te)})]).finally(()=>{e!==void 0&&clearTimeout(e)})},close:async()=>await H(i)}}catch(e){throw i.listening&&await H(i),e}}function H(e){return new Promise((t,n)=>{e.close(e=>e===void 0?t():n(e))})}var U=`the OAuth credential is valid, but the API refused this account (HTTP 403); signing in again will not change that`;async function Oe(e){let n;try{n=se(l().host)}catch(e){return o(`auth login: invalid API host — ${p(e)}`)}let i=await b(n);if(i.state===`missing`)return G(n,e);if(i.state===`unavailable`)return o(`auth login: ${i.summary}`);if(i.state===`invalid`)return G(n,e,`Saved OAuth credential cannot be read — ${i.summary}`);let{stored:a}=i;if(ae(a.credential))return await W(a,e);let s;try{s=await r(a.credential.tokens.access_token,m(a.credential.client))}catch(r){return r instanceof t?G(n,e,`Saved OAuth credential was rejected`):o(`auth login: saved OAuth credential could not be verified — ${p(r,v(a.credential.tokens))}`)}return s===`forbidden`?o(`auth login: ${U}`):s===null?G(n,e,`Saved OAuth credential was rejected`):d(`OAuth CLI access token is already stored and verified.`,$(a))}async function W(e,t){let n=await g(e.host);if(n.state===`unavailable`)return o(`auth login: ${n.summary}`);let{tokens:r}=e.credential;if(r.refresh_token===void 0)return G(e.host,t,`Saved OAuth access token expired`,n);let i;try{i=await y(e)}catch(i){return G(e.host,t,`Saved OAuth credential could not be renewed — ${p(i,v(r))}`,n)}J(n);let a=await Q(e.host,i,`OAuth CLI access token renewed and verified.`);if(!a.ok)return a;let s=await Z(i);return s.state===`failed`?o(`auth login: ${s.summary}`):s.state===`rejected`?G(e.host,t,`Renewed OAuth access token was rejected`,n):a}async function G(e,t,n,r){let i=r??await g(e);if(i.state===`unavailable`)return o(`auth login: ${i.summary}`);J(i),n!==void 0&&C.write(`${n}; continuing to browser sign-in.\n`);let a;try{let e=(await Y()).oauthClient;if(e==null)throw Error(`the API does not advertise an OAuth CLI client`);a=e}catch(e){return o(`auth login: OAuth configuration is unavailable — ${p(e)}`)}let s;try{s=await X(a)}catch(e){return o(`auth login: OAuth authorization-server discovery failed — ${p(e)}`)}if(t.noBrowser)return await K(e,a,s);let c=pe(32).toString(`base64url`),l;try{l=await De(Ee(a),c);let t=await I(_(a),{metadata:s,clientInformation:{client_id:S(a)},redirectUrl:l.redirectUri,resource:m(a),scope:x(a).join(` `),state:c}),n=await te(t.authorizationUrl,{noBrowser:!1});if(n.state!==`opened`)return await l.close(),l=void 0,C.write(`Browser not opened automatically (${n.reason}).\n`),await K(e,a,s);C.write(`Browser sign-in opened: choose the account, then approve. Waiting for the loopback callback...
3
3
  `);let r=await l.waitForAuthorizationCode();if(r.state===`timed-out`)return await l.close(),l=void 0,C.write(`Browser sign-in was not completed; continuing with a device code.
4
4
  `),await K(e,a,s);if(r.state===`failed`)return o(`auth login: ${r.message}`);let i;try{i=await _e(_(a),{metadata:s,clientInformation:{client_id:S(a)},authorizationCode:r.authorizationCode,codeVerifier:t.codeVerifier,redirectUri:l.redirectUri,resource:m(a)})}catch(e){return o(`auth login: OAuth token exchange failed — ${p(e,[r.authorizationCode,t.codeVerifier])}`)}return await q(e,a,i)}catch(e){return o(`auth login: OAuth browser authorization failed — ${p(e)}`)}finally{await l?.close()}}async function K(e,t,n){let r;try{r=await Se(t,n)}catch(e){return o(`auth login: OAuth device authorization request failed — ${p(e)}`)}C.write([`Sign-in URL (works on any device): ${r.verificationUri.toString()}`,`Confirm that the page shows code ${r.userCode} before approving.`,"That page approves with the account already signed in there; to pick an account, run `auth login` on a machine with a browser.",`Waiting for approval...