@aventurevc/aventure-cli 0.8.154 → 0.8.156

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/aventure-cli/index.js +1 -1
  2. package/dist/aventure-cli/unified-operations.json +1 -1
  3. package/dist/chunks/{api-key-bearer-credential-CW5W3VVg.js → api-key-bearer-credential-4LScynXy.js} +1 -1
  4. package/dist/chunks/api-key-bearer-credential-CA4OpfsH.js +1 -0
  5. package/dist/chunks/{aventure-cli-MEA66dmm.js → aventure-cli-BemgrYF3.js} +42 -42
  6. package/dist/chunks/{cli-help-policy-BbLTU6HE.js → cli-help-policy-3jSdulx3.js} +1 -1
  7. package/dist/chunks/contract-HStzXwji.js +22 -0
  8. package/dist/chunks/detail-D09DdW-w.js +1 -0
  9. package/dist/chunks/detail-Dobtzmp5.js +1 -0
  10. package/dist/chunks/dist-Q4PISeeD.js +96 -0
  11. package/dist/chunks/{env-ClsLmXWa.js → env-XeZDJpn3.js} +1 -1
  12. package/dist/chunks/logging-BRs4ijNm.js +1 -0
  13. package/dist/chunks/{logging-sKoOD-tO.js → logging-DAGOYqaQ.js} +1 -1
  14. package/dist/chunks/oauth-bearer-credential-Danq0Rcg.js +1 -0
  15. package/dist/chunks/{oauth-bearer-credential-_hReIflB.js → oauth-bearer-credential-kUzaF0hp.js} +2 -2
  16. package/dist/chunks/{oauth-login-BTK7bnlR.js → oauth-login-CVIyq_3x.js} +2 -2
  17. package/dist/chunks/oauth-login-DdhJJOVp.js +1 -0
  18. package/dist/chunks/openapi-commands-BegEQVj4.js +1 -0
  19. package/dist/chunks/{openapi-commands-CuOsKOYe.js → openapi-commands-BrF8nKmC.js} +1 -1
  20. package/dist/chunks/{output-mode-sM_EbDW_.js → output-mode-CRxIcJgT.js} +1 -1
  21. package/dist/chunks/output-mode-DMWG6UcE.js +1 -0
  22. package/dist/chunks/{output-spill-D0GZ7YT_.js → output-spill-CtnznV5-.js} +1 -1
  23. package/dist/chunks/provider-catalog-BcVhP5ot.js +1 -0
  24. package/dist/chunks/response-problem-BoXoN3go.js +1 -0
  25. package/dist/chunks/{result-envelope-DTzTOcab.js → result-envelope-q4j0rGDr.js} +1 -1
  26. package/dist/chunks/startup-auth-ByS4CwxH.js +1 -0
  27. package/dist/chunks/{startup-auth-GYDuOgMb.js → startup-auth-ChbX0MJF.js} +1 -1
  28. package/dist/chunks/{text-field-r9akQrZl.js → text-field-BoNdbrtA.js} +1 -1
  29. package/dist/chunks/text-field-CxrRvM47.js +1 -0
  30. package/dist/chunks/tool-policy-aPyLxMku.js +1 -0
  31. package/package.json +3 -3
  32. package/scripts/install-zsh-completion-loader.mjs +0 -1
  33. package/dist/chunks/api-key-bearer-credential-DNxYcBcd.js +0 -1
  34. package/dist/chunks/contract-BjZg8t8U.js +0 -22
  35. package/dist/chunks/detail-BAUbCLgG.js +0 -1
  36. package/dist/chunks/detail-BnHDsTdz.js +0 -1
  37. package/dist/chunks/dist-qYT7b7rJ.js +0 -96
  38. package/dist/chunks/logging-B3nxJH8H.js +0 -1
  39. package/dist/chunks/oauth-bearer-credential-BeLpql1L.js +0 -1
  40. package/dist/chunks/oauth-login-ChJumDeg.js +0 -1
  41. package/dist/chunks/openapi-commands--bnPRBsW.js +0 -1
  42. package/dist/chunks/output-mode-Bispjv2H.js +0 -1
  43. package/dist/chunks/provider-catalog-DuLSGg1k.js +0 -1
  44. package/dist/chunks/response-problem-DCBMY8Lr.js +0 -1
  45. package/dist/chunks/startup-auth-AXrwl1fP.js +0 -1
  46. package/dist/chunks/text-field-CJvckkTy.js +0 -1
  47. package/dist/chunks/tool-policy-Cg0XvZMq.js +0 -1
@@ -1,39 +1,39 @@
1
- import{n as e,o as t,r as n,t as r}from"./commander-BB7CDPLs.js";import{i,o as a}from"./logging-sKoOD-tO.js";import{M as o,O as s,i as c,o as l,v as u,w as d,y as f}from"./person-owner-BJgNYLKX.js";import{Ar as p,Dr as m,Er as h,Lr as ee,Mr as te,Or as ne,Rr as re,kr as ie}from"./dist-qYT7b7rJ.js";import{n as ae,r as g,s as _,u as oe}from"./result-envelope-DTzTOcab.js";import{i as se,l as v,o as ce,r as le,s as ue,t as y}from"./env-ClsLmXWa.js";import{a as b,n as de,r as fe,t as pe}from"./package-DPDX5zmx.js";import{S as me,d as he,f as ge,o as _e,p as ve,r as ye,s as be,t as xe}from"./tool-policy-Cg0XvZMq.js";import{i as Se,r as Ce}from"./response-problem-DCBMY8Lr.js";import{n as we}from"./output-spill-D0GZ7YT_.js";import{a as Te,c as Ee,d as De,f as Oe,i as ke,l as Ae,m as je,n as x,o as Me,r as Ne,s as Pe,u as Fe,y as Ie}from"./contract-BjZg8t8U.js";import{a as Le,c as Re,i as ze,l as Be,n as Ve,s as He,t as Ue}from"./cli-help-policy-BbLTU6HE.js";import{S as We,_ as Ge,a as Ke,g as S,h as qe,i as Je,m as Ye,n as Xe,p as Ze,r as Qe,s as $e,t as et,v as tt,x as C,y as nt}from"./api-key-bearer-credential-CW5W3VVg.js";import{a as rt,c as it,d as at,g as ot,l as st,m as ct,o as lt,s as ut,t as dt,u as ft}from"./oauth-bearer-credential-_hReIflB.js";import{n as pt,r as mt,t as ht}from"./oauth-login-BTK7bnlR.js";import{a as gt,c as _t,d as vt,i as yt,l as bt,n as xt,o as St,s as Ct,t as wt,u as Tt}from"./startup-auth-GYDuOgMb.js";import{n as Et,t as w}from"./openapi-commands-CuOsKOYe.js";import{i as T,r as Dt,t as E}from"./output-mode-sM_EbDW_.js";import{spawnSync as Ot}from"node:child_process";import{basename as D,dirname as O,relative as kt,resolve as k,sep as At}from"node:path";import{copyFileSync as jt,existsSync as A,lstatSync as Mt,mkdirSync as Nt,mkdtempSync as Pt,readFileSync as Ft,readdirSync as It,readlinkSync as Lt,realpathSync as Rt,renameSync as zt,symlinkSync as Bt,writeFileSync as Vt}from"node:fs";import j,{stderr as M,stdin as Ht}from"node:process";import{TextDecoder as Ut,inspect as Wt}from"node:util";import{homedir as Gt,hostname as Kt,platform as qt}from"node:os";import{fileURLToPath as Jt}from"node:url";import{setTimeout as Yt}from"node:timers/promises";import{randomUUID as Xt,webcrypto as Zt}from"node:crypto";import{readFile as Qt}from"node:fs/promises";import{createInterface as $t}from"node:readline/promises";function en(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{...g(`${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 _(`Environment-bound options applied`,r)}function tn(e,t,n){if(!P(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||!gn(n,r.name))continue;let a=hn(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 nn(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 rn(e,t,n,r=!1){if(r||!N(t)||!Array.isArray(n))return bn(e,t,n);for(let[r,i]of n.entries()){let n=bn(e,t,i,r);if(!n.ok)return n}return _(`Body value assigned`,null)}function an(e,t,n,r){return bn(e,t,r,n)}function on(e){let t=[];for(let n of e.split(`.`)){let e=Sn(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function sn(e,t){let n=on(t);if(n===null)return null;let r=mn(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:pn(r)}:null}function cn(e,t){if(N(e.name)||e.schemaType===`array`)return _(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return _(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?_(`Scalar body option selected`,t[0]):g(`${n} was already given; pass it once.`)}var ln=/^(?<row>\d+):(?<item>.*)$/su;function un(e,t){let n=on(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=ln.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 dn(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&on(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function fn(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=sn(r,i.name);if(a===null)continue;if(a.firstHole!==null)return g(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||un(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return g(`${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 pn(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function mn(e,t){let n=e;for(let e of t){if(!P(n))return;n=n[e]??null}return n}function hn(e,t){if(!N(t))return mn(e,t.split(`.`))}function gn(e,t){return vn(e,t.split(`.`))}function _n(e,t,n){if(!P(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)&&gn(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function vn(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=Sn(n);if(!P(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>vn(e,r)):vn(a,r)}function N(e){return e.split(`.`).some(e=>Sn(e).isArray)}function yn(e,t){return e.parameter.length===0||!P(t)?null:wn(t,[],Cn(e.parameter))}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bn(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=Sn(o),c=e===i.length-1,l=xn(a,s,t,c,n,r);if(!l.ok||l.data===null)return g(l.summary,l.warnings);if(c)return _(`Body value assigned`,null);a=l.data}return g(`${t} is not a valid body option path.`)}function xn(e,t,n,r,i,a){let o=()=>g(`${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,_(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,_(`Body path created`,e)}return P(c)?_(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,_(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,_(`Body path created`,n)}return P(s)?_(`Body path stepped`,s):o()}function Sn(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function Cn(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 wn(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=wn(r,t,n);if(e!==null)return e}return null}if(!P(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!Tn(a,n)){if(!En(e))continue;return{path:a,suggestion:Dn(e,n)}}let o=wn(i,e,n);if(o!==null)return o}return null}function Tn(e,t){return t.prefix.has(e)||t.leaf.has(e)}function En(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function Dn(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:On(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 On(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 kn(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(Re(e)),t.description=te(t.description,{...e,hasParseDefault:t.defaultValue!==void 0}))}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?Ln(r,i):r===void 0?i===void 0?0:1:-1})}function An(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 jn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function Mn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:Fn(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 Nn(e,t){return[...new Set((e.cliConflicts??[]).filter(e=>e.includes(t)).flatMap(e=>e.filter(e=>e!==t)))]}function Pn(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?Be(n):`${Be(n)} Required JSON paths: ${r.join(`, `)}.`}function Fn(e,t){let n=Le(t.description,void 0),r=e.kind!==`multipart`&&N(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}.`:``}${In(e,t)}`}function In(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=on(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 Ln(e,t){return He(e)-He(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function Rn(e){let t;try{t=e===`-`?await zn():await Qt(e,`utf8`)}catch(t){return g(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return _(`No input provided`,null);let e=JSON.parse(t);return _(`Input parsed`,e)}catch(e){return g(`Input is not valid JSON: ${e.message}`)}}async function zn(){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 F=`--content-type`;function Bn(t,n,r){let i=e=>!r?.has(e)&&(r?.add(e),!0),a=n.requestBody??[];if(a.length>1&&i(F)){let n=a.map(({contentType:e})=>e);t.addOption(new e(`${F} <media-type>`,`Select the request body encoding, never an uploaded file's media type; omit for ${n[0]}.`).choices(n).argParser(Hn(a)))}if(or(n)&&i(`--from-file`)){let r=a[0];if(r===void 0)throw Error(`${n.operationId} has no request body`);t.addOption(new e(`--from-file <path>`,Pn(r,r.requiredPath)).argParser(Wn(`--from-file`)))}let o=An(a).filter(e=>i(I(e.variant[0].parameter)));for(let n of o.toSorted((e,t)=>Ln(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:r,parameter:i}=n.variant[0],o=new e(jn(n),a.length>1?Mn(n):Fn(r,i));a.length===1&&i.envName!==void 0&&o.env(i.envName);let s=a.length===1?Nn(r,i.optionKey):[];s.length>0&&o.conflicts(s),a.length>1?o.argParser(Vn):N(i.name)||i.schemaType===`array`?o.argParser(Un):o.argParser(Wn(i.flag)),t.addOption(o),o.envVar!==void 0&&t.on(`optionEnv:${o.name()}`,()=>{let e=t.opts()[i.optionKey];typeof e==`string`&&e.trim()&&t.setOptionValueWithSource(i.optionKey,e.trim(),`env`)})}ar(t,n,o)}function Vn(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function Hn(e){return(n,r)=>{if(r!==void 0)throw new t(`${F} was already given; pass it once.`);let i=me(e,n);if(!i.ok)throw new t(i.summary);return n}}function Un(e,t){return[...t??[],e]}function Wn(e){let n=e.split(/\s+/u)[0]??e;return(e,r)=>{if(r!==void 0)throw new t(`${n} was already given; pass it once.`);return e}}async function Gn(e,t){let n=St(e,t),r=me(e.requestBody??[],n);if(!r.ok||r.data===null)return g(r.summary,r.warnings);let i=r.data;if(i===void 0)return _(`No body`,void 0);let a=Kn(e,i,t);if(a!==null)return g(a);let o=en(e.operationId,i,t);if(!o.ok)return g(o.summary,o.warnings);t=o.data;let s=qn(i,t);if(s!==null)return g(s);let c=await Zn(t);if(!c.ok)return g(c.summary,c.warnings);let l=_n(e.requestBody??[],i,c.data);if(l!==null)return g(l);let u=Xn(e.operationId,i,c.data);if(!u.ok)return u;let d=tn(e.operationId,i,c.data);if(d!==null)return g(d);let f=Qn(e.operationId,i,t);if(!f.ok)return f;if(c.data===void 0&&f.data===void 0)return i.required?g(ir(e.operationId,i)):_(`No body`,void 0);let p=er(e.operationId,i,c.data,f.data);if(!p.ok||p.data===void 0)return p;if(i.schemaType===`array`&&!Array.isArray(p.data))return g(`${e.operationId} requires a JSON array body.`);if(i.parameter.length>0&&!P(p.data)){let t=i.kind===`multipart`?` keyed by multipart part name`:` body`;return g(`${e.operationId} requires a JSON object${t}.`)}let m=Yn(i,p.data);if(m.length>0)return g(`${e.operationId} requires body option(s): ${m.join(`, `)}`);let h=p.data,ee=P(h)?nn(i).filter(e=>!gn(h,e)):[];return ee.length>0?g(Jn(e.operationId,i,ee)):p}function Kn(e,t,n){let r=new Set(t.parameter.map(({optionKey:e})=>e));for(let i of e.requestBody??[])if(i!==t)for(let t of i.parameter){if(r.has(t.optionKey)||n[t.optionKey]===void 0)continue;let i=(e.requestBody??[]).filter(e=>e.parameter.some(({optionKey:e})=>e===t.optionKey)).map(({contentType:e})=>e);return`${I(t)} requires ${F} ${i.join(` or `)}.`}return null}function qn(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 Jn(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 Yn(e,t){return P(t)?e.parameter.filter(e=>e.required&&!gn(t,e.name)).map(I):[]}function Xn(e,t,n){let r=yn(t,n);if(r===null)return _(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion}.`;return g(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function Zn(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return _(`No body file`,void 0);let n=await Rn(t);if(!n.ok)return g(n.summary,n.warnings);let r=oe.safeParse(n.data);return r.success?_(`Input parsed`,r.data):g(`Input is not valid JSON value: ${r.error.message}`)}function Qn(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=cn(e,n[e.optionKey]);if(!a.ok||a.data===null)return g(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=$n(t,n,r,e,o);if(!s.ok)return g(s.summary,s.warnings);i=!0}if(!i)return _(`No direct body options`,void 0);let a=fn(e,t,n,r);return a===null?_(`Direct body options parsed`,r):a}function $n(e,t,n,r,i){let a=un(r,i);if(a===null){let e=nr(r,i);return e.ok?rn(n,r.name,e.data,r.schemaType===`array`):g(e.summary,e.warnings)}if(a.plain.length>0)return g(`${I(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=dn(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return g(`${I(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=rr(r.name,r.itemSchemaType,e);if(!t.ok)return g(t.summary,t.warnings);i.push(t.data)}let a=an(n,r.name,e,i);if(!a.ok)return a}return _(`Body value assigned`,null)}var I=e=>e.flag.split(` `)[0]??e.name;function er(e,t,n,r){if(n===void 0)return _(`Direct body parsed`,r);if(r===void 0)return _(`Input parsed`,n);if(P(n)&&P(r))try{return _(`Input parsed`,tr(t,n,r))}catch(t){return g(`${e} ${t.message}`)}return g(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function tr(e,t,n,r=``){let i={...t};for(let[t,a]of Object.entries(n)){let n=i[t],o=`${r}${t}`;if(P(n)&&P(a))i[t]=tr(e,n,a,`${o}.`);else if(n===void 0||n===a)i[t]=a;else throw Error(`sets JSON key '${o}' both in --from-file and with ${e.parameter.find(({name:e})=>e===o)?.flag.split(` `)[0]??`body options`} — set it in one place${Array.isArray(n)?`: move the per-item fields inside the matching '${o}[]' object(s) in the file body`:Pe.test(o)?`; keep multi-line text in the --from-file body`:``}.`)}return i}function nr(e,t){if(typeof t==`boolean`)return _(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return rr(e.name,e.schemaType,t??``);let n=[],r=N(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=rr(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return _(`Body value parsed`,n)}function rr(e,t,n){if(t===`boolean`)return n===`true`?_(`Body value parsed`,!0):n===`false`?_(`Body value parsed`,!1):g(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?g(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?g(`${e} must be an integer.`):_(`Body value parsed`,i)}return _(`Body value parsed`,n)}function ir(e,t){let n=t.parameter.filter(e=>e.required);if(n.length>0&&t.requiredPath.every(e=>n.some(({name:t})=>t===e||t.startsWith(`${e}.`))))return`${e} requires body option(s): ${n.map(I).join(`, `)}`;let r=nn(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(I).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function ar(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:F,location:`body`}),or(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),kn(e.options,r)}function or(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function sr(e){let t=ae(e,Ne(e,w));return gr(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function cr(e){let t=ae(e,Ne(e,w));gr(t);let n=ke(w,t.data,t.summary),r=[];if(t.ok&&n!==null){let e=lr(t);r.push(n.endsWith(`
1
+ import{n as e,o as t,r as n,t as r}from"./commander-BB7CDPLs.js";import{i,o as a}from"./logging-DAGOYqaQ.js";import{M as o,O as s,i as c,o as l,v as u,w as d,y as f}from"./person-owner-BJgNYLKX.js";import{Ar as p,Dr as m,Er as h,Lr as ee,Mr as te,Or as ne,Rr as re,kr as ie}from"./dist-Q4PISeeD.js";import{n as ae,r as g,s as _,u as oe}from"./result-envelope-q4j0rGDr.js";import{i as se,l as v,o as ce,r as le,s as ue,t as y}from"./env-XeZDJpn3.js";import{a as b,n as de,r as fe,t as pe}from"./package-DPDX5zmx.js";import{C as me,d as he,f as ge,o as _e,p as ve,r as ye,s as be,t as xe}from"./tool-policy-aPyLxMku.js";import{i as Se,r as Ce}from"./response-problem-BoXoN3go.js";import{n as we}from"./output-spill-CtnznV5-.js";import{a as Te,c as Ee,d as De,f as Oe,i as ke,l as Ae,m as je,n as x,o as Me,r as Ne,s as Pe,u as Fe,y as Ie}from"./contract-HStzXwji.js";import{a as Le,c as Re,i as ze,l as Be,n as Ve,s as He,t as Ue}from"./cli-help-policy-3jSdulx3.js";import{S as We,_ as Ge,a as Ke,g as S,h as qe,i as Je,m as Ye,n as Xe,p as Ze,r as Qe,s as $e,t as et,v as tt,x as C,y as nt}from"./api-key-bearer-credential-4LScynXy.js";import{a as rt,c as it,d as at,g as ot,l as st,m as ct,o as lt,s as ut,t as dt,u as ft}from"./oauth-bearer-credential-kUzaF0hp.js";import{n as pt,r as mt,t as ht}from"./oauth-login-CVIyq_3x.js";import{a as gt,c as _t,d as vt,i as yt,l as bt,n as xt,o as St,s as Ct,t as wt,u as Tt}from"./startup-auth-ChbX0MJF.js";import{n as Et,t as w}from"./openapi-commands-BrF8nKmC.js";import{i as T,r as Dt,t as E}from"./output-mode-CRxIcJgT.js";import{spawnSync as Ot}from"node:child_process";import{basename as D,dirname as O,relative as kt,resolve as k,sep as At}from"node:path";import{copyFileSync as jt,existsSync as A,lstatSync as Mt,mkdirSync as Nt,mkdtempSync as Pt,readFileSync as Ft,readdirSync as It,readlinkSync as Lt,realpathSync as Rt,renameSync as zt,symlinkSync as Bt,writeFileSync as Vt}from"node:fs";import j,{stderr as M,stdin as Ht}from"node:process";import{TextDecoder as Ut,inspect as Wt}from"node:util";import{homedir as Gt,hostname as Kt,platform as qt}from"node:os";import{fileURLToPath as Jt}from"node:url";import{setTimeout as Yt}from"node:timers/promises";import{randomUUID as Xt,webcrypto as Zt}from"node:crypto";import{readFile as Qt}from"node:fs/promises";import{createInterface as $t}from"node:readline/promises";function en(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{...g(`${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 _(`Environment-bound options applied`,r)}function tn(e,t,n){if(!P(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||!gn(n,r.name))continue;let a=hn(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 nn(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 rn(e,t,n,r=!1){if(r||!N(t)||!Array.isArray(n))return bn(e,t,n);for(let[r,i]of n.entries()){let n=bn(e,t,i,r);if(!n.ok)return n}return _(`Body value assigned`,null)}function an(e,t,n,r){return bn(e,t,r,n)}function on(e){let t=[];for(let n of e.split(`.`)){let e=Sn(n);if(t.push(e.key),e.isArray)return t.join(`.`)}return null}function sn(e,t){let n=on(t);if(n===null)return null;let r=mn(e,n.split(`.`));return Array.isArray(r)?{path:n,rowCount:r.length,firstHole:pn(r)}:null}function cn(e,t){if(N(e.name)||e.schemaType===`array`)return _(`Repeated body option selected`,typeof t==`string`?[t]:t);if(!Array.isArray(t))return _(`Scalar body option selected`,t);let n=e.flag.split(` `)[0]??e.name;return t.length===1?_(`Scalar body option selected`,t[0]):g(`${n} was already given; pass it once.`)}var ln=/^(?<row>\d+):(?<item>.*)$/su;function un(e,t){let n=on(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=ln.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 dn(e,t,n){let r=0;for(let i of e.parameter){let e=t[i.optionKey];e!==void 0&&typeof e!=`boolean`&&on(i.name)===n&&(r=Math.max(r,typeof e==`string`?1:e.length))}return r}function fn(e,t,n,r){for(let i of t.parameter){let t=n[i.optionKey];if(t===void 0)continue;let a=sn(r,i.name);if(a===null)continue;if(a.firstHole!==null)return g(`${e} has no ${a.path}[] row ${a.firstHole} — number ${a.path}[] rows from 0 with no gaps.`);if(i.schemaType!==`array`||a.rowCount<=1||un(i,t)!==null)continue;let o=i.flag.split(` `)[0]??i.name;return g(`${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 pn(e){for(let t=0;t<e.length;t+=1)if(e[t]===void 0)return t;return null}function mn(e,t){let n=e;for(let e of t){if(!P(n))return;n=n[e]??null}return n}function hn(e,t){if(!N(t))return mn(e,t.split(`.`))}function gn(e,t){return vn(e,t.split(`.`))}function _n(e,t,n){if(!P(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)&&gn(n,e.name))return`${e.name} in --from-file requires --content-type ${i.contentType}.`}return null}function vn(e,t){let[n,...r]=t;if(n===void 0)return!0;let i=Sn(n);if(!P(e)||!Object.hasOwn(e,i.key))return!1;let a=e[i.key]??null;return i.isArray?Array.isArray(a)&&a.every(e=>vn(e,r)):vn(a,r)}function N(e){return e.split(`.`).some(e=>Sn(e).isArray)}function yn(e,t){return e.parameter.length===0||!P(t)?null:wn(t,[],Cn(e.parameter))}function P(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bn(e,t,n,r=0){let i=t.split(`.`),a=e;for(let[e,o]of i.entries()){let s=Sn(o),c=e===i.length-1,l=xn(a,s,t,c,n,r);if(!l.ok||l.data===null)return g(l.summary,l.warnings);if(c)return _(`Body value assigned`,null);a=l.data}return g(`${t} is not a valid body option path.`)}function xn(e,t,n,r,i,a){let o=()=>g(`${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,_(`Body value assigned`,e)):o();let c=n[a];if(c===void 0){let e={};return n[a]=e,_(`Body path created`,e)}return P(c)?_(`Body path stepped`,c):o()}if(r)return s===void 0?(e[t.key]=i,_(`Body value assigned`,e)):o();if(s===void 0){let n={};return e[t.key]=n,_(`Body path created`,n)}return P(s)?_(`Body path stepped`,s):o()}function Sn(e){let t=e.endsWith(`[]`);return{key:t?e.slice(0,-2):e,isArray:t}}function Cn(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 wn(e,t,n){if(Array.isArray(e)){if(e.length===0)return null;for(let r of e){let e=wn(r,t,n);if(e!==null)return e}return null}if(!P(e))return null;for(let[r,i]of Object.entries(e)){let e=[...t,Array.isArray(i)?`${r}[]`:r],a=e.join(`.`);if(!Tn(a,n)){if(!En(e))continue;let t=Dn(e,n);return{path:a,...t===void 0?{}:{suggestion:t}}}let o=wn(i,e,n);if(o!==null)return o}return null}function Tn(e,t){return t.prefix.has(e)||t.leaf.has(e)}function En(e){return e.slice(0,-1).some(e=>e.endsWith(`[]`))}function Dn(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:On(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 On(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}var kn=e=>Array.isArray(e)&&!Object.isFrozen(e);function An(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(Re(e)),t.description=te(t.description,{...e,hasParseDefault:t.defaultValue!==void 0}))}if(!kn(e))throw Error(`Commander option list is frozen; generated option help cannot be ordered.`);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?Rn(r,i):r===void 0?i===void 0?0:1:-1})}function jn(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 Mn(e){let{flag:t}=e.variant[0].parameter;return e.variant.every(({parameter:e})=>e.flag===t)?t:`${t.split(` `)[0]??t} <value>`}function Nn(e){let t=e.variant.map(({descriptor:e,parameter:t})=>({contentType:e.contentType,text:In(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 Fn(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?Be(n):`${Be(n)} Required JSON paths: ${r.join(`, `)}.`}function In(e,t){let n=Le(t.description,void 0),r=e.kind!==`multipart`&&N(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}.`:``}${Ln(e,t)}`}function Ln(e,t){if(e.kind===`multipart`||t.schemaType!==`array`)return``;let n=on(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 Rn(e,t){return He(e)-He(t)||Number(e.required!==!0)-Number(t.required!==!0)}async function zn(e){let t;try{t=e===`-`?await Bn():await Qt(e,`utf8`)}catch(t){return g(`Could not read input: ${t.message}`,[`path=${e}`])}try{if(t.trim().length===0)return _(`No input provided`,null);let e=JSON.parse(t);return _(`Input parsed`,e)}catch(e){return g(`Input is not valid JSON: ${e.message}`)}}async function Bn(){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 F=`--content-type`;function Vn(t,n,r){let i=e=>!r?.has(e)&&(r?.add(e),!0),a=n.requestBody??[];if(a.length>1&&i(F)){let n=a.map(({contentType:e})=>e);t.addOption(new e(`${F} <media-type>`,`Select the request body encoding, never an uploaded file's media type; omit for ${n[0]}.`).choices(n).argParser(Un(a)))}if(sr(n)&&i(`--from-file`)){let r=a[0];if(r===void 0)throw Error(`${n.operationId} has no request body`);t.addOption(new e(`--from-file <path>`,Fn(r,r.requiredPath)).argParser(Gn(`--from-file`)))}let o=jn(a).filter(e=>i(I(e.variant[0].parameter)));for(let n of o.toSorted((e,t)=>Rn(e.variant[0].parameter,t.variant[0].parameter))){let{descriptor:r,parameter:i}=n.variant[0],o=new e(Mn(n),a.length>1?Nn(n):In(r,i));a.length===1&&i.envName!==void 0&&o.env(i.envName);let s=a.length===1?Pn(r,i.optionKey):[];s.length>0&&o.conflicts(s),a.length>1?o.argParser(Hn):N(i.name)||i.schemaType===`array`?o.argParser(Wn):o.argParser(Gn(i.flag)),t.addOption(o),o.envVar!==void 0&&t.on(`optionEnv:${o.name()}`,()=>{let e=t.opts()[i.optionKey];typeof e==`string`&&e.trim()&&t.setOptionValueWithSource(i.optionKey,e.trim(),`env`)})}or(t,n,o)}function Hn(e,t){return t===void 0?e:typeof t==`string`?[t,e]:[...t,e]}function Un(e){return(n,r)=>{if(r!==void 0)throw new t(`${F} was already given; pass it once.`);let i=me(e,n);if(!i.ok)throw new t(i.summary);return n}}function Wn(e,t){return[...t??[],e]}function Gn(e){let n=e.split(/\s+/u)[0]??e;return(e,r)=>{if(r!==void 0)throw new t(`${n} was already given; pass it once.`);return e}}async function Kn(e,t){let n=St(e,t),r=me(e.requestBody??[],n);if(!r.ok||r.data===null)return g(r.summary,r.warnings);let i=r.data;if(i===void 0)return _(`No body`,void 0);let a=qn(e,i,t);if(a!==null)return g(a);let o=en(e.operationId,i,t);if(!o.ok)return g(o.summary,o.warnings);t=o.data;let s=Jn(i,t);if(s!==null)return g(s);let c=await Qn(t);if(!c.ok)return g(c.summary,c.warnings);let l=_n(e.requestBody??[],i,c.data);if(l!==null)return g(l);let u=Zn(e.operationId,i,c.data);if(!u.ok)return u;let d=tn(e.operationId,i,c.data);if(d!==null)return g(d);let f=$n(e.operationId,i,t);if(!f.ok)return f;if(c.data===void 0&&f.data===void 0)return i.required?g(ar(e.operationId,i)):_(`No body`,void 0);let p=tr(e.operationId,i,c.data,f.data);if(!p.ok||p.data===void 0)return p;if(i.schemaType===`array`&&!Array.isArray(p.data))return g(`${e.operationId} requires a JSON array body.`);if(i.parameter.length>0&&!P(p.data)){let t=i.kind===`multipart`?` keyed by multipart part name`:` body`;return g(`${e.operationId} requires a JSON object${t}.`)}let m=Xn(i,p.data);if(m.length>0)return g(`${e.operationId} requires body option(s): ${m.join(`, `)}`);let h=p.data,ee=P(h)?nn(i).filter(e=>!gn(h,e)):[];return ee.length>0?g(Yn(e.operationId,i,ee)):p}function qn(e,t,n){let r=new Set(t.parameter.map(({optionKey:e})=>e));for(let i of e.requestBody??[])if(i!==t)for(let t of i.parameter){if(r.has(t.optionKey)||n[t.optionKey]===void 0)continue;let i=(e.requestBody??[]).filter(e=>e.parameter.some(({optionKey:e})=>e===t.optionKey)).map(({contentType:e})=>e);return`${I(t)} requires ${F} ${i.join(` or `)}.`}return null}function Jn(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 Yn(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 Xn(e,t){return P(t)?e.parameter.filter(e=>e.required&&!gn(t,e.name)).map(I):[]}function Zn(e,t,n){let r=yn(t,n);if(r===null)return _(`Body file paths validated`,null);let i=r.suggestion===void 0?``:` Use ${r.suggestion}.`;return g(`${e} --from-file contains unknown JSON path ${r.path}.${i}`)}async function Qn(e){let t=typeof e.fromFile==`string`?e.fromFile:void 0;if(t===void 0)return _(`No body file`,void 0);let n=await zn(t);if(!n.ok)return g(n.summary,n.warnings);let r=oe.safeParse(n.data);return r.success?_(`Input parsed`,r.data):g(`Input is not valid JSON value: ${r.error.message}`)}function $n(e,t,n){let r={},i=!1;for(let e of t.parameter){let a=cn(e,n[e.optionKey]);if(!a.ok||a.data===null)return g(a.summary,a.warnings);let o=a.data;if(o===void 0)continue;let s=er(t,n,r,e,o);if(!s.ok)return g(s.summary,s.warnings);i=!0}if(!i)return _(`No direct body options`,void 0);let a=fn(e,t,n,r);return a===null?_(`Direct body options parsed`,r):a}function er(e,t,n,r,i){let a=un(r,i);if(a===null){let e=rr(r,i);return e.ok?rn(n,r.name,e.data,r.schemaType===`array`):g(e.summary,e.warnings)}if(a.plain.length>0)return g(`${I(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=dn(e,t,a.container);for(let e of a.rows.keys())if(!(e<o))return g(`${I(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=ir(r.name,r.itemSchemaType,e);if(!t.ok)return g(t.summary,t.warnings);i.push(t.data)}let a=an(n,r.name,e,i);if(!a.ok)return a}return _(`Body value assigned`,null)}var I=e=>e.flag.split(` `)[0]??e.name;function tr(e,t,n,r){if(n===void 0)return _(`Direct body parsed`,r);if(r===void 0)return _(`Input parsed`,n);if(P(n)&&P(r))try{return _(`Input parsed`,nr(t,n,r))}catch(t){return g(`${e} ${t instanceof Error?t.message:String(t)}`)}return g(`${e} cannot combine --from-file with direct body options unless the file body is an object.`)}function nr(e,t,n,r=``){let i={...t};for(let[t,a]of Object.entries(n)){let n=i[t],o=`${r}${t}`;if(P(n)&&P(a))i[t]=nr(e,n,a,`${o}.`);else if(n===void 0||n===a)i[t]=a;else throw Error(`sets JSON key '${o}' both in --from-file and with ${e.parameter.find(({name:e})=>e===o)?.flag.split(` `)[0]??`body options`} — set it in one place${Array.isArray(n)?`: move the per-item fields inside the matching '${o}[]' object(s) in the file body`:Pe.test(o)?`; keep multi-line text in the --from-file body`:``}.`)}return i}function rr(e,t){if(typeof t==`boolean`)return _(`Body value parsed`,t);if(t===void 0||typeof t==`string`)return ir(e.name,e.schemaType,t??``);let n=[],r=N(e.name)&&e.schemaType!==`array`?e.schemaType:e.itemSchemaType;for(let i of t){let t=ir(e.name,r,i);if(!t.ok)return t;n.push(t.data)}return _(`Body value parsed`,n)}function ir(e,t,n){if(t===`boolean`)return n===`true`?_(`Body value parsed`,!0):n===`false`?_(`Body value parsed`,!1):g(`${e} must be true or false.`);if(t===`number`||t===`integer`){let r=n.trim(),i=Number(r);return r===``||!Number.isFinite(i)?g(`${e} must be a finite ${t}.`):t===`integer`&&!Number.isInteger(i)?g(`${e} must be an integer.`):_(`Body value parsed`,i)}return _(`Body value parsed`,n)}function ar(e,t){let n=t.parameter.filter(e=>e.required);if(n.length>0&&t.requiredPath.every(e=>n.some(({name:t})=>t===e||t.startsWith(`${e}.`))))return`${e} requires body option(s): ${n.map(I).join(`, `)}`;let r=nn(t);if(r.length>0)return`${e} requires --from-file with JSON body path(s): ${r.join(`, `)}`;let i=t.parameter.map(I).join(`, `);return i.length===0?`${e} requires --from-file`:`${e} requires --from-file or body option(s): ${i}`}function or(e,t,n){let r=[...t.parameters,...n.map(({variant:e})=>e[0].parameter)];(t.requestBody?.length??0)>1&&r.push({optionKey:`contentType`,flag:F,location:`body`}),sr(t)&&r.push({optionKey:`fromFile`,flag:`--from-file`,location:`body`}),An(e.options,r)}function sr(e){return(e.requestBody??[]).some(e=>e.kind!==`multipart`||e.parameter.some(e=>e.schemaFormat!==`binary`))}function cr(e){let t=ae(e,Ne(e,w));return _r(t),process.stdout.write(`${JSON.stringify(t)}\n`),t}function lr(e){let t=ae(e,Ne(e,w));_r(t);let n=ke(w,t.data,t.summary),r=[];if(t.ok&&n!==null){let e=ur(t);r.push(n.endsWith(`
2
2
  `)?n.slice(0,-1):n),r.push(...e),process.stdout.write(Te(r.join(`
3
- `),!0,!0,e.length));return}let i=t.ok?`OK`:`FAIL`;r.push(`[${i}] ${t.summary}`),!t.ok&&t.problem!==void 0&&r.push(...fr(t.problem)),r.push(...lr(t)),process.stdout.write(Te(r.join(`
4
- `),!0))}function lr(e){let t=[];e.ids.length>0&&t.push(` ids: ${e.ids.join(`, `)}`);for(let[n,r]of Object.entries(e.counts))t.push(` ${n}: ${r}`);for(let n of e.references)t.push(` ref: ${n}`);if(e.truncation!==void 0){let n=e.truncation.omitted.join(`, `);t.push(` truncated: byteLength=${e.truncation.byteLength} maxBytes=${e.truncation.maxBytes} omitted=${n}`,` recovery: ${e.truncation.recovery}`)}for(let n of e.warnings)t.push(` warn: ${n}`);return t}function L(e,t){let n=we(t);if(e.mode===`data`||e.mode===`data-full`){let t=e.mode===`data`?ae(n,Ne(n,w)):n;gr(t),process.stdout.write(`${JSON.stringify(t.ok&&t.truncated!==!0?ur(t.data):t)}\n`),t.ok||(process.exitCode=1);return}let r=e.mode===`json`?sr(n):n;e.mode===`text`&&cr(r),r.ok||(process.exitCode=1)}function ur(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 dr(e,t){let n=Me(t);if(n===null){process.stderr.write(`explain: the response carried no search interpretation
5
- `),process.exitCode=1;return}(e===`text`?process.stdout:process.stderr).write(n)}function fr(e){let t=[];typeof e.code==`string`&&t.push(` code: ${e.code}`),typeof e.detail==`string`&&t.push(` detail: ${e.detail}`),typeof e.hint==`string`&&t.push(` hint: ${e.hint}`),typeof e.suggestion==`string`&&t.push(` suggestion: ${e.suggestion}`);let n=Object.entries(e.suggestions??{});if(n.length>0){let e=n.map(([e,t])=>`${e}=${t}`).join(`; `);t.push(` suggestions: ${e}`)}return typeof e.requiredRole==`string`&&t.push(` requiredRole: ${e.requiredRole}`),t.push(...pr(e),...mr(`unknownParameters`,e.unknownParameters),...mr(`validParameters`,e.validParameters),...hr(e.resolution)),t}function pr(e){let t=[];return 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?[` meter: ${t.join(` `)}`]:[]}function mr(e,t){return t!=null&&t.length>0?[` ${e}: ${t.join(`, `)}`]:[]}function hr(e){if(e==null)return[];let t=[`action=${e.action}`];return 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}`),[` resolution: ${t.join(` `)}`]}function gr(e){e.ok&&e.warnings.length===0||a({component:b().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 _r(e,t,n=b().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 g(`Invalid --limit value: ${JSON.stringify(e.limit)} (expected a non-negative integer)`,["Pass a non-negative integer, e.g. `--limit 20`."]);let i=Oe(t,n),a=Ie(e.root??``),o=[...new Set(i.map(({cli:e})=>Ie(e.path.at(0)??``)))].toSorted();if(a.length>0&&!o.includes(a))return g(`Unknown --root value: ${JSON.stringify(e.root)}`,[`Pass one of: ${o.join(`, `)}.`]);let s=je(e.q??``,i.filter(t=>br(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]),directParameterName:e.flags.filter(({location:e})=>e!==`body`).map(({wireName:e})=>e),parameterDescription:[e.body.description,...e.flags.map(({description:e})=>e)]})).map(({item:e})=>e),c=s.slice(0,r);return _(`Operation catalog matches`,{operation:c,count:{totalOperations:t.length,matched:s.length,returned:c.length}})}function vr(e,t,n=b().bin[0]){let r=Oe(t,n),i=e.operationId===void 0?yr(r,e.command):r.find(t=>t.operationId===e.operationId);if(i===void 0){let i=Tr(e.command??``),a=r.map(e=>e.cli.command).filter(e=>e.startsWith(`${n} ${i} `));if(a.length>0)return g(`${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=_r({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 g(`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 _(`Generated operation detail`,{operation:i,usage:Sr(i,r)})}function yr(e,t){if(t===void 0)return;let{bin:n}=b(),r=Tr(t,n);return e.find(e=>Tr(e.cli.command,n)===r)}var R=(e,t)=>e===void 0||e===`all`||e===`any`||e===String(t);function br(e,t){return(t.root===void 0||xr(e,t.root))&&R(t.scope,e.scope)&&R(t.mutates,e.mutates)&&R(t.destructive,e.destructive)&&R(t.intent,e.intent)&&R(t.method,e.method)}function xr(e,t){let n=Ie(t);return n.length===0||Ie(e.cli.path.at(0)??``)===n}function Sr(e,t){let n=Ee(e);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 (CLI-only operation)`}`,e.body.hasBody?`body: kind=${e.body.kind??`unknown`} required=${e.body.required} requiredPath=${e.body.requiredPath.join(`,`)}`:`body: none`,...e.successResponse===void 0?[]:[`success: ${e.successResponse}`],...[!0,!1].flatMap(t=>[`path`,`query`,`header`,`body`].map(r=>{let i=n.filter(e=>e.required===t&&e.location===r),a=wr(`${t?`required`:`optional`} ${r} flags`,i);return t&&r===`body`&&e.body.kind===`json`&&i.length>0?`${a} (required unless --from-file sets JSON key(s) ${i.map(({wireName:e})=>e).join(`, `)})`:a})),...De(e,t),...Cr(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
6
- `)}function Cr(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}function wr(e,t){return`${e}: ${t.length===0?`none`:t.map(e=>e.name).join(` `)}`}function Tr(e,t=b().bin){let[n=``,...r]=e.trim().split(/\s+/u);return(t.includes(n)?r:[n,...r]).join(` `)}var Er=`dist/aventure-cli/command-catalog.compact.txt`,Dr=` · `,Or=`-`;function kr(e=b().bin[0]){return k(Ar(O(Jt(import.meta.url)),e),Er)}function Ar(e,t){let n=e;for(;;){if(A(k(n,`package.json`)))return n;let r=O(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function jr(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function Mr(e,t,n,r=b().bin[0]){let i=_r(e,t,r);if(!i.ok||i.data===null){L({mode:n},i);return}Pr({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:Lr(i.data,Ir(e.format,`lines`)),summary:`Generated operation matches`})}function Nr(e,t,n,r=b().bin[0]){let i=vr(e,t,r);if(!i.ok||i.data===null){L({mode:n},i);return}Pr({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:Rr(i.data,Ir(e.format,`usage`)),summary:`Generated operation detail`})}function Pr(e){let t=e.mode,n=Ir(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`)){L({mode:t},g(`--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.matched===0&&(r||e.opts.format===void 0||n===`text`)?`No generated operations matched.`:e.rendered,a=i.endsWith(`
7
- `)?i:`${i}\n`;if(e.opts.output!==void 0){Vt(e.opts.output,a),L({mode:t},_(e.summary,{outputPath:e.opts.output,byteLength:Buffer.byteLength(a,`utf8`),format:n},{counts:Ur(e.data)}));return}if(t===`text`){Fr(e.summary,a);return}L({mode:t},_(e.summary,e.data,{counts:Ur(e.data)}))}function Fr(e,t){let n=we(_(e,t));if(!n.ok||n.data===null){L({mode:`text`},n);return}process.stdout.write(n.data.endsWith(`
8
- `)?n.data:`${n.data}\n`)}function Ir(e,t){return e??t}function Lr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?e.operation.map(e=>JSON.stringify(e)).join(`
9
- `):t===`text`?Vr(e.operation):t===`compact`?e.operation.map(zr).join(`
10
- `):e.operation.map(Hr).join(`
11
- `)}function Rr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?JSON.stringify(e.operation):t===`lines`?Hr(e.operation):t===`compact`?zr(e.operation):e.usage}function zr(e){let t=Br(e);return[e.cli.command,e.summary,t.length===0?Or:t.join(` `)].join(Dr)}function Br(e){return e.flags.filter(t=>t.required&&(t.contentType===void 0||t.contentType===e.body.contentType)).map(e=>e.name)}function Vr(e){return e.map(e=>`${e.cli.command}\n ${Hr(e)}`).join(`
12
- `)}function Hr(e){let t=Br(e);return[z(`operationId`,e.operationId),z(`scope`,e.scope),z(`mutates`,String(e.mutates)),z(`destructive`,String(e.destructive)),z(`intent`,e.intent),z(`resource`,e.resource),z(`cli`,e.cli.command),e.mcpTool===null?``:z(`mcpTool`,e.mcpTool),z(`method`,e.method),z(`path`,e.path),z(`auth`,e.auth),z(`flags`,[...new Set(e.flags.map(e=>e.name))].join(` `)),z(`requiredFlags`,t.join(` `)),z(`bodyKind`,e.body.kind??``),z(`bodyRequired`,String(e.body.required)),z(`summary`,e.summary)].filter(e=>e.length>0).join(` `)}function z(e,t){return t.length===0?``:`${e}=${JSON.stringify(t)}`}function Ur(e){return`count`in e?e.count:{returned:1}}function Wr(e,t,n=b().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(`
13
- `)).argument(`[command...]`,"command path, operationId, or METHOD and path, e.g. `help entities get`"),r.addOption(new Gr(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()});let i=Zr(t);i!==void 0&&r.option(`--ask <question>`,i.summary),E(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=T(a);if(r.length>0){L({mode:e},g(`Use either a command path or --ask, not both.`));return}L({mode:e},await ti(i,a.ask,a.environment,e));return}let o=ei(e,r),s=t.find(t=>o!==void 0&&ei(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?$r(r,t):_(`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){L({mode:T(a)},c);return}Nr({...a,...c.data},t,T(a,`text`),n)}),Xr(e,t,n)}var Gr=class extends e{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))}},Kr=2,qr=6,Jr={formatHelp(e,t){let r=r=>n.prototype.formatHelp.call(this,e,Object.assign(Object.create(t),r));if(t.visibleCommands(e).length===0)return r({});let i=t.padWidth(e,t),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 t=n.prototype.visibleCommands.call(this,e);return e.parent===null?t.filter(e=>!Ve.has(e.name())):t},subcommandTerm(e){let t=n.prototype.subcommandTerm.call(this,e);return e.commands.length>0&&e.registeredArguments.length===0?`${t} <command>`:t},formatItem(e,t,r,i){let a=i.helpWidth??80,o=a-t-4;return r===``||o>=i.minWidthToWrap?n.prototype.formatItem.call(i,e,t,r,i):`${` `.repeat(Kr)}${e}\n${Yr(r,a,i)}`}};function Yr(e,t,n){return n.boxWrap(e,t-qr).replace(/^/gmu,` `.repeat(qr))}function Xr(e,t,n){for(let r of t){let i=ei(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=Ae(r.operationId,t,n),[s,...c]=Cr(r.errorResponse),l=c.map(t=>Yr(t.trimStart(),a,e).replace(/^ +/u,` `.repeat(Kr))),u=s===void 0?[]:[``,s,...l];return`\n${[...o,...u].join(`
14
- `)}\n`})}}function Zr(e){let[t,...n]=e.filter(e=>{let[t,n,...r]=e.cliPath;return t===`help`&&n!==void 0&&r.length===0&&ni(e)!==void 0});return n.length===0?t:void 0}var Qr='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function $r(e,t){let[n,...r]=e,i=he.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return _(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=ge(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return _(`Resolved by route template`,{operationId:s.operationId});let c=ie({method:a,path:o});return!c.ok||c.data===null?g(c.summary,[...c.warnings,Qr]):_(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function ei(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 ti(e,t,n,r){let i=ni(e);if(i===void 0)return g(`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 Gn(e,{[i.optionKey]:t});return a.ok?await p({method:e.method,path:m(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:Dt(r)?`json`:`auto`}):a}function ni(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 ri(e,t,n){if(e.cliPath[0]!==`lookup`||!ii(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?g(i):g(i,[],{httpStatus:n.httpStatus,problem:n.problem})}function ii(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}function ai(e,t){if(e.deprecated!==!0)return t;let n=e.description.match(/^Deprecated:[^.]*\./u)?.[0]??`Deprecated; run \`help ${e.cliPath.join(` `)}\` for its replacement.`;return{...t,warnings:[n,...t.warnings]}}var oi=f({artifact:d().nullish(),group:d().nullish(),name:d().nullish(),revision:d().nullish(),time:c({offset:!0}).nullish(),version:d().nullish()}),si=f({build:oi}),ci=l([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),li=l([`RSA_OAEP_256_A256_GCM_V1`]),ui=f({clientLabel:d().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:ci.nullish(),encryptionAlgorithm:li.nullish(),encryptionPublicKey:d().min(344).max(12e3).nullish()}),di=32;async function fi(){let e=await Zt.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await Zt.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function pi(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=mi(n,`wrapped key`,128,1024),s=mi(r,`nonce`,12,12),c=mi(i,`ciphertext`,1,65536),l=mi(a,`authentication tag`,16,16),u;try{u=await Zt.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!==di)throw Error(`broker credential used an invalid AES-256 key`);let e=await Zt.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 Zt.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new Ut(`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 mi(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 hi=l([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),gi=l([`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`]),_i=f({approvedAt:c({offset:!0}).nullish(),clientLabel:d(),clientPlatform:ci,comparisonCode:d(),consumedAt:c({offset:!0}).nullish(),createdAt:c({offset:!0}),expiresAt:c({offset:!0}),id:s(),intervalSeconds:u().int().min(1),keyReadyAt:c({offset:!0}).nullish(),status:hi,terminalAt:c({offset:!0}).nullish(),terminalReason:gi.nullish(),updatedAt:c({offset:!0})}),vi=f({algorithm:li,authenticationTag:d(),ciphertext:d(),nonce:d(),wrappedKey:d()}),yi=f({delivery:vi.nullish(),expiresAt:c({offset:!0}),status:hi,terminalReason:gi.nullish()}),bi=f({comparisonCode:d(),expiresAt:c({offset:!0}),id:s(),intervalSeconds:u().int().min(1),pollSecret:d(),verificationUrl:d()}),B=[{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. Use --no-browser for OAuth device authorization only when the issuer advertises device-grant support; otherwise use --key --no-browser for API-key approval.`,operationId:`getAuthProviderCatalog`,method:`GET`,path:`/v1/auth/providers`,bodyOption:[],localOption:[{optionKey:`browser`,flag:`--no-browser`,description:`Use OAuth device authorization only when the issuer advertises device-grant support: print a sign-in URL and code, then wait for approval. Otherwise use --key --no-browser for API-key approval.`},{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 API-key approval URL and wait for approval 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.`}]}],xi=x(B,`start`),Si=x(B,`poll`),Ci=x(B,`acknowledge`),V=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${Ge(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=ki(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},wi=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${S(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function Ti(e){let t=await re(We(v()),{method:xi.method,path:ve(xi.path,{},xi.operationId),headers:{},contentType:`application/json`,body:e},bi);if(t.ok&&t.redirect)throw new V(`start`,Ai(t.status));if(!t.ok)throw new V(`start`,t.problem);return ji(t.data)}async function Ei(e,t){let n=ne(Si.operationId),r=await re(We(v()),{method:Si.method,path:ve(Si.path,{cliAuthorizationId:e},Si.operationId),headers:{[n]:t}},yi);if(r.ok&&r.redirect)throw new V(`poll`,Ai(r.status),[t]);if(!r.ok)throw new V(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:Oi(r.headers[`retry-after`])}}async function Di(e,t){let n=ne(Ci.operationId),r;try{r=await re(We(v()),{method:Ci.method,path:ve(Ci.path,{cliAuthorizationId:e},Ci.operationId),headers:{[n]:t}},_i)}catch(e){throw new wi(`acknowledge`,e,[t])}if(r.ok&&r.redirect)throw new V(`acknowledge`,Ai(r.status),[t]);if(!r.ok)throw new V(`acknowledge`,r.problem,[t]);return r.data}function Oi(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function ki(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function Ai(e){return{status:e,title:`Unexpected redirect`,type:`about:blank`,code:void 0,detail:`CLI authorization endpoint returned an unexpected redirect`}}function ji(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())})`},[Wt.custom]:{enumerable:!1,value:a}})}async function Mi(e){let t=await Ni(e.credential.secret);if(t.state!==`verified`||e.activation!==`active`)return{stored:e,verification:t};try{return{stored:await Ke(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 — ${S(n,[e.credential.secret])}`}}}}async function Ni(e){let t=We(v()),n;try{n=await re(t,{method:`GET`,path:m(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},tt)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${S(t,[e])}`}}return n.ok&&n.redirect?{state:`unavailable`,summary:`identity verification returned unexpected redirect ${n.status}`}: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: ${Ge(n.problem,[e])}`}}var Pi=x(B,`revoke`);async function Fi(e){let t;try{t=C(v().host)}catch(e){return g(`auth logout: invalid API host — ${S(e)}`)}let n=await Ii(t),r=await zi(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`?_(`No CLI credential is stored for this API host.`,a):n.state===`failed`?{...g(`auth logout: ${i[0]}`),data:a}:_(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 Ii(e){let t=await lt(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await Ri(t.stored):{revoked:!1};try{await rt(e)}catch(e){return{state:`failed`,summary:S(e)}}return{state:`forgotten`,...n}}async function Li(e){let t=Reflect.get(await ht(e),`revocation_endpoint`);return typeof t==`string`?ot(t,`revocation endpoint`,!0):void 0}async function Ri(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await Li(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:ft(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:S(e,ct(n))}}}async function zi(e,t){let n;try{n=await Je(e)}catch(e){return g(`auth logout: stored credential could not be read — ${S(e)}`)}if(n.state===`unavailable`)return{...g(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await Bi(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!t.forgetLocal)return{...g(`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:Vi(r,!1,!1)};try{await Xe(r.host)}catch(e){return{...g(`auth logout: local credential removal failed — ${S(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:Vi(r,a,!1)}}return _(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.`,Vi(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function Bi(e){let t=We(v());try{let n=await re(t,{method:Pi.method,path:ve(Pi.path,{},Pi.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},tt);return n.ok&&n.redirect?{outcome:`unconfirmed`,summary:`remote key revocation returned unexpected redirect ${n.status}`}: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:Ge(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:S(t,[e.credential.secret])}}}function Vi(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var Hi=`RSA_OAEP_256_A256_GCM_V1`,Ui=1,Wi=30,H=b().bin[0],Gi=`The local record remains pending and unavailable to ordinary commands. Re-run \`${H} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function Ki(e){if(!Ht.isTTY)return g(`${H} 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=v().host;t=C(e),n=nt(e)}catch(e){return g(`auth login --key: invalid environment configuration — ${S(e)}`)}for(;;){let e;try{e=await Qe(t)}catch(e){return g(`auth login --key: credential storage could not be inspected — ${S(e)}`)}if(e.state===`unavailable`)return g(`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&&M.write($e(e.keyringFailure));break}let n=await qi(e.stored);if(n!==null)return n}let r;try{r=await fi()}catch(e){return g(`auth login --key: ephemeral encryption key could not be created — ${S(e)}`)}let i=ui.safeParse({clientLabel:e.clientLabel?.trim()||(Kt().trim()||H).slice(0,120),clientPlatform:Zi(),encryptionAlgorithm:Hi,encryptionPublicKey:r.publicKey});if(!i.success)return g(`auth login --key: ${o(i.error)}`);let a;try{a=await Ti(i.data)}catch(e){return g(`auth login --key: could not start browser authorization — ${S(e)}`)}let s;try{s=Ye(a,n)}catch(e){return g(`auth login --key: unsafe browser authorization URL rejected — ${S(e)}`)}if(!Xi(await Ze(a,n,{noBrowser:e.noBrowser}),a,s))return g(`auth login --key: browser authorization requires an interactive terminal for manual handoff`,[`Automatic browser opening did not complete, and the approval URL was withheld because stderr is not an interactive terminal. Retry from an interactive terminal.`],{references:[s]});let c;try{c=await Yi(a)}catch(e){return g(`auth login --key: authorization did not complete — ${S(e)}`,[],{references:[s]})}if(c.algorithm!==Hi)return g(`auth login --key: broker selected an unsupported encryption algorithm`);let l;try{l=await pi(r.privateKey,c)}catch(e){return g(`auth login --key: encrypted credential could not be opened — ${S(e)}`)}let u=await Ni(l);if(u.state!==`verified`)return g(`auth login --key: decrypted credential was neither stored nor acknowledged — ${u.summary}`);let d;try{d=await Ke(t,{apiKey:u.apiKey,secret:l},`pending`)}catch(e){return g(`auth login --key: credential could not be durably stored — ${S(e)}`)}let f;try{f=await Ji(a)}catch(e){return U(d,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${S(e,[a.pollSecret])}`,Gi)}if(f.status!==`CONSUMED`)return U(d,!0,`auth login --key: broker returned ${f.status} after acknowledgment`,Gi);let p=await Ni(l);if(p.state!==`verified`||!ta(p.apiKey,d.credential.apiKey))return U(d,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${p.summary}`,Gi);try{let e=await Ke(t,{apiKey:p.apiKey,secret:l},`active`);return _(`API key stored; authenticated identity and broker acknowledgment verified.`,ea(e,!0),{ids:[e.credential.apiKey.id]})}catch(e){return U(d,!0,`auth login --key: remote acknowledgment succeeded, but local activation could not be confirmed — ${S(e)}`,Gi)}}async function qi(e){let t=await Ni(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?_(`API key is already stored and its authenticated identity was verified.`,ea(e,!0),{ids:[e.credential.apiKey.id]}):U(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${H} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&ta(t.apiKey,e.credential.apiKey))try{let n=await Ke(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return _(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,ea(n,!0),{ids:[n.credential.apiKey.id]})}catch(t){return U(e,!0,`auth login --key: credential is valid but could not be promoted locally — ${S(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${H} 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 U(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 \`${H} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await Bi(e);if(n.outcome===`unconfirmed`)return U(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 Xe(e.host)}catch(t){return U(e,!1,`auth login --key: stale pending credential could not be removed — ${S(t,[e.credential.secret])}`)}return M.write(n.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
3
+ `),!0,!0,e.length));return}let i=t.ok?`OK`:`FAIL`;r.push(`[${i}] ${t.summary}`),!t.ok&&t.problem!==void 0&&r.push(...pr(t.problem)),r.push(...ur(t)),process.stdout.write(Te(r.join(`
4
+ `),!0))}function ur(e){let t=[];e.ids.length>0&&t.push(` ids: ${e.ids.join(`, `)}`);for(let[n,r]of Object.entries(e.counts))t.push(` ${n}: ${r}`);for(let n of e.references)t.push(` ref: ${n}`);if(e.truncation!==void 0){let n=e.truncation.omitted.join(`, `);t.push(` truncated: byteLength=${e.truncation.byteLength} maxBytes=${e.truncation.maxBytes} omitted=${n}`,` recovery: ${e.truncation.recovery}`)}for(let n of e.warnings)t.push(` warn: ${n}`);return t}function L(e,t){let n=we(t);if(e.mode===`data`||e.mode===`data-full`){let t=e.mode===`data`?ae(n,Ne(n,w)):n;_r(t),process.stdout.write(`${JSON.stringify(t.ok&&t.truncated!==!0?dr(t.data):t)}\n`),t.ok||(process.exitCode=1);return}let r=e.mode===`json`?cr(n):n;e.mode===`text`&&lr(r),r.ok||(process.exitCode=1)}function dr(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 fr(e,t){let n=Me(t);if(n===null){process.stderr.write(`explain: the response carried no search interpretation
5
+ `),process.exitCode=1;return}(e===`text`?process.stdout:process.stderr).write(n)}function pr(e){let t=[];typeof e.code==`string`&&t.push(` code: ${e.code}`),typeof e.detail==`string`&&t.push(` detail: ${e.detail}`),typeof e.hint==`string`&&t.push(` hint: ${e.hint}`),typeof e.suggestion==`string`&&t.push(` suggestion: ${e.suggestion}`);let n=Object.entries(e.suggestions??{});if(n.length>0){let e=n.map(([e,t])=>`${e}=${t}`).join(`; `);t.push(` suggestions: ${e}`)}return typeof e.requiredRole==`string`&&t.push(` requiredRole: ${e.requiredRole}`),t.push(...mr(e),...hr(`unknownParameters`,e.unknownParameters),...hr(`validParameters`,e.validParameters),...gr(e.resolution)),t}function mr(e){let t=[];return 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?[` meter: ${t.join(` `)}`]:[]}function hr(e,t){return t!=null&&t.length>0?[` ${e}: ${t.join(`, `)}`]:[]}function gr(e){if(e==null)return[];let t=[`action=${e.action}`];return 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}`),[` resolution: ${t.join(` `)}`]}function _r(e){e.ok&&e.warnings.length===0||a({component:b().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 vr(e,t,n=b().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 g(`Invalid --limit value: ${JSON.stringify(e.limit)} (expected a non-negative integer)`,["Pass a non-negative integer, e.g. `--limit 20`."]);let i=Oe(t,n),a=Ie(e.root??``),o=[...new Set(i.map(({cli:e})=>Ie(e.path.at(0)??``)))].toSorted();if(a.length>0&&!o.includes(a))return g(`Unknown --root value: ${JSON.stringify(e.root)}`,[`Pass one of: ${o.join(`, `)}.`]);let s=je(e.q??``,i.filter(t=>xr(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]),directParameterName:e.flags.filter(({location:e})=>e!==`body`).map(({wireName:e})=>e),parameterDescription:[e.body.description,...e.flags.map(({description:e})=>e)]})).map(({item:e})=>e),c=s.slice(0,r);return _(`Operation catalog matches`,{operation:c,count:{totalOperations:t.length,matched:s.length,returned:c.length}})}function yr(e,t,n=b().bin[0]){let r=Oe(t,n),i=e.operationId===void 0?br(r,e.command):r.find(t=>t.operationId===e.operationId);if(i===void 0){let i=Er(e.command??``),a=r.map(e=>e.cli.command).filter(e=>e.startsWith(`${n} ${i} `));if(a.length>0)return g(`${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=vr({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 g(`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 _(`Generated operation detail`,{operation:i,usage:Cr(i,r)})}function br(e,t){if(t===void 0)return;let{bin:n}=b(),r=Er(t,n);return e.find(e=>Er(e.cli.command,n)===r)}var R=(e,t)=>e===void 0||e===`all`||e===`any`||e===String(t);function xr(e,t){return(t.root===void 0||Sr(e,t.root))&&R(t.scope,e.scope)&&R(t.mutates,e.mutates)&&R(t.destructive,e.destructive)&&R(t.intent,e.intent)&&R(t.method,e.method)}function Sr(e,t){let n=Ie(t);return n.length===0||Ie(e.cli.path.at(0)??``)===n}function Cr(e,t){let n=Ee(e);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 (CLI-only operation)`}`,e.body.hasBody?`body: kind=${e.body.kind??`unknown`} required=${e.body.required} requiredPath=${e.body.requiredPath.join(`,`)}`:`body: none`,...e.successResponse===void 0?[]:[`success: ${e.successResponse}`],...[!0,!1].flatMap(t=>[`path`,`query`,`header`,`body`].map(r=>{let i=n.filter(e=>e.required===t&&e.location===r),a=Tr(`${t?`required`:`optional`} ${r} flags`,i);return t&&r===`body`&&e.body.kind===`json`&&i.length>0?`${a} (required unless --from-file sets JSON key(s) ${i.map(({wireName:e})=>e).join(`, `)})`:a})),...De(e,t),...wr(e.errorResponse),``,e.summary,e.description].filter(e=>e.length>0).join(`
6
+ `)}function wr(e){return e.length===0?[]:[`Errors:`,...e.map(({status:e,description:t})=>` ${e} ${t}`)]}function Tr(e,t){return`${e}: ${t.length===0?`none`:t.map(e=>e.name).join(` `)}`}function Er(e,t=b().bin){let[n=``,...r]=e.trim().split(/\s+/u);return(t.includes(n)?r:[n,...r]).join(` `)}var Dr=`dist/aventure-cli/command-catalog.compact.txt`,Or=` · `,kr=`-`;function Ar(e=b().bin[0]){return k(jr(O(Jt(import.meta.url)),e),Dr)}function jr(e,t){let n=e;for(;;){if(A(k(n,`package.json`)))return n;let r=O(n);if(r===n)throw Error(`No package.json above ${e}; ${t} is not in a package layout.`);n=r}}function Mr(e,t){let n=t.join(` `).trim();return n.length===0?e:{...e,q:e.q===void 0?n:`${e.q} ${n}`}}function Nr(e,t,n,r=b().bin[0]){let i=vr(e,t,r);if(!i.ok||i.data===null){L({mode:n},i);return}Fr({opts:e,mode:n,data:i.data,defaultFormat:`lines`,rendered:Rr(i.data,Lr(e.format,`lines`)),summary:`Generated operation matches`})}function Pr(e,t,n,r=b().bin[0]){let i=yr(e,t,r);if(!i.ok||i.data===null){L({mode:n},i);return}Fr({opts:e,mode:n,data:i.data,defaultFormat:`usage`,rendered:zr(i.data,Lr(e.format,`usage`)),summary:`Generated operation detail`})}function Fr(e){let t=e.mode,n=Lr(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`)){L({mode:t},g(`--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.matched===0&&(r||e.opts.format===void 0||n===`text`)?`No generated operations matched.`:e.rendered,a=i.endsWith(`
7
+ `)?i:`${i}\n`;if(e.opts.output!==void 0){Vt(e.opts.output,a),L({mode:t},_(e.summary,{outputPath:e.opts.output,byteLength:Buffer.byteLength(a,`utf8`),format:n},{counts:Wr(e.data)}));return}if(t===`text`){Ir(e.summary,a);return}L({mode:t},_(e.summary,e.data,{counts:Wr(e.data)}))}function Ir(e,t){let n=we(_(e,t));if(!n.ok||n.data===null){L({mode:`text`},n);return}process.stdout.write(n.data.endsWith(`
8
+ `)?n.data:`${n.data}\n`)}function Lr(e,t){return e??t}function Rr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?e.operation.map(e=>JSON.stringify(e)).join(`
9
+ `):t===`text`?Hr(e.operation):t===`compact`?e.operation.map(Br).join(`
10
+ `):e.operation.map(Ur).join(`
11
+ `)}function zr(e,t){return t===`json`?JSON.stringify(e,null,2):t===`ndjson`?JSON.stringify(e.operation):t===`lines`?Ur(e.operation):t===`compact`?Br(e.operation):e.usage}function Br(e){let t=Vr(e);return[e.cli.command,e.summary,t.length===0?kr:t.join(` `)].join(Or)}function Vr(e){return e.flags.filter(t=>t.required&&(t.contentType===void 0||t.contentType===e.body.contentType)).map(e=>e.name)}function Hr(e){return e.map(e=>`${e.cli.command}\n ${Ur(e)}`).join(`
12
+ `)}function Ur(e){let t=Vr(e);return[z(`operationId`,e.operationId),z(`scope`,e.scope),z(`mutates`,String(e.mutates)),z(`destructive`,String(e.destructive)),z(`intent`,e.intent),z(`resource`,e.resource),z(`cli`,e.cli.command),e.mcpTool===null?``:z(`mcpTool`,e.mcpTool),z(`method`,e.method),z(`path`,e.path),z(`auth`,e.auth),z(`flags`,[...new Set(e.flags.map(e=>e.name))].join(` `)),z(`requiredFlags`,t.join(` `)),z(`bodyKind`,e.body.kind??``),z(`bodyRequired`,String(e.body.required)),z(`summary`,e.summary)].filter(e=>e.length>0).join(` `)}function z(e,t){return t.length===0?``:`${e}=${JSON.stringify(t)}`}function Wr(e){return`count`in e?e.count:{returned:1}}function Gr(e,t,n=b().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(`
13
+ `)).argument(`[command...]`,"command path, operationId, or METHOD and path, e.g. `help entities get`"),r.addOption(new Kr(r)),r.hook(`preSubcommand`,e=>{e.opts().help&&e.help()});let i=Qr(t);i!==void 0&&r.option(`--ask <question>`,i.summary),E(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=T(a);if(r.length>0){L({mode:e},g(`Use either a command path or --ask, not both.`));return}L({mode:e},await ni(i,a.ask,a.environment,e));return}let o=ti(e,r),s=t.find(t=>o!==void 0&&ti(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?ei(r,t):_(`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){L({mode:T(a)},c);return}Pr({...a,...c.data},t,T(a,`text`),n)}),Zr(e,t,n)}var Kr=class extends e{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))}},qr=2,Jr=6,Yr={formatHelp(e,t){let r=r=>n.prototype.formatHelp.call(this,e,Object.assign(Object.create(t),r));if(t.visibleCommands(e).length===0)return r({});let i=t.padWidth(e,t),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 t=n.prototype.visibleCommands.call(this,e);return e.parent===null?t.filter(e=>!Ve.has(e.name())):t},subcommandTerm(e){let t=n.prototype.subcommandTerm.call(this,e);return e.commands.length>0&&e.registeredArguments.length===0?`${t} <command>`:t},formatItem(e,t,r,i){let a=i.helpWidth??80,o=a-t-4;return r===``||o>=i.minWidthToWrap?n.prototype.formatItem.call(i,e,t,r,i):`${` `.repeat(qr)}${e}\n${Xr(r,a,i)}`}};function Xr(e,t,n){return n.boxWrap(e,t-Jr).replace(/^/gmu,` `.repeat(Jr))}function Zr(e,t,n){for(let r of t){let i=ti(e,r.cliPath);i!==void 0&&i.addHelpText(`after`,()=>{let e=i.createHelp(),a=i.configureOutput().getOutHelpWidth?.();e.prepareContext(a===void 0?{}:{helpWidth:a});let o=e.helpWidth??80,s=Ae(r.operationId,t,n),[c,...l]=wr(r.errorResponse),u=l.map(t=>Xr(t.trimStart(),o,e).replace(/^ +/u,` `.repeat(qr))),d=c===void 0?[]:[``,c,...u];return`\n${[...s,...d].join(`
14
+ `)}\n`})}}function Qr(e){let[t,...n]=e.filter(e=>{let[t,n,...r]=e.cliPath;return t===`help`&&n!==void 0&&r.length===0&&ri(e)!==void 0});return n.length===0?t:void 0}var $r='Accepted selectors: `<METHOD> <route template or concrete path>`, an operationId, or a CLI command path such as "entities get".';function ei(e,t){let[n,...r]=e,i=he.find(e=>e===n?.toLowerCase());if(i===void 0||r.length===0){let n=e.join(` `).trim();return _(`Resolved by name`,t.some(e=>e.operationId===n)?{operationId:n}:{command:n})}let a=ge(i),o=r.join(``),s=t.find(e=>e.method===a&&e.path===o);if(s!==void 0)return _(`Resolved by route template`,{operationId:s.operationId});let c=ie({method:a,path:o});return!c.ok||c.data===null?g(c.summary,[...c.warnings,$r]):_(`Resolved by method and path`,{operationId:c.data.operation.operationId})}function ti(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 ni(e,t,n,r){let i=ri(e);if(i===void 0)return g(`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 Kn(e,{[i.optionKey]:t});return a.ok?await p({method:e.method,path:m(e.operationId,{}),searchParams:{},body:a.data,auth:e.auth,responseFormat:Dt(r)?`json`:`auto`}):a}function ri(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 ii(e,t,n){if(e.cliPath[0]!==`lookup`||!ai(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?g(i):g(i,[],{httpStatus:n.httpStatus,problem:n.problem})}function ai(e){return e.ok?Array.isArray(e.data)&&e.data.length===0:e.httpStatus===404}function oi(e,t){if(e.deprecated!==!0)return t;let n=e.description.match(/^Deprecated:[^.]*\./u)?.[0]??`Deprecated; run \`help ${e.cliPath.join(` `)}\` for its replacement.`;return{...t,warnings:[n,...t.warnings]}}var si=f({artifact:d().nullish(),group:d().nullish(),name:d().nullish(),revision:d().nullish(),time:c({offset:!0}).nullish(),version:d().nullish()}),ci=f({build:si}),li=l([`MACOS`,`LINUX`,`WINDOWS`,`OTHER`]),ui=l([`RSA_OAEP_256_A256_GCM_V1`]),di=f({clientLabel:d().regex(/.*\S.*/).min(1).max(120).nullish(),clientPlatform:li.nullish(),encryptionAlgorithm:ui.nullish(),encryptionPublicKey:d().min(344).max(12e3).nullish()}),fi=32;async function pi(){let e=await Zt.subtle.generateKey({name:`RSA-OAEP`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:`SHA-256`},!0,[`encrypt`,`decrypt`]),t=await Zt.subtle.exportKey(`spki`,e.publicKey);return{publicKey:Buffer.from(t).toString(`base64`),privateKey:e.privateKey}}async function mi(e,t){let{wrappedKey:n,nonce:r,ciphertext:i,authenticationTag:a}=t,o=hi(n,`wrapped key`,128,1024),s=hi(r,`nonce`,12,12),c=hi(i,`ciphertext`,1,65536),l=hi(a,`authentication tag`,16,16),u;try{u=await Zt.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!==fi)throw Error(`broker credential used an invalid AES-256 key`);let e=await Zt.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 Zt.subtle.decrypt({name:`AES-GCM`,iv:s,tagLength:128},e,t)}catch{throw Error(`broker credential payload failed authentication`)}let r=new Ut(`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 hi(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 gi=l([`PENDING`,`ISSUING`,`KEY_READY`,`REVOKING`,`CONSUMED`,`REVOKED`,`DENIED`,`EXPIRED`,`FAILED`]),_i=l([`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`]),vi=f({approvedAt:c({offset:!0}).nullish(),clientLabel:d(),clientPlatform:li,comparisonCode:d(),consumedAt:c({offset:!0}).nullish(),createdAt:c({offset:!0}),expiresAt:c({offset:!0}),id:s(),intervalSeconds:u().int().min(1),keyReadyAt:c({offset:!0}).nullish(),status:gi,terminalAt:c({offset:!0}).nullish(),terminalReason:_i.nullish(),updatedAt:c({offset:!0})}),yi=f({algorithm:ui,authenticationTag:d(),ciphertext:d(),nonce:d(),wrappedKey:d()}),bi=f({delivery:yi.nullish(),expiresAt:c({offset:!0}),status:gi,terminalReason:_i.nullish()}),xi=f({comparisonCode:d(),expiresAt:c({offset:!0}),id:s(),intervalSeconds:u().int().min(1),pollSecret:d(),verificationUrl:d()}),B=[{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. Use --no-browser for OAuth device authorization only when the issuer advertises device-grant support; otherwise use --key --no-browser for API-key approval.`,operationId:`getAuthProviderCatalog`,method:`GET`,path:`/v1/auth/providers`,bodyOption:[],localOption:[{optionKey:`browser`,flag:`--no-browser`,description:`Use OAuth device authorization only when the issuer advertises device-grant support: print a sign-in URL and code, then wait for approval. Otherwise use --key --no-browser for API-key approval.`},{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 API-key approval URL and wait for approval 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.`}]}],Si=x(B,`start`),Ci=x(B,`poll`),wi=x(B,`acknowledge`),V=class extends Error{httpStatus;retryAfterSeconds;retryable;constructor(e,t,n=[]){super(`CLI authorization ${e} failed: ${Ge(t,n)}`),this.name=`CliAuthorizationRequestError`,this.httpStatus=t.status,this.retryAfterSeconds=Ai(t.retryAfterSeconds),this.retryable=t.status>=500||t.status===429}},Ti=class extends Error{constructor(e,t,n=[]){super(`CLI authorization ${e} transport failed: ${S(t,n)}`,{cause:t}),this.name=`CliAuthorizationTransportError`}};async function Ei(e){let t=await re(We(v()),{method:Si.method,path:ve(Si.path,{},Si.operationId),headers:{},contentType:`application/json`,body:e},xi);if(t.ok&&t.redirect)throw new V(`start`,ji(t.status));if(!t.ok)throw new V(`start`,t.problem);return Mi(t.data)}async function Di(e,t){let n=ne(Ci.operationId),r=await re(We(v()),{method:Ci.method,path:ve(Ci.path,{cliAuthorizationId:e},Ci.operationId),headers:{[n]:t}},bi);if(r.ok&&r.redirect)throw new V(`poll`,ji(r.status),[t]);if(!r.ok)throw new V(`poll`,r.problem,[t]);return{authorization:r.data,retryAfterSeconds:ki(r.headers[`retry-after`])}}async function Oi(e,t){let n=ne(wi.operationId),r;try{r=await re(We(v()),{method:wi.method,path:ve(wi.path,{cliAuthorizationId:e},wi.operationId),headers:{[n]:t}},vi)}catch(e){throw new Ti(`acknowledge`,e,[t])}if(r.ok&&r.redirect)throw new V(`acknowledge`,ji(r.status),[t]);if(!r.ok)throw new V(`acknowledge`,r.problem,[t]);return r.data}function ki(e){if(e===void 0)return null;let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function Ai(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function ji(e){return{status:e,title:`Unexpected redirect`,type:`about:blank`,code:void 0,detail:`CLI authorization endpoint returned an unexpected redirect`}}function Mi(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())})`},[Wt.custom]:{enumerable:!1,value:a}})}async function Ni(e){let t=await Pi(e.credential.secret);if(t.state!==`verified`||e.activation!==`active`)return{stored:e,verification:t};try{return{stored:await Ke(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 — ${S(n,[e.credential.secret])}`}}}}async function Pi(e){let t=We(v()),n;try{n=await re(t,{method:`GET`,path:m(`getCurrentApiKey`,{}),headers:{Authorization:`Bearer ${e}`}},tt)}catch(t){return{state:`unavailable`,summary:`identity verification failed before an HTTP response — ${S(t,[e])}`}}return n.ok&&n.redirect?{state:`unavailable`,summary:`identity verification returned unexpected redirect ${n.status}`}: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: ${Ge(n.problem,[e])}`}}var Fi=x(B,`revoke`);async function Ii(e){let t;try{t=C(v().host)}catch(e){return g(`auth logout: invalid API host — ${S(e)}`)}let n=await Li(t),r=await Bi(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`?_(`No CLI credential is stored for this API host.`,a):n.state===`failed`?{...g(`auth logout: ${i[0]}`),data:a}:_(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 Li(e){let t=await lt(e);if(t.state===`missing`)return{state:`missing`};let n=t.state===`found`?await zi(t.stored):{revoked:!1};try{await rt(e)}catch(e){return{state:`failed`,summary:S(e)}}return{state:`forgotten`,...n}}async function Ri(e){let t=Reflect.get(await ht(e),`revocation_endpoint`);return typeof t==`string`?ot(t,`revocation endpoint`,!0):void 0}async function zi(e){let{client:t,tokens:n}=e.credential,r=n.refresh_token??n.access_token;try{let e=await Ri(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:ft(t)})});return n.ok?{revoked:!0}:{revoked:!1,summary:`revocation endpoint answered ${n.status}`}}catch(e){return{revoked:!1,summary:S(e,ct(n))}}}async function Bi(e,t){let n;try{n=await Je(e)}catch(e){return g(`auth logout: stored credential could not be read — ${S(e)}`)}if(n.state===`unavailable`)return{...g(`auth logout: ${n.summary}`),data:{host:e,revoked:!1,forgotten:!1}};if(n.state===`missing`)return null;let r=n.stored,i=await Vi(r),a=i.outcome===`revoked`,o=r.activation===`pending`&&i.outcome===`rejected`;if(!a&&!o&&!t.forgetLocal)return{...g(`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:Hi(r,!1,!1)};try{await Xe(r.host)}catch(e){return{...g(`auth logout: local credential removal failed — ${S(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:Hi(r,a,!1)}}return _(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.`,Hi(r,a,!0),{ids:[r.credential.apiKey.id],warnings:a||o?[]:[`Remote revocation was not confirmed; the API key may remain active.`]})}async function Vi(e){let t=We(v());try{let n=await re(t,{method:Fi.method,path:ve(Fi.path,{},Fi.operationId),headers:{Authorization:`Bearer ${e.credential.secret}`}},tt);return n.ok&&n.redirect?{outcome:`unconfirmed`,summary:`remote key revocation returned unexpected redirect ${n.status}`}: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:Ge(n.problem,[e.credential.secret])}}catch(t){return{outcome:`unconfirmed`,summary:S(t,[e.credential.secret])}}}function Hi(e,t,n){return{host:e.host,apiKeyId:e.credential.apiKey.id,activation:e.activation,revoked:t,forgotten:n}}var Ui=`RSA_OAEP_256_A256_GCM_V1`,Wi=1,Gi=30,H=b().bin[0],Ki=`The local record remains pending and unavailable to ordinary commands. Re-run \`${H} auth login --key\`; it recovers the credential when the broker acknowledged it, and otherwise clears the stale record.`;async function qi(e){if(!Ht.isTTY)return g(`${H} 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=v().host;t=C(e),n=nt(e)}catch(e){return g(`auth login --key: invalid environment configuration — ${S(e)}`)}for(;;){let e;try{e=await Qe(t)}catch(e){return g(`auth login --key: credential storage could not be inspected — ${S(e)}`)}if(e.state===`unavailable`)return g(`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&&M.write($e(e.keyringFailure));break}let n=await Ji(e.stored);if(n!==null)return n}let r;try{r=await pi()}catch(e){return g(`auth login --key: ephemeral encryption key could not be created — ${S(e)}`)}let i=di.safeParse({clientLabel:e.clientLabel?.trim()||(Kt().trim()||H).slice(0,120),clientPlatform:Qi(),encryptionAlgorithm:Ui,encryptionPublicKey:r.publicKey});if(!i.success)return g(`auth login --key: ${o(i.error)}`);let a;try{a=await Ei(i.data)}catch(e){return g(`auth login --key: could not start browser authorization — ${S(e)}`)}let s;try{s=Ye(a,n)}catch(e){return g(`auth login --key: unsafe browser authorization URL rejected — ${S(e)}`)}if(!Zi(await Ze(a,n,{noBrowser:e.noBrowser}),a,s))return g(`auth login --key: browser authorization requires an interactive terminal for manual handoff`,[`Automatic browser opening did not complete, and the approval URL was withheld because stderr is not an interactive terminal. Retry from an interactive terminal.`],{references:[s]});let c;try{c=await Xi(a)}catch(e){return g(`auth login --key: authorization did not complete — ${S(e)}`,[],{references:[s]})}if(c.algorithm!==Ui)return g(`auth login --key: broker selected an unsupported encryption algorithm`);let l;try{l=await mi(r.privateKey,c)}catch(e){return g(`auth login --key: encrypted credential could not be opened — ${S(e)}`)}let u=await Pi(l);if(u.state!==`verified`)return g(`auth login --key: decrypted credential was neither stored nor acknowledged — ${u.summary}`);let d;try{d=await Ke(t,{apiKey:u.apiKey,secret:l},`pending`)}catch(e){return g(`auth login --key: credential could not be durably stored — ${S(e)}`)}let f;try{f=await Yi(a)}catch(e){return U(d,!0,`auth login --key: credential was stored and verified, but broker acknowledgment was not confirmed — ${S(e,[a.pollSecret])}`,Ki)}if(f.status!==`CONSUMED`)return U(d,!0,`auth login --key: broker returned ${f.status} after acknowledgment`,Ki);let p=await Pi(l);if(p.state!==`verified`||!na(p.apiKey,d.credential.apiKey))return U(d,!0,`auth login --key: broker acknowledgment succeeded, but refreshed credential metadata could not prove the granted lifetime — ${p.summary}`,Ki);try{let e=await Ke(t,{apiKey:p.apiKey,secret:l},`active`);return _(`API key stored; authenticated identity and broker acknowledgment verified.`,ta(e,!0),{ids:[e.credential.apiKey.id]})}catch(e){return U(d,!0,`auth login --key: remote acknowledgment succeeded, but local activation could not be confirmed — ${S(e)}`,Ki)}}async function Ji(e){let t=await Pi(e.credential.secret);if(e.activation!==`pending`)return t.state===`verified`?_(`API key is already stored and its authenticated identity was verified.`,ta(e,!0),{ids:[e.credential.apiKey.id]}):U(e,!1,`auth login --key: stored credential ${t.state} — ${t.summary}`,`Run \`${H} auth logout\` to revoke/remove it before authorizing a replacement.`);if(t.state===`verified`&&na(t.apiKey,e.credential.apiKey))try{let n=await Ke(e.host,{apiKey:t.apiKey,secret:e.credential.secret},`active`);return _(`Recovered pending CLI credential: broker acknowledgment had succeeded.`,ta(n,!0),{ids:[n.credential.apiKey.id]})}catch(t){return U(e,!0,`auth login --key: credential is valid but could not be promoted locally — ${S(t,[e.credential.secret])}`,`The remote key remains valid. Re-run \`${H} 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 U(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 \`${H} auth login --key\` when the API is reachable; it recovers an acknowledged credential and clears an unacknowledged one.`);let n=await Vi(e);if(n.outcome===`unconfirmed`)return U(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 Xe(e.host)}catch(t){return U(e,!1,`auth login --key: stale pending credential could not be removed — ${S(t,[e.credential.secret])}`)}return M.write(n.outcome===`revoked`?`Revoked and cleared a stale pending CLI credential; starting a fresh browser authorization.
15
15
  `:`Cleared a stale pending CLI credential whose remote key can no longer authenticate; starting a fresh browser authorization.
16
- `),null}async function Ji(e){let t=new Date(e.expiresAt).getTime(),n=Qi(e.intervalSeconds);for(;;)try{return await Di(e.id,e.pollSecret)}catch(e){if(e instanceof V){if(!e.retryable)throw e;n=Qi(e.retryAfterSeconds??n)}else if(!(e instanceof wi))throw e;if(Date.now()>=t)throw e;M.write(`Broker acknowledgment was interrupted; retrying.
17
- `),await $i(n,t)}}async function Yi(e){let t=new Date(e.expiresAt).getTime(),n=Qi(e.intervalSeconds),r;for(M.write(`Waiting for browser approval...
18
- `);Date.now()<t;){let i;try{i=await Ei(e.id,e.pollSecret)}catch(e){if(e instanceof V){if(!e.retryable)throw e;n=Qi(e.retryAfterSeconds??n)}r=e,M.write(`Authorization poll was interrupted; retrying.
19
- `),await $i(n,t);continue}r=void 0;let a=i.authorization;switch(a.status){case`PENDING`:case`ISSUING`:case`REVOKING`:n=Qi(i.retryAfterSeconds??n),await $i(n,t);break;case`KEY_READY`:if(a.delivery===null||a.delivery===void 0)throw Error(`broker returned KEY_READY without an encrypted delivery`);return a.delivery;case`DENIED`:case`EXPIRED`:case`FAILED`:throw Error(Ce(a.terminalReason?.trim()??``,[e.pollSecret])||`broker entered terminal state ${a.status}`);case`CONSUMED`:throw Error(`broker credential was already consumed; restart login`)}}throw Error(r===void 0?`browser authorization expired before approval completed`:`browser authorization expired after a retryable broker failure: ${S(r,[e.pollSecret])}`)}function Xi(e,t,n){let r=e.state===`opened`;return!r&&!M.isTTY?!1:(M.write([r?`Browser approval opened for this request.`:`Browser not opened automatically (${e.reason}).`,...M.isTTY?[`Open this one-time approval URL in your browser:`,t.verificationUrl]:[`Approval reference: ${n}`],`Comparison code: ${t.comparisonCode}`,`Confirm that the browser shows the same code before approving.`,``].join(`
20
- `)),!0)}function Zi(){switch(qt()){case`darwin`:return`MACOS`;case`linux`:return`LINUX`;case`win32`:return`WINDOWS`;default:return`OTHER`}}function Qi(e){return Math.min(Wi,Math.max(Ui,e))}async function $i(e,t){let n=t-Date.now();n>0&&await Yt(Math.min(e*1e3,n))}function ea(e,t){return{host:e.host,provider:e.provider,apiKeyId:e.credential.apiKey.id,name:Ce(e.credential.apiKey.name,[e.credential.secret]),activation:e.activation,verified:t}}function U(e,t,n,r){return{...g(n,r===void 0?[]:[r]),data:ea(e,t)}}function ta(e,t){return e.expiresAt===null||e.expiresAt===void 0||t.expiresAt===null||t.expiresAt===void 0?!1:new Date(e.expiresAt)>new Date(t.expiresAt)}async function na(){return null}async function ra(e){let t=null,n=e=>{t=e};try{await dt(e,n),await et(n)}catch(e){return{materialized:t,failure:S(e)}}return{materialized:t,failure:null}}async function ia(e,t,n,r){if(r.failure!==null)return{scope:e,selected:null,identity:null,authorization:null,error:r.failure};let i=null,a=null,o,s=e=>{o=e,a=aa(e.credential,r.materialized)};try{let t=await p({method:`POST`,path:`/v1/auth/me/permissions`,body:{operation:[]},auth:e,requesterScope:e,responseFormat:`json`,onAuthPrepared:s});if(!t.ok)throw Error(oa(t));if(a===null)throw Error(`Live permission probe did not prepare a credential`);if(i=ua(t.data),e===`read`)return{scope:e,selected:a,identity:null,authorization:i,error:null};if(o===void 0)throw Error(`Live permission probe did not retain its prepared credential`);let n=await na(e,o);return{scope:e,selected:a,identity:n,authorization:i,error:null}}catch(r){return{scope:e,selected:a,identity:null,authorization:i,error:S(r,sa(t,n,o))}}}function aa(e,t){if(e===null)return null;let n=t??qe().source;if(n===null)throw Error(`Prepared credential has no local provenance`);return{credential:e,source:n}}function oa(e){return[e.summary,...e.warnings].join(` — `)}function sa(e,t,n){return[v().userBearerToken,...Se(n?.headers??{}),...e.state===`found`?ct(e.stored.credential.tokens):[],t.state===`found`?t.stored.credential.secret:void 0]}function ca(e,t,n=null){let r=t.state===`found`?t.stored:void 0,i=r?.credential.apiKey.expiresAt??null;return{host:e,present:r!==void 0,provider:r?.provider??null,activation:r?.activation??null,apiKeyId:r?.credential.apiKey.id??null,subject:r?.credential.apiKey.subject??null,scope:r?.credential.apiKey.scopes??[],name:r===void 0?null:Ce(r.credential.apiKey.name,[r.credential.secret]),status:r?.credential.apiKey.status??null,expiresAt:i,metadataSource:r===void 0?null:n?.state===`verified`?`clerk`:`store-cache`,live:n===null?null:{state:n.state,summary:n.summary},expiresInDay:pa(i),storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function la(e,t){let n=t.state===`found`?t.stored:void 0;return{host:e,present:n!==void 0,provider:n?.provider??null,expiresAt:n?.credential.expiresAt??null,expired:n===void 0?null:it(n.credential),renewable:n===void 0?null:n.credential.tokens.refresh_token!==void 0,identity:n===void 0?null:at(n.credential),client:n?.credential.client??null,storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function ua(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)throw Error(`permission probe returned no JSON response`);let t=ee.safeParse(e.response);if(!t.success)throw t.error;return t.data}function da(e,t){let{expiresAt:n,expiresInDay:r}=ca(e,t);return n!==null&&r!==null&&new Date(n).getTime()<=Date.now()?` (cached expiry passed ${Math.abs(r)}d ago; \`auth status\` re-checks it with aVenture sign-in)`:``}var fa=864e5;function pa(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/fa)}var ma=7;function ha(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,ma)}\u2026${e.slice(-4)}`}var ga=13,_a=14;function va(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.apiKey.host}`+(e.apiVersion===null?` (api build unavailable)`:` (api ${e.apiVersion})`),``,...ba(e.oauth,e.cliName,e.refresh),...Sa(e.apiKey,e.oauth,e.cliName),``,W(`Providers`,Ta(e.providers)),W(`Environment`,Ea(e.resolved)),W(`Selected`,Da(e.resolved,e.refresh,e.cliName)),...ya(e.live),...e.systemOk?[]:[W(`System`,`uptime read failed`)]].join(`
21
- `)}function ya(e){if(e===null)return[];let t=G(`local credential provenance was captured before verification`);if(e.error!==null)return[``,W(`Live probe`,`${e.scope} permission probe failed`),t,G(e.error)];if(e.authorization===null)return[];let n=e.authorization.permissionGrant,r=e.identity;return[``,W(`Live probe`,`${e.scope} permission probe succeeded`),t,G(`operation access ${e.authorization.operationAccess}; ${n.role.length} role; ${n.permission.length} permission`),...r===null?[G(e.scope===`read`?`identity not requested for a read-scope credential`:`identity unavailable in this build`)]:[W(`Live account`,r.nameFull??r.email??r.clerkUserId??r.id)],G(`no API operation was executed or individually authorized`)]}function W(e,t){return` ${e.padEnd(ga)}${t}`}function G(e){return` ${``.padEnd(ga)}${e}`}function ba(e,t,n){switch(e.state){case`found`:{let{credential:r,provider:i}=e.stored,a=at(r);return[W(`OAuth`,`${a.email??a.subject??`unknown identity`} via ${i}`),G(xa(r,t,n))]}case`missing`:return[W(`OAuth`,`none stored`),...e.keyringFailure===void 0?[]:[G(`OS keyring unusable — login stores to file: ${e.keyringFailure}`)]];case`unavailable`:return[W(`OAuth`,`storage unavailable: ${e.summary}`)];case`invalid`:return[W(`OAuth`,`stored credential invalid: ${e.summary}`)];default:throw Error(`Unsupported OAuth credential state`)}}function xa(e,t,n){return it(e)?e.tokens.refresh_token===void 0?`access token expired — run \`${t} auth login\``:n.failure===null?n.materialized===`api-key`?`access token expired and renewal failed; the API key is in use — \`${t} auth login\` renews OAuth`:`access token expired — not renewed while AUTH_TOKEN is set in the environment`:`access token expired — ${n.failure}`:`access token valid until ${e.expiresAt}`}function Sa(e,t,n){if(!e.present){if(t.state===`found`)return[];let r=e.storageFailure??(t.state===`unavailable`?t.summary:null);return r===null?[W(`Signed in`,`no \u2014 run \`${n} auth login\``),...e.error===null?[]:[G(`stored credential invalid: ${e.error}`)]]:[W(`Signed in`,`credential storage unavailable`),G(r)]}return[W(t.state===`found`?`API key`:`Signed in`,e.subject??`unknown subject`),G(`via ${e.provider??`unknown store`}`),W(`Key`,`${e.name??`unnamed`} ${ha(e.apiKeyId)}`),...Ca(e,n),W(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function Ca(e,t){let n=e.live,r=e.expiresInDay,i=e.expiresAt;if(n?.state===`invalid`)return[W(`Key state`,`rejected by aVenture sign-in \u2014 ${n.summary}`),G(`run \`${t} auth logout\`, then \`${t} auth login --key\``)];let a=n?.state===`verified`;return[W(`Key state`,a?`${e.status??`unknown`}, verified by aVenture sign-in now`:`${e.status??`unknown`} when stored`),...i===null||r===null?[G(`no expiry recorded`)]:[G(wa(i,r,a?`expires`:`cached expiry`))],...a?[]:[G(n===null?"aVenture sign-in owns the live verdict — `auth status` re-checks it":`aVenture sign-in could not be reached \u2014 ${n.summary}`)]]}function wa(e,t,n){let r=e.slice(0,10);return new Date(e).getTime()<=Date.now()?`${n} ${r} passed ${Math.abs(t)}d ago`:t<=_a?`${n} ${r}, ${t}d away`:`${n} ${r}`}function Ta(e){if(e.state===`unavailable`)return`unavailable: ${e.summary}`;let t=e.catalog.oauthClient;return[e.catalog.clerkPublishableKey?`browser sign-in`:`no browser sign-in`,t?`oauth ${st(t).host} client ${t.clientId}`:`no OAuth CLI client`].join(`; `)}function Ea(e){return`${y.authToken}=${e.present?e.source??`resolved`:`unset`}`}function Da(e,t,n){return e.present||t.materialized===`env`?`${y.authToken} from the environment`:t.materialized===`oauth`?`saved OAuth access token`:t.materialized===`api-key`?`saved API key`:`none \u2014 sign in with \`${n} auth login\``}var Oa=`# >>> aventure-cli completion setup (managed by aventure-cli) >>>`,ka=`# <<< aventure-cli completion setup (managed by aventure-cli) <<<`,Aa=`.aventure-cli-completion.bak`;function ja(e,t){e.command(`install`).summary(`install shell completion loaders`).description(`Install managed shell completion loaders for supported shells.`).action(()=>Ra([])),e.command(`uninstall`).summary(`remove shell completion loaders`).description(`Remove managed shell completion loaders installed by ${t}.`).action(()=>Ra([`--uninstall`]))}function Ma(e,t){e.command(`setup`).summary(`configure zsh completion startup`).description(`Configure ~/.zshrc so zsh loads ${t} completion loaders.`).option(`--dry-run`,`print the managed zshrc block without writing`).option(`--yes`,`apply without prompting`).option(`--uninstall`,`remove the managed zshrc block`).action(async e=>{let t=Ia(),n=await Fa({rcFile:k(Gt(),`.zshrc`),installerPath:t,mode:e.uninstall?`uninstall`:`install`,dryRun:e.dryRun,prompter:e.yes||e.dryRun?void 0:Ya});j.stdout.write(`${n.message}\n`),!n.cancelled&&!e.dryRun&&Ra(e.uninstall?[`--uninstall`]:[])})}function Na(e,t=`fpath-only`){return[Oa,`# installer: ${e}`,'fpath=("${XDG_DATA_HOME:-$HOME/.local/share}/zsh/site-functions" $fpath)',...t===`fpath-and-compinit`?[`autoload -Uz compinit`,`compinit`]:[],ka].join(`
22
- `)}function Pa(){let e=Ra([`--status`],`pipe`);if(e.status!==0)return{refreshed:!1,message:`completion status exited ${e.status??1}`};if(!za(e.stdout??``))return{refreshed:!1,message:`no managed shell completions found`};let t=Ra([],`pipe`);return t.status===0?{refreshed:!0,message:(t.stdout??``).trim()||`shell completions refreshed`}:{refreshed:!1,message:`completion refresh exited ${t.status??1}`}}async function Fa({rcFile:e,installerPath:t,mode:n,dryRun:r=!1,prompter:i}){let a=Ba(e),o=a.length===0?[]:a.split(`
23
- `),s=Va(o,e);if(n===`uninstall`&&s===null)return{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:a};let c=n===`install`?Ha(o,s,t,e):Ua(o,s);return c===a?{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:c}:r?{changed:!0,cancelled:!1,message:c,content:c}:i!==void 0&&!await i(`Update ${e}?`)?{changed:!0,cancelled:!0,message:`${e}: unchanged; pass --yes to apply without a prompt`,content:a}:(Ka(e,c),{changed:!0,cancelled:!1,message:`${e}: updated`,content:c})}function Ia(e=j.argv[1]){let t=e===void 0?``:La(e),n=k(O(t),`..`,`..`,`scripts`,`install-zsh-completion-loader.mjs`);return A(n)?n:k(O(t),`..`,`scripts`,`install-zsh-completion-loader.mjs`)}function La(e){try{return Rt(e)}catch{return k(e)}}function Ra(e,t=`inherit`){let n=Ot(j.execPath,[Ia(),...e],{encoding:t===`pipe`?`utf8`:void 0,stdio:t});if(n.error!==void 0)throw n.error;if(t===`inherit`){n.status!==0&&(j.exitCode=n.status??1);return}return{stdout:n.stdout?.toString(),stderr:n.stderr?.toString(),status:n.status}}function za(e){return e.split(/\r?\n/u).some(e=>e.trim().endsWith(`: managed`))}function Ba(e){return A(e)?(qa(e),Ft(e,`utf8`)):``}function Va(e,t){let n=Wa(e,Oa),r=Wa(e,ka);if(n.length===0&&r.length===0)return null;if(n.length!==1||r.length!==1||n[0]>=r[0])throw Error(`${t} has malformed managed completion setup markers; fix manually before retrying.`);return[n[0],r[0]]}function Ha(e,t,n,r){let i=t===null?[...e]:[...e.slice(0,t[0]),...e.slice(t[1]+1)],a=Ga(i),o=Na(n,a===-1?`fpath-and-compinit`:`fpath-only`).split(`
24
- `),s=t===null?a:t[0],c=s===-1?i.length:s;if(t!==null&&a!==-1&&a<c)throw Error(`${r} runs compinit before the managed block; move the block above compinit manually.`);return Ja([...i.slice(0,c),...o,...i.slice(c)])}function Ua(e,t){return Ja(t===null?e:[...e.slice(0,t[0]),...e.slice(t[1]+1)])}function Wa(e,t){return e.flatMap((e,n)=>e===t?[n]:[])}function Ga(e){return e.findIndex(e=>/^\s*(autoload\s+.*\bcompinit\b|compinit(?:\s|$))/.test(e))}function Ka(e,t){Nt(O(e),{recursive:!0}),A(e)&&(qa(e),qa(`${e}${Aa}`),jt(e,`${e}${Aa}`));let n=k(O(e),`.${D(e)}.${j.pid}.tmp`);qa(n),Vt(n,t,{mode:420}),zt(n,e)}function qa(e){if(A(e)&&Mt(e).isSymbolicLink())throw Error(`refusing to write symlink: ${e}`)}function Ja(e){let t=e.join(`
16
+ `),null}async function Yi(e){let t=new Date(e.expiresAt).getTime(),n=$i(e.intervalSeconds);for(;;)try{return await Oi(e.id,e.pollSecret)}catch(e){if(e instanceof V){if(!e.retryable)throw e;n=$i(e.retryAfterSeconds??n)}else if(!(e instanceof Ti))throw e;if(Date.now()>=t)throw e;M.write(`Broker acknowledgment was interrupted; retrying.
17
+ `),await ea(n,t)}}async function Xi(e){let t=new Date(e.expiresAt).getTime(),n=$i(e.intervalSeconds),r;for(M.write(`Waiting for browser approval...
18
+ `);Date.now()<t;){let i;try{i=await Di(e.id,e.pollSecret)}catch(e){if(e instanceof V){if(!e.retryable)throw e;n=$i(e.retryAfterSeconds??n)}r=e,M.write(`Authorization poll was interrupted; retrying.
19
+ `),await ea(n,t);continue}r=void 0;let a=i.authorization;switch(a.status){case`PENDING`:case`ISSUING`:case`REVOKING`:n=$i(i.retryAfterSeconds??n),await ea(n,t);break;case`KEY_READY`:if(a.delivery===null||a.delivery===void 0)throw Error(`broker returned KEY_READY without an encrypted delivery`);return a.delivery;case`DENIED`:case`EXPIRED`:case`FAILED`:case`REVOKED`:throw Error(Ce(a.terminalReason?.trim()??``,[e.pollSecret])||`broker entered terminal state ${a.status}`);case`CONSUMED`:throw Error(`broker credential was already consumed; restart login`)}}throw Error(r===void 0?`browser authorization expired before approval completed`:`browser authorization expired after a retryable broker failure: ${S(r,[e.pollSecret])}`)}function Zi(e,t,n){let r=e.state===`opened`;return!r&&!M.isTTY?!1:(M.write([r?`Browser approval opened for this request.`:`Browser not opened automatically (${e.reason}).`,...M.isTTY?[`Open this one-time approval URL in your browser:`,t.verificationUrl]:[`Approval reference: ${n}`],`Comparison code: ${t.comparisonCode}`,`Confirm that the browser shows the same code before approving.`,``].join(`
20
+ `)),!0)}function Qi(){switch(qt()){case`darwin`:return`MACOS`;case`linux`:return`LINUX`;case`win32`:return`WINDOWS`;default:return`OTHER`}}function $i(e){return Math.min(Gi,Math.max(Wi,e))}async function ea(e,t){let n=t-Date.now();n>0&&await Yt(Math.min(e*1e3,n))}function ta(e,t){return{host:e.host,provider:e.provider,apiKeyId:e.credential.apiKey.id,name:Ce(e.credential.apiKey.name,[e.credential.secret]),activation:e.activation,verified:t}}function U(e,t,n,r){return{...g(n,r===void 0?[]:[r]),data:ta(e,t)}}function na(e,t){return e.expiresAt===null||e.expiresAt===void 0||t.expiresAt===null||t.expiresAt===void 0?!1:new Date(e.expiresAt)>new Date(t.expiresAt)}async function ra(){return null}async function ia(e){let t=null,n=e=>{t=e};try{await dt(e,n),await et(n)}catch(e){return{materialized:t,failure:S(e)}}return{materialized:t,failure:null}}async function aa(e,t,n,r){if(r.failure!==null)return{scope:e,selected:null,identity:null,authorization:null,error:r.failure};let i=null,a=null,o,s=e=>{o=e,a=oa(e.credential,r.materialized)};try{let t=await p({method:`POST`,path:`/v1/auth/me/permissions`,body:{operation:[]},auth:e,requesterScope:e,responseFormat:`json`,onAuthPrepared:s});if(!t.ok)throw Error(sa(t));if(a===null)throw Error(`Live permission probe did not prepare a credential`);if(i=da(t.data),e===`read`)return{scope:e,selected:a,identity:null,authorization:i,error:null};if(o===void 0)throw Error(`Live permission probe did not retain its prepared credential`);let n=await ra(e,o);return{scope:e,selected:a,identity:n,authorization:i,error:null}}catch(r){return{scope:e,selected:a,identity:null,authorization:i,error:S(r,ca(t,n,o))}}}function oa(e,t){if(e===null)return null;let n=t??qe().source;if(n===null)throw Error(`Prepared credential has no local provenance`);return{credential:e,source:n}}function sa(e){return[e.summary,...e.warnings].join(` — `)}function ca(e,t,n){return[v().userBearerToken,...Se(n?.headers??{}),...e.state===`found`?ct(e.stored.credential.tokens):[],t.state===`found`?t.stored.credential.secret:void 0]}function la(e,t,n=null){let r=t.state===`found`?t.stored:void 0,i=r?.credential.apiKey.expiresAt??null;return{host:e,present:r!==void 0,provider:r?.provider??null,activation:r?.activation??null,apiKeyId:r?.credential.apiKey.id??null,subject:r?.credential.apiKey.subject??null,scope:r?.credential.apiKey.scopes??[],name:r===void 0?null:Ce(r.credential.apiKey.name,[r.credential.secret]),status:r?.credential.apiKey.status??null,expiresAt:i,metadataSource:r===void 0?null:n?.state===`verified`?`clerk`:`store-cache`,live:n===null?null:{state:n.state,summary:n.summary},expiresInDay:ma(i),storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function ua(e,t){let n=t.state===`found`?t.stored:void 0;return{host:e,present:n!==void 0,provider:n?.provider??null,expiresAt:n?.credential.expiresAt??null,expired:n===void 0?null:it(n.credential),renewable:n===void 0?null:n.credential.tokens.refresh_token!==void 0,identity:n===void 0?null:at(n.credential),client:n?.credential.client??null,storageFailure:t.state===`unavailable`?t.summary:null,keyringFailure:t.state===`missing`?t.keyringFailure??null:null,error:t.state===`invalid`?t.summary:null}}function da(e){if(typeof e!=`object`||!e||e instanceof Uint8Array)throw Error(`permission probe returned no JSON response`);let t=ee.safeParse(e.response);if(!t.success)throw t.error;return t.data}function fa(e,t){let{expiresAt:n,expiresInDay:r}=la(e,t);return n!==null&&r!==null&&new Date(n).getTime()<=Date.now()?` (cached expiry passed ${Math.abs(r)}d ago; \`auth status\` re-checks it with aVenture sign-in)`:``}var pa=864e5;function ma(e){if(e===null)return null;let t=new Date(e).getTime();return Number.isNaN(t)?null:Math.round((t-Date.now())/pa)}var ha=7;function ga(e){return e===null?`none`:e.length<=11?e:`${e.slice(0,ha)}\u2026${e.slice(-4)}`}var _a=13,va=14;function ya(e){return[``,`${e.cliName} ${e.cliVersion} \u2192 ${e.apiKey.host}`+(e.apiVersion===null?` (api build unavailable)`:` (api ${e.apiVersion})`),``,...xa(e.oauth,e.cliName,e.refresh),...Ca(e.apiKey,e.oauth,e.cliName),``,W(`Providers`,Ea(e.providers)),W(`Environment`,Da(e.resolved)),W(`Selected`,Oa(e.resolved,e.refresh,e.cliName)),...ba(e.live),...e.systemOk?[]:[W(`System`,`uptime read failed`)]].join(`
21
+ `)}function ba(e){if(e===null)return[];let t=G(`local credential provenance was captured before verification`);if(e.error!==null)return[``,W(`Live probe`,`${e.scope} permission probe failed`),t,G(e.error)];if(e.authorization===null)return[];let n=e.authorization.permissionGrant,r=e.identity;return[``,W(`Live probe`,`${e.scope} permission probe succeeded`),t,G(`operation access ${e.authorization.operationAccess}; ${n.role.length} role; ${n.permission.length} permission`),...r===null?[G(e.scope===`read`?`identity not requested for a read-scope credential`:`identity unavailable in this build`)]:[W(`Live account`,r.nameFull??r.email??r.clerkUserId??r.id)],G(`no API operation was executed or individually authorized`)]}function W(e,t){return` ${e.padEnd(_a)}${t}`}function G(e){return` ${``.padEnd(_a)}${e}`}function xa(e,t,n){switch(e.state){case`found`:{let{credential:r,provider:i}=e.stored,a=at(r);return[W(`OAuth`,`${a.email??a.subject??`unknown identity`} via ${i}`),G(Sa(r,t,n))]}case`missing`:return[W(`OAuth`,`none stored`),...e.keyringFailure===void 0?[]:[G(`OS keyring unusable — login stores to file: ${e.keyringFailure}`)]];case`unavailable`:return[W(`OAuth`,`storage unavailable: ${e.summary}`)];case`invalid`:return[W(`OAuth`,`stored credential invalid: ${e.summary}`)];default:throw Error(`Unsupported OAuth credential state`)}}function Sa(e,t,n){return it(e)?e.tokens.refresh_token===void 0?`access token expired — run \`${t} auth login\``:n.failure===null?n.materialized===`api-key`?`access token expired and renewal failed; the API key is in use — \`${t} auth login\` renews OAuth`:`access token expired — not renewed while AUTH_TOKEN is set in the environment`:`access token expired — ${n.failure}`:`access token valid until ${e.expiresAt}`}function Ca(e,t,n){if(!e.present){if(t.state===`found`)return[];let r=e.storageFailure??(t.state===`unavailable`?t.summary:null);return r===null?[W(`Signed in`,`no \u2014 run \`${n} auth login\``),...e.error===null?[]:[G(`stored credential invalid: ${e.error}`)]]:[W(`Signed in`,`credential storage unavailable`),G(r)]}return[W(t.state===`found`?`API key`:`Signed in`,e.subject??`unknown subject`),G(`via ${e.provider??`unknown store`}`),W(`Key`,`${e.name??`unnamed`} ${ga(e.apiKeyId)}`),...wa(e,n),W(`Scopes`,e.scope.length===0?`none`:e.scope.join(`, `))]}function wa(e,t){let n=e.live,r=e.expiresInDay,i=e.expiresAt;if(n?.state===`invalid`)return[W(`Key state`,`rejected by aVenture sign-in \u2014 ${n.summary}`),G(`run \`${t} auth logout\`, then \`${t} auth login --key\``)];let a=n?.state===`verified`;return[W(`Key state`,a?`${e.status??`unknown`}, verified by aVenture sign-in now`:`${e.status??`unknown`} when stored`),...i===null||r===null?[G(`no expiry recorded`)]:[G(Ta(i,r,a?`expires`:`cached expiry`))],...a?[]:[G(n===null?"aVenture sign-in owns the live verdict — `auth status` re-checks it":`aVenture sign-in could not be reached \u2014 ${n.summary}`)]]}function Ta(e,t,n){let r=e.slice(0,10);return new Date(e).getTime()<=Date.now()?`${n} ${r} passed ${Math.abs(t)}d ago`:t<=va?`${n} ${r}, ${t}d away`:`${n} ${r}`}function Ea(e){if(e.state===`unavailable`)return`unavailable: ${e.summary}`;let t=e.catalog.oauthClient;return[e.catalog.clerkPublishableKey?`browser sign-in`:`no browser sign-in`,t?`oauth ${st(t).host} client ${t.clientId}`:`no OAuth CLI client`].join(`; `)}function Da(e){return`${y.authToken}=${e.present?e.source??`resolved`:`unset`}`}function Oa(e,t,n){return e.present||t.materialized===`env`?`${y.authToken} from the environment`:t.materialized===`oauth`?`saved OAuth access token`:t.materialized===`api-key`?`saved API key`:`none \u2014 sign in with \`${n} auth login\``}var ka=`# >>> aventure-cli completion setup (managed by aventure-cli) >>>`,Aa=`# <<< aventure-cli completion setup (managed by aventure-cli) <<<`,ja=`.aventure-cli-completion.bak`;function Ma(e,t){e.command(`install`).summary(`install shell completion loaders`).description(`Install managed shell completion loaders for supported shells.`).action(()=>za([])),e.command(`uninstall`).summary(`remove shell completion loaders`).description(`Remove managed shell completion loaders installed by ${t}.`).action(()=>za([`--uninstall`]))}function Na(e,t){e.command(`setup`).summary(`configure zsh completion startup`).description(`Configure ~/.zshrc so zsh loads ${t} completion loaders.`).option(`--dry-run`,`print the managed zshrc block without writing`).option(`--yes`,`apply without prompting`).option(`--uninstall`,`remove the managed zshrc block`).action(async e=>{let t=La(),n=await Ia({rcFile:k(Gt(),`.zshrc`),installerPath:t,mode:e.uninstall?`uninstall`:`install`,dryRun:e.dryRun,prompter:e.yes||e.dryRun?void 0:Xa});j.stdout.write(`${n.message}\n`),!n.cancelled&&!e.dryRun&&za(e.uninstall?[`--uninstall`]:[])})}function Pa(e,t=`fpath-only`){return[ka,`# installer: ${e}`,'fpath=("${XDG_DATA_HOME:-$HOME/.local/share}/zsh/site-functions" $fpath)',...t===`fpath-and-compinit`?[`autoload -Uz compinit`,`compinit`]:[],Aa].join(`
22
+ `)}function Fa(){let e=za([`--status`],`pipe`);if(e.status!==0)return{refreshed:!1,message:`completion status exited ${e.status??1}`};if(!Ba(e.stdout??``))return{refreshed:!1,message:`no managed shell completions found`};let t=za([],`pipe`);return t.status===0?{refreshed:!0,message:(t.stdout??``).trim()||`shell completions refreshed`}:{refreshed:!1,message:`completion refresh exited ${t.status??1}`}}async function Ia({rcFile:e,installerPath:t,mode:n,dryRun:r=!1,prompter:i}){let a=Va(e),o=a.length===0?[]:a.split(`
23
+ `),s=Ha(o,e);if(n===`uninstall`&&s===null)return{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:a};let c=n===`install`?Ua(o,s,t,e):Wa(o,s);return c===a?{changed:!1,cancelled:!1,message:`${e}: already up-to-date`,content:c}:r?{changed:!0,cancelled:!1,message:c,content:c}:i!==void 0&&!await i(`Update ${e}?`)?{changed:!0,cancelled:!0,message:`${e}: unchanged; pass --yes to apply without a prompt`,content:a}:(qa(e,c),{changed:!0,cancelled:!1,message:`${e}: updated`,content:c})}function La(e=j.argv[1]){let t=e===void 0?``:Ra(e),n=k(O(t),`..`,`..`,`scripts`,`install-zsh-completion-loader.mjs`);return A(n)?n:k(O(t),`..`,`scripts`,`install-zsh-completion-loader.mjs`)}function Ra(e){try{return Rt(e)}catch{return k(e)}}function za(e,t=`inherit`){let n=Ot(j.execPath,[La(),...e],{encoding:t===`pipe`?`utf8`:void 0,stdio:t});if(n.error!==void 0)throw n.error;if(t===`inherit`){n.status!==0&&(j.exitCode=n.status??1);return}return{stdout:n.stdout?.toString(),stderr:n.stderr?.toString(),status:n.status}}function Ba(e){return e.split(/\r?\n/u).some(e=>e.trim().endsWith(`: managed`))}function Va(e){return A(e)?(Ja(e),Ft(e,`utf8`)):``}function Ha(e,t){let n=Ga(e,ka),r=Ga(e,Aa);if(n.length===0&&r.length===0)return null;let[i]=n,[a]=r;if(n.length!==1||r.length!==1||i===void 0||a===void 0||i>=a)throw Error(`${t} has malformed managed completion setup markers; fix manually before retrying.`);return[i,a]}function Ua(e,t,n,r){let i=t===null?[...e]:[...e.slice(0,t[0]),...e.slice(t[1]+1)],a=Ka(i),o=Pa(n,a===-1?`fpath-and-compinit`:`fpath-only`).split(`
24
+ `),s=t===null?a:t[0],c=s===-1?i.length:s;if(t!==null&&a!==-1&&a<c)throw Error(`${r} runs compinit before the managed block; move the block above compinit manually.`);return Ya([...i.slice(0,c),...o,...i.slice(c)])}function Wa(e,t){return Ya(t===null?e:[...e.slice(0,t[0]),...e.slice(t[1]+1)])}function Ga(e,t){return e.flatMap((e,n)=>e===t?[n]:[])}function Ka(e){return e.findIndex(e=>/^\s*(autoload\s+.*\bcompinit\b|compinit(?:\s|$))/.test(e))}function qa(e,t){Nt(O(e),{recursive:!0}),A(e)&&(Ja(e),Ja(`${e}${ja}`),jt(e,`${e}${ja}`));let n=k(O(e),`.${D(e)}.${j.pid}.tmp`);Ja(n),Vt(n,t,{mode:420}),zt(n,e)}function Ja(e){if(A(e)&&Mt(e).isSymbolicLink())throw Error(`refusing to write symlink: ${e}`)}function Ya(e){let t=e.join(`
25
25
  `);return t.length===0||t.endsWith(`
26
- `)?t:`${t}\n`}async function Ya(e){if(!j.stdin.isTTY)return!1;let t=$t({input:j.stdin,output:j.stdout});try{let n=await t.question(`${e} [y/N] `);return/^(y|yes)$/i.test(n.trim())}finally{t.close()}}var Xa=new Intl.Collator(void 0,{numeric:!0}),Za=2e4,Qa=[`lib`,`aventurevc-releases`];function $a(e,t=b()){let n=t.registry===``?`Requires npm authentication for @aventurevc packages.`:`Installs from npm.`;E(e.command(`update`).summary(`Check for or install the latest release`).description([`Compare the running CLI version against the latest published`,`release and install it into the active published bin prefix.`,``,`Refuses to install when the running binary is the working-tree build`,`(rebuild that checkout instead). ${n}`,`--execute is deprecated, accepted, and ignored; update executes by its verb.`].join(`
27
- `)).option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1).option(`--release <version>`,`Install and activate exactly this version, not the latest.`)).action(e=>L({mode:T(e)},eo(void 0,`apply`,e.release)))}function eo(e,t=`apply`,n){let r=e;try{r??=b(process.argv[1])}catch(e){return g(e instanceof Error?e.message:String(e),[`invalid_package_metadata`])}let i=r.name,a=r.version,o=r.registry===``?``:de,s=r.registry===``&&i===`@aventurevc/aventure-cli`,c=n;if(c===void 0){let e=to([`view`,o,`version`,`--silent`,`--global`],r,{timeout:Za});if(!e.ok)return{...e,data:null};if(c=(e.data??``).trim(),c===``)return g(`npm view ${o} returned empty version`,[`empty_stdout`])}let l=n!==void 0||s||Xa.compare(a,c)<0,u={targetPackage:o,runningPackage:i,currentVersion:a,latestVersion:c,upgradeAvailable:l,upgradeInstalled:!1};if(t===`check`)return _(`${i}@${a} → ${o}@${c} (${l?`available`:`up to date`})`,u);if(r.workingTreeRoot!==null)return g(`Refusing to install over the working-tree build at ${r.workingTreeRoot}; rebuild via make instead`,["running CLI is npm-linked from the back-end checkout — `update` is for published bins"]);try{let e=io(r),t=k(e,...Qa),i=D(o),s=k(t,`${i}-current`),l=o===``?[o,``]:[o,fe],d=ao(e,r),f=n??[c,d?.version??a].reduce((e,t)=>Xa.compare(e,t)<0?t:e,a);Nt(t,{recursive:!0});let p=[ro(r),...A(s)?[Rt(s)]:[],...It(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>k(t,e.name))],m,h=null,ee=!1;for(let t of new Set(p.filter(t=>t!==e))){let e=no(t,l,f,r.registry);if(e.ok&&e.data!==null){m=t,h=e.data;break}}if(m===void 0){m=Pt(k(t,`${i}-${encodeURIComponent(f)}-`));let e=to([`install`,`-g`,`--prefix`,m,...l.map(e=>`${e}@${f}`)],r,{stdio:[`ignore`,`inherit`,`inherit`]});if(!e.ok)return{...e,data:null};ee=!0;let n=no(m,l,f,r.registry);if(!n.ok)return{...n,data:null};h=n.data}if(h===null)throw Error(`release verification produced no package`);let te=oo(m,e,s,h,n),ne=co();return _(`${o} active at ${te}`,{...u,upgradeInstalled:ee||n!==void 0||d?.version!==te,installPrefix:e,verifiedVersion:te,completionRefreshed:ne.refreshed,completionRefreshMessage:ne.message})}catch(e){return g(`${o} update failed: ${so(e)}`,[`existing releases were preserved`])}}function to(e,t,n={}){let r={...process.env};t.registry===``?r.NODE_AUTH_TOKEN??=r.GH_PACKAGES_TOKEN:delete r.GH_PACKAGES_TOKEN;let i=[...e,`--@aventurevc:registry=${t.registry}`],a=Ot(`npm`,i,{env:r,encoding:`utf8`,...n});if(a.error)return a.signal===`SIGTERM`&&n.timeout!==void 0?g(`npm ${e[0]??``} did not answer within ${n.timeout}ms`,[`timeout`]):g(`npm ${e[0]??``} failed to start: ${a.error.message}`,[`spawn_error`]);if(a.status!==0){let t=(a.stderr??``).trim().split(`
28
- `).slice(-3).join(` | `);return g(`npm ${e.join(` `)} exited ${a.status}`,[t||`no stderr`])}return _(`npm ok`,a.stdout??``)}function no(e,t,n,r){try{let i=t.map(t=>{let i=b(k(e,`lib`,`node_modules`,...t.split(`/`),`package.json`));if(i.name!==t||i.version!==n||i.registry!==r)throw Error(`${t} does not match ${n} from ${r}`);for(let t of i.bin)if(!Rt(k(e,`bin`,t)).startsWith(`${i.packageRoot}${At}`))throw Error(`${t} escapes ${i.packageRoot}`);return i});for(let t of i){let r=k(e,`bin`,t.bin[0]),i=Ot(process.execPath,[r,`--version`],{encoding:`utf8`,timeout:Za});if(i.error)throw Error(`${t.name} verification failed: ${i.error.message}`);let a=(i.stdout??``).trim();if(i.status!==0||a!==n)throw Error(`${t.name} expected ${n} but reported ${a||`empty output`}`)}return _(`CLI and MCP release verified`,i)}catch(t){return g(`release verification failed: ${so(t)}`,[`release prefix: ${e}`])}}function ro(e){let t=O(e.packageRoot),n=O(t),r=O(n);if(D(t)!==e.name.split(`/`)[0]||D(n)!==`node_modules`||D(r)!==`lib`)throw Error(`the running package is not in a verifiable global npm prefix; npm install was not run`);if(!e.entryPath.startsWith(`${e.packageRoot}${At}`))throw Error(`the running entry escapes its package root`);return O(r)}function io(e){let t=ro(e),n=`${At}${Qa.join(At)}${At}`,r=t.lastIndexOf(n);return r<0?t:t.slice(0,r)}function ao(e,t){let n=t.registry===``?D(``):pe,r=k(e,`bin`,n);if(!A(r))return null;let i=b(r);if(i.registry!==t.registry)throw Error(`${r} belongs to another product`);return i}function oo(e,t,n,r,i){let a=r[0];if(a===void 0)throw Error(`release contains no CLI`);let o=k(t,`bin`);Nt(o,{recursive:!0});let s=r.flatMap(e=>e.bin.filter((e,t)=>{let n=k(o,e);if(!A(n)||b(n).registry===a.registry)return!0;if(a.registry!==``&&t>0)return!1;throw Error(`${n} belongs to another product`)}));if(!A(n)){let t=Pt(k(O(n),`${D(n)}-seed-`));Nt(k(t,`bin`));for(let n of s){let r=k(o,n);Bt(Rt(A(r)?r:k(e,`bin`,n)),k(t,`bin`,n))}try{Bt(kt(O(n),t),n)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`EEXIST`))throw e}}if(!Mt(n).isSymbolicLink())throw Error(`${n} is not a release symlink`);for(let e of s){let t=kt(o,k(n,`bin`,e)),r=k(o,`.${e}-${Xt()}`);Bt(t,r),zt(r,k(o,e))}for(let e of s){let t=k(o,e);if(!Mt(t).isSymbolicLink()||k(o,Lt(t))!==k(n,`bin`,e))throw Error(`${t} does not follow the product current pointer`)}let c=ao(t,a);if(i===void 0&&c!==null&&Xa.compare(c.version,a.version)>0)return c.version;let l=`${n}-${Xt()}`;return Bt(kt(O(n),e),l),zt(l,n),a.version}function so(e){return e instanceof Error?e.message:String(e)}function co(){try{return Pa()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var lo=[{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 signs in, as which account and role, never secrets`},{name:`catalog`,purpose:`this CLI knows every operation the API serves`}],uo=`operationFingerprint`;function fo(e,t=b().bin[0]){E(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: [...] }`:",...lo.map(e=>` - ${e.name}: ${e.purpose}`),``,`Exit code is 0 only when no check failed; a skipped check (no registry reachable) or a`,`warned one (the account read failed) 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(`
29
- `))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),L({mode:T(e)},await po(t))})}async function po(e){let t=ho(),n=go(e),[r,i]=await Promise.all([_o(e),vo(t,e)]),a=[n.check,r,i.check,await bo(e),Do(t,i.servedFingerprint,n.upgradeAvailable,e)],o={pass:mo(a,`pass`),warn:mo(a,`warn`),fail:mo(a,`fail`),skip:mo(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.warn} warn, ${o.fail} fail, ${o.skip} skip`,...a.map(e=>` ${e.name} ${e.status} — ${e.message}`)].join(`
30
- `);return c.ok?_(l,c,{counts:o}):{...g(l,s,{counts:o}),data:c}}function mo(e,t){return e.filter(e=>e.status===t).length}function K(e,t,n){return{name:e,status:t,message:n}}function ho(){return w.find(e=>e.intent===`status`&&e.resource===`status`)}function go(e){let t=b(),n=eo(t,`check`);if(!n.ok||n.data===null)return{check:K(`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?K(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):K(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function _o(e){try{let{EntityDetailSchema:e}=await import(`./detail-BnHDsTdz.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return K(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return K(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${S(t)}.`)}}async function vo(e,t){if(e===void 0)return{check:K(`api-host`,`skip`,`No status operation resolved from the generated catalog; fix the catalog check first.`),servedFingerprint:null};let n;try{n=v().host}catch(e){return{check:K(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${S(e)}.`),servedFingerprint:null}}let r=await p({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>g(S(e)));return r.ok?{check:K(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:yo(r.data)}:{check:K(`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 yo(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[uo];return typeof n==`string`&&n.length>0?n:null}async function bo(e){let t=qe(),[n,r]=await Promise.all([So(),Co()]);if(r.state===`unavailable`&&r.cause===`environment`)return K(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t.present,a=r.state===`found`&&r.stored.activation===`active`;if(!i&&n.state===`invalid`)return K(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`);if(!i&&n.state===`found`&&it(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0)return K(`auth`,`fail`,`Saved OAuth access token is expired without a refresh token; run \`${e} auth login\` to sign in again.`);if(!i&&!a&&n.state===`unavailable`)return K(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${y.authToken} through the environment — ${n.summary}.`);if(i||n.state===`found`||a){let i=await xo(e,t);return K(`auth`,i.status,`Credential source available: ${wo(t,n,r)}; ${i.text}.`)}return r.state===`unavailable`?K(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${y.authToken} through the environment — ${r.summary}.`):K(`auth`,`fail`,`Run \`${e} auth login\` for OAuth or \`${e} auth login --key\` for an API key. For non-interactive use, set ${y.authToken} in the environment.`)}async function xo(e,t){let n=C(v().host),r=await ra(e),i=`credential=${t.present?t.source??`env`:r.materialized??`none`}`;try{if(r.failure!==null)throw Error(r.failure);let e=await na(`write`);if(e===null)return{status:`pass`,text:`${i} host=${n}`};let t=e.rbacRole.length===0?`none`:e.rbacRole.join(`,`);return{status:`pass`,text:`${i} account=${e.email??e.id} role=${t} host=${n}`}}catch(t){return{status:`warn`,text:`${i} account=unread host=${n} — GET /v1/auth/me returned ${S(t,[v().userBearerToken])}; run \`${e} auth status --verify write\``}}}async function So(){let e;try{e=C(v().host)}catch(e){return{state:`unavailable`,summary:S(e)}}return await ut(e)}async function Co(){let e;try{e=C(v().host)}catch(e){return{state:`unavailable`,summary:S(e),cause:`environment`}}try{return await Qe(e)}catch(e){return{state:`unavailable`,summary:S(e),cause:`storage`}}}function wo(e,t,n){return[Ea(e),`oauth=${Eo(t)}`,`api-key=${To(n)}`].join(` `)}function To(e){if(e.state!==`found`)return e.state===`missing`?`unset`:`unavailable`;let t=C(v().host);return`${e.stored.activation}${da(t,e)}`}function Eo(e){switch(e.state){case`found`:return it(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 Do(e,t,n,r){let i=w.length;if(e===void 0)return K(`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 K(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${Et}.`);if(t===`8a75d2eb11607c79`)return K(`catalog`,`pass`,`${i} generated operations match the set the API serves (${Et}).`);let a=`This catalog describes a different operation set than the API serves (${Et} vs ${t})`;return n===!0?K(`catalog`,`fail`,`${a}: run \`${r} update\`.`):K(`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 Oo=x(B,`oauth`),ko=[x(B,`start`),x(B,`poll`),x(B,`acknowledge`)],Ao=x(B,`revoke`);function jo(t,n=b().bin[0]){let r=Fo(t);fo(r,n);let i=[`${Oo.description} Default method: OAuth in your browser.`,`With --key: ${ko.map(({description:e})=>e).join(` `)}`].join(`
31
- `);E(Po(r,[Oo,...ko],i)).action(Mo),E(Po(r,[Ao],Ao.description)).action(No),E(r.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(`
32
- `)).addOption(new e(`--verify <scope>`,`verify one permission-probe scope`).choices([`read`,`write`]))).action(async function(e){Io(this),L({mode:T(e)},await Lo(n,e.verify))}),r.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: ${y.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(`
33
- `)).action(async function(){Io(this);let e=await ra(n),t=process.env[y.authToken]?.trim();if(e.failure===null&&t!==void 0&&t.length>0){process.stdout.write(`${t}\n`);return}L({mode:`text`},e.failure===null?Go(`auth token: no credentials resolved`,null,n,{oauth:!0,apiKey:!0}):g(`auth token: ${e.failure}`))})}async function Mo(e){Io(this);let t=T(e);if(e.providers===!0){L({mode:t},await zo());return}L({mode:t},e.key===!0?await Ki({noBrowser:!e.browser,clientLabel:e.clientLabel}):await mt({noBrowser:!e.browser}))}async function No(e){Io(this),L({mode:T(e)},await Fi({forgetLocal:e.forgetLocal===!0}))}function Po(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 Fo(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Sign in, sign out, and check credentials`).description([`\`${Oo.command}\`: ${Oo.summary}; \`--key\` ${ko[0].summary.toLowerCase()}.`,`\`${Ao.command}\`: ${Ao.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(`
34
- `))}function Io(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function Lo(e,t){let n;try{n=C(v().host)}catch(e){return g(`auth status: invalid API host — ${S(e)}`)}let r=qe(),i=ra(e),[a,o,s]=await Promise.all([Wo(`/v1/status`,`GET /v1/status`),Wo(`/info`,`GET /info`),Bo()]),c=await i,[l,u]=await Promise.all([ut(n),Ro(n)]),d=t===void 0?null:await ia(t,l,u.inspection,c),f=b().version,p=ca(n,u.inspection,u.verification),m=va({cliName:e,cliVersion:f,apiVersion:o.ok?Ho(o.data):null,oauth:l,apiKey:p,providers:s,resolved:r,refresh:c,systemOk:a.ok,live:d}),h={cli:{version:f},api:o.ok?o.data??null:null,auth:{[y.authToken]:r},selected:c.materialized,oauth:la(n,l),apiKey:p,providers:s,live:d,system:a.ok?a.data??null:null,...o.ok?{}:{apiError:o.summary},...a.ok?{}:{systemError:a.summary}};return c.failure===null?!o.ok&&o.httpStatus===401?{...g(`auth status: the API rejected the selected credential (401) | ${m}`,[`Replace or unset ${y.authToken}, or run \`${e} auth login\`.`]),data:h}:d!==null&&d.error!==null?{...g(`auth status: ${d.scope} permission probe failed — ${d.error}`,[d.error]),data:h}:d!==null||r.present||l.state===`found`||u.inspection.state===`found`?_(m,h):Go(`auth status: no credentials resolved | ${m}`,h,e,{oauth:l.state===`missing`,apiKey:u.inspection.state===`missing`}):{...g(`auth status: ${c.failure} | ${m}`,[c.failure]),data:h}}async function Ro(e){let t=await Vo(e);if(t.state!==`found`)return{inspection:t,verification:null};let{stored:n,verification:r}=await Mi(t.stored);return{inspection:{state:`found`,stored:n},verification:r}}async function zo(){let e=await Bo();return e.state===`found`?_(`Sign-in providers for the selected API host`,e.catalog):g(`auth login --providers: ${e.summary}`)}async function Bo(){try{return{state:`found`,catalog:await pt()}}catch(e){return{state:`unavailable`,summary:S(e)}}}async function Vo(e){try{return await Qe(e)}catch(e){return{state:`invalid`,summary:S(e)}}}function Ho(e){if(!Uo(e))return null;let t=si.safeParse(Reflect.get(e,`response`));if(!t.success)return null;let n=t.data.build.version?.trim();return n&&n.length>0?n:null}function Uo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Wo(e,t){return await p({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>g(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}function Go(e,t,n,r){return{...g(e,[...r.apiKey?[`For an API key (works over SSH), run \`${n} auth login --key\`.`]:[],...r.oauth?[`For OAuth, run \`${n} auth login\`; without a browser it prints a device code.`]:[],`For non-interactive use, set ${y.authToken} to an aVenture API key (create one at ${se}/settings/api-keys).`]),data:t}}function Ko(e,t=w,n=b().bin[0]){let r=e.command(`completion`).summary(`Generate shell completion scripts`).description(`Generate shell completion scripts for the aVenture CLI.`);for(let i of[`bash`,`fish`,`zsh`])r.command(i).summary(`Print ${i} shell completions`).description(`Print ${i} completion definitions for ${n}.`).action(()=>{j.stdout.write(Jo(e,i,t))});ja(r,n),Ma(r,n)}function qo(){return b().bin}function Jo(e,t,n=w,r=qo()){let i=rs(n);return t===`fish`?[`# fish completions for ${r.join(`, `)}`,...Xo(e),...r.map(e=>`complete -c ${q(e)} -e`),`${gs(r)} -f`,...Zo(e,r),...Qo(e,i,r),``].join(`
35
- `):Yo(e,t,i,r)}function Yo(e,t,n,r){let i=t===`zsh`?`typeset -ga `:``,a=`complete -F _aventure_cli ${r.map(e=>e.replaceAll(`'`,`'\\''`)).join(` `)}`,[o,s,c]=os(e,n);return[...t===`zsh`?[`#compdef ${r.join(` `)}`]:[],`# ${t} completions for ${r.join(`, `)}`,`${i}_aventure_cli_commands=(`,...o.map(e=>` ${e}`),`)`,`${i}_aventure_cli_options=(`,...s.map(e=>` ${e}`),`)`,`${i}_aventure_cli_values=(`,...c.map(e=>` ${e}`),`)`,``,...ls(t),...t===`bash`?[a,``]:[``]].join(`
36
- `)}function Xo(e){return[`function __aventure_cli_command_path\n set -l global_value_options ${$o(e).filter(e=>e.required||e.optional).flatMap(e=>fs(e)??[]).map(q).join(` `)}\n set -l tokens (commandline -xpc)\n if test (count $tokens) -gt 0\n set -e tokens[1]\n end\n set -l path\n set -l skip_next 0\n for token in $tokens\n if test $skip_next -eq 1\n set skip_next 0\n continue\n end\n if string match -q -- '--*=*' $token\n set -l name (string replace -r '^--([^=]+)=.*$' '$1' -- $token)\n contains -- $name $global_value_options; and continue\n end\n if string match -q -- '--*' $token\n set -l name (string replace -r '^--' '' -- $token)\n if contains -- $name $global_value_options\n set skip_next 1\n continue\n end\n break\n end\n if string match -q -- '-*' $token\n break\n end\n set -a path $token\n end\n printf '%s\\n' $path\nend\n`,`function __aventure_cli_path_is
26
+ `)?t:`${t}\n`}async function Xa(e){if(!j.stdin.isTTY)return!1;let t=$t({input:j.stdin,output:j.stdout});try{let n=await t.question(`${e} [y/N] `);return/^(y|yes)$/i.test(n.trim())}finally{t.close()}}var Za=new Intl.Collator(void 0,{numeric:!0}),Qa=2e4,$a=[`lib`,`aventurevc-releases`];function eo(e,t=b()){let n=t.registry===``?`Requires npm authentication for @aventurevc packages.`:`Installs from npm.`;E(e.command(`update`).summary(`Check for or install the latest release`).description([`Compare the running CLI version against the latest published`,`release and install it into the active published bin prefix.`,``,`Refuses to install when the running binary is the working-tree build`,`(rebuild that checkout instead). ${n}`,`--execute is deprecated, accepted, and ignored; update executes by its verb.`].join(`
27
+ `)).option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1).option(`--release <version>`,`Install and activate exactly this version, not the latest.`)).action(e=>L({mode:T(e)},to(void 0,`apply`,e.release)))}function to(e,t=`apply`,n){let r=e;try{r??=b(process.argv[1])}catch(e){return g(e instanceof Error?e.message:String(e),[`invalid_package_metadata`])}let i=r.name,a=r.version,o=r.registry===``?``:de,s=r.registry===``&&i===`@aventurevc/aventure-cli`,c=n;if(c===void 0){let e=no([`view`,o,`version`,`--silent`,`--global`],r,{timeout:Qa});if(!e.ok)return{...e,data:null};if(c=(e.data??``).trim(),c===``)return g(`npm view ${o} returned empty version`,[`empty_stdout`])}let l=n!==void 0||s||Za.compare(a,c)<0,u={targetPackage:o,runningPackage:i,currentVersion:a,latestVersion:c,upgradeAvailable:l,upgradeInstalled:!1};if(t===`check`)return _(`${i}@${a} → ${o}@${c} (${l?`available`:`up to date`})`,u);if(r.workingTreeRoot!==null)return g(`Refusing to install over the working-tree build at ${r.workingTreeRoot}; rebuild via make instead`,["running CLI is npm-linked from the back-end checkout — `update` is for published bins"]);try{let e=ao(r),t=k(e,...$a),i=D(o),s=k(t,`${i}-current`),l=o===``?[o,``]:[o,fe],d=oo(e,r),f=n??[c,d?.version??a].reduce((e,t)=>Za.compare(e,t)<0?t:e,a);Nt(t,{recursive:!0});let p=[io(r),...A(s)?[Rt(s)]:[],...It(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>k(t,e.name))],m,h=null,ee=!1;for(let t of new Set(p.filter(t=>t!==e))){let e=ro(t,l,f,r.registry);if(e.ok&&e.data!==null){m=t,h=e.data;break}}if(m===void 0){m=Pt(k(t,`${i}-${encodeURIComponent(f)}-`));let e=no([`install`,`-g`,`--prefix`,m,...l.map(e=>`${e}@${f}`)],r,{stdio:[`ignore`,`inherit`,`inherit`]});if(!e.ok)return{...e,data:null};ee=!0;let n=ro(m,l,f,r.registry);if(!n.ok)return{...n,data:null};h=n.data}if(h===null)throw Error(`release verification produced no package`);let te=so(m,e,s,h,n),ne=lo();return _(`${o} active at ${te}`,{...u,upgradeInstalled:ee||n!==void 0||d?.version!==te,installPrefix:e,verifiedVersion:te,completionRefreshed:ne.refreshed,completionRefreshMessage:ne.message})}catch(e){return g(`${o} update failed: ${co(e)}`,[`existing releases were preserved`])}}function no(e,t,n={}){let r={...process.env};t.registry===``?r.NODE_AUTH_TOKEN??=r.GH_PACKAGES_TOKEN:delete r.GH_PACKAGES_TOKEN;let i=[...e,`--@aventurevc:registry=${t.registry}`],a=Ot(`npm`,i,{env:r,encoding:`utf8`,...n});if(a.error)return a.signal===`SIGTERM`&&n.timeout!==void 0?g(`npm ${e[0]??``} did not answer within ${n.timeout}ms`,[`timeout`]):g(`npm ${e[0]??``} failed to start: ${a.error.message}`,[`spawn_error`]);if(a.status!==0){let t=(a.stderr??``).trim().split(`
28
+ `).slice(-3).join(` | `);return g(`npm ${e.join(` `)} exited ${a.status}`,[t||`no stderr`])}return _(`npm ok`,a.stdout??``)}function ro(e,t,n,r){try{let i=t.map(t=>{let i=b(k(e,`lib`,`node_modules`,...t.split(`/`),`package.json`));if(i.name!==t||i.version!==n||i.registry!==r)throw Error(`${t} does not match ${n} from ${r}`);for(let t of i.bin)if(!Rt(k(e,`bin`,t)).startsWith(`${i.packageRoot}${At}`))throw Error(`${t} escapes ${i.packageRoot}`);return i});for(let t of i){let r=k(e,`bin`,t.bin[0]),i=Ot(process.execPath,[r,`--version`],{encoding:`utf8`,timeout:Qa});if(i.error)throw Error(`${t.name} verification failed: ${i.error.message}`);let a=(i.stdout??``).trim();if(i.status!==0||a!==n)throw Error(`${t.name} expected ${n} but reported ${a||`empty output`}`)}return _(`CLI and MCP release verified`,i)}catch(t){return g(`release verification failed: ${co(t)}`,[`release prefix: ${e}`])}}function io(e){let t=O(e.packageRoot),n=O(t),r=O(n);if(D(t)!==e.name.split(`/`)[0]||D(n)!==`node_modules`||D(r)!==`lib`)throw Error(`the running package is not in a verifiable global npm prefix; npm install was not run`);if(!e.entryPath.startsWith(`${e.packageRoot}${At}`))throw Error(`the running entry escapes its package root`);return O(r)}function ao(e){let t=io(e),n=`${At}${$a.join(At)}${At}`,r=t.lastIndexOf(n);return r<0?t:t.slice(0,r)}function oo(e,t){let n=t.registry===``?D(``):pe,r=k(e,`bin`,n);if(!A(r))return null;let i=b(r);if(i.registry!==t.registry)throw Error(`${r} belongs to another product`);return i}function so(e,t,n,r,i){let a=r[0];if(a===void 0)throw Error(`release contains no CLI`);let o=k(t,`bin`);Nt(o,{recursive:!0});let s=r.flatMap(e=>e.bin.filter((e,t)=>{let n=k(o,e);if(!A(n)||b(n).registry===a.registry)return!0;if(a.registry!==``&&t>0)return!1;throw Error(`${n} belongs to another product`)}));if(!A(n)){let t=Pt(k(O(n),`${D(n)}-seed-`));Nt(k(t,`bin`));for(let n of s){let r=k(o,n);Bt(Rt(A(r)?r:k(e,`bin`,n)),k(t,`bin`,n))}try{Bt(kt(O(n),t),n)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`EEXIST`))throw e}}if(!Mt(n).isSymbolicLink())throw Error(`${n} is not a release symlink`);for(let e of s){let t=kt(o,k(n,`bin`,e)),r=k(o,`.${e}-${Xt()}`);Bt(t,r),zt(r,k(o,e))}for(let e of s){let t=k(o,e);if(!Mt(t).isSymbolicLink()||k(o,Lt(t))!==k(n,`bin`,e))throw Error(`${t} does not follow the product current pointer`)}let c=oo(t,a);if(i===void 0&&c!==null&&Za.compare(c.version,a.version)>0)return c.version;let l=`${n}-${Xt()}`;return Bt(kt(O(n),e),l),zt(l,n),a.version}function co(e){return e instanceof Error?e.message:String(e)}function lo(){try{return Fa()}catch(e){return{refreshed:!1,message:e instanceof Error?e.message:String(e)}}}var uo=[{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 signs in, as which account and role, never secrets`},{name:`catalog`,purpose:`this CLI knows every operation the API serves`}],fo=`operationFingerprint`;function po(e,t=b().bin[0]){E(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: [...] }`:",...uo.map(e=>` - ${e.name}: ${e.purpose}`),``,`Exit code is 0 only when no check failed; a skipped check (no registry reachable) or a`,`warned one (the account read failed) 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(`
29
+ `))).action(async function(e){let n=this.optsWithGlobals();n.environment!==void 0&&(process.env.API_ENV=n.environment),L({mode:T(e)},await mo(t))})}async function mo(e){let t=go(),n=_o(e),[r,i]=await Promise.all([vo(e),yo(t,e)]),a=[n.check,r,i.check,await xo(e),Oo(t,i.servedFingerprint,n.upgradeAvailable,e)],o={pass:ho(a,`pass`),warn:ho(a,`warn`),fail:ho(a,`fail`),skip:ho(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.warn} warn, ${o.fail} fail, ${o.skip} skip`,...a.map(e=>` ${e.name} ${e.status} — ${e.message}`)].join(`
30
+ `);return c.ok?_(l,c,{counts:o}):{...g(l,s,{counts:o}),data:c}}function ho(e,t){return e.filter(e=>e.status===t).length}function K(e,t,n){return{name:e,status:t,message:n}}function go(){return w.find(e=>e.intent===`status`&&e.resource===`status`)}function _o(e){let t=b(),n=to(t,`check`);if(!n.ok||n.data===null)return{check:K(`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?K(`cli-version`,`fail`,`Upgrade ${r} from ${i} to ${a}: run \`${e} update\`.`):K(`cli-version`,`pass`,`${r} ${i} matches the latest published release.`),upgradeAvailable:o}}async function vo(e){try{let{EntityDetailSchema:e}=await import(`./detail-Dobtzmp5.js`);if(typeof e.safeParse!=`function`)throw Error(`EntityDetailSchema does not expose a Zod parser`);return K(`api-schemas`,`pass`,`Installed @aventurevc/api-schemas contracts resolve beyond the CLI startup path.`)}catch(t){return K(`api-schemas`,`fail`,`Reinstall the CLI: run \`${e} update\` — ${S(t)}.`)}}async function yo(e,t){if(e===void 0)return{check:K(`api-host`,`skip`,`No status operation resolved from the generated catalog; fix the catalog check first.`),servedFingerprint:null};let n;try{n=v().host}catch(e){return{check:K(`api-host`,`fail`,`Correct API_ENV or pass \`--environment <name>\` — ${S(e)}.`),servedFingerprint:null}}let r=await p({method:e.method,path:e.path,auth:e.auth,responseFormat:`json`}).catch(e=>g(S(e)));return r.ok?{check:K(`api-host`,`pass`,`${e.method} ${e.path} answered at ${n}.`),servedFingerprint:bo(r.data)}:{check:K(`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 bo(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[fo];return typeof n==`string`&&n.length>0?n:null}async function xo(e){let t=qe(),[n,r]=await Promise.all([Co(),wo()]);if(r.state===`unavailable`&&r.cause===`environment`)return K(`auth`,`fail`,`Fix the environment configuration first — ${r.summary}.`);let i=t.present,a=r.state===`found`&&r.stored.activation===`active`;if(!i&&n.state===`invalid`)return K(`auth`,`fail`,`Saved OAuth credential is invalid; run \`${e} auth login\` to sign in again after verification — ${n.summary}.`);if(!i&&n.state===`found`&&it(n.stored.credential)&&n.stored.credential.tokens.refresh_token===void 0)return K(`auth`,`fail`,`Saved OAuth access token is expired without a refresh token; run \`${e} auth login\` to sign in again.`);if(!i&&!a&&n.state===`unavailable`)return K(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login\`, or inject ${y.authToken} through the environment — ${n.summary}.`);if(i||n.state===`found`||a){let i=await So(e,t);return K(`auth`,i.status,`Credential source available: ${To(t,n,r)}; ${i.text}.`)}return r.state===`unavailable`?K(`auth`,`fail`,`Make the OS keyring or the CLI config directory usable before \`${e} auth login --key\`, or inject ${y.authToken} through the environment — ${r.summary}.`):K(`auth`,`fail`,`Run \`${e} auth login\` for OAuth or \`${e} auth login --key\` for an API key. For non-interactive use, set ${y.authToken} in the environment.`)}async function So(e,t){let n=C(v().host),r=await ia(e),i=`credential=${t.present?t.source??`env`:r.materialized??`none`}`;try{if(r.failure!==null)throw Error(r.failure);let e=await ra(`write`);if(e===null)return{status:`pass`,text:`${i} host=${n}`};let t=e.rbacRole.length===0?`none`:e.rbacRole.join(`,`);return{status:`pass`,text:`${i} account=${e.email??e.id} role=${t} host=${n}`}}catch(t){return{status:`warn`,text:`${i} account=unread host=${n} — GET /v1/auth/me returned ${S(t,[v().userBearerToken])}; run \`${e} auth status --verify write\``}}}async function Co(){let e;try{e=C(v().host)}catch(e){return{state:`unavailable`,summary:S(e)}}return await ut(e)}async function wo(){let e;try{e=C(v().host)}catch(e){return{state:`unavailable`,summary:S(e),cause:`environment`}}try{return await Qe(e)}catch(e){return{state:`unavailable`,summary:S(e),cause:`storage`}}}function To(e,t,n){return[Da(e),`oauth=${Do(t)}`,`api-key=${Eo(n)}`].join(` `)}function Eo(e){if(e.state!==`found`)return e.state===`missing`?`unset`:`unavailable`;let t=C(v().host);return`${e.stored.activation}${fa(t,e)}`}function Do(e){switch(e.state){case`found`:return it(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 Oo(e,t,n,r){let i=w.length;if(e===void 0)return K(`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 K(`catalog`,`skip`,`Could not read the served operation fingerprint, so drift is unproven; this catalog holds ${i} operations at ${Et}.`);if(t===`60c711695ed8d07b`)return K(`catalog`,`pass`,`${i} generated operations match the set the API serves (${Et}).`);let a=`This catalog describes a different operation set than the API serves (${Et} vs ${t})`;return n===!0?K(`catalog`,`fail`,`${a}: run \`${r} update\`.`):K(`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 ko=x(B,`oauth`),Ao=[x(B,`start`),x(B,`poll`),x(B,`acknowledge`)],jo=x(B,`revoke`);function Mo(t,n=b().bin[0]){let r=Io(t);po(r,n);let i=[`${ko.description} Default method: OAuth in your browser.`,`With --key: ${Ao.map(({description:e})=>e).join(` `)}`].join(`
31
+ `);E(Fo(r,[ko,...Ao],i)).action(No),E(Fo(r,[jo],jo.description)).action(Po),E(r.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(`
32
+ `)).addOption(new e(`--verify <scope>`,`verify one permission-probe scope`).choices([`read`,`write`]))).action(async function(e){Lo(this),L({mode:T(e)},await Ro(n,e.verify))}),r.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: ${y.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(`
33
+ `)).action(async function(){Lo(this);let e=await ia(n),t=process.env[y.authToken]?.trim();if(e.failure===null&&t!==void 0&&t.length>0){process.stdout.write(`${t}\n`);return}L({mode:`text`},e.failure===null?Ko(`auth token: no credentials resolved`,null,n,{oauth:!0,apiKey:!0}):g(`auth token: ${e.failure}`))})}async function No(e){Lo(this);let t=T(e);if(e.providers===!0){L({mode:t},await Bo());return}L({mode:t},e.key===!0?await qi({noBrowser:!e.browser,clientLabel:e.clientLabel}):await mt({noBrowser:!e.browser}))}async function Po(e){Lo(this),L({mode:T(e)},await Ii({forgetLocal:e.forgetLocal===!0}))}function Fo(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 Io(e){return(e.commands.find(e=>e.name()===`auth`)??e.command(`auth`)).summary(`Sign in, sign out, and check credentials`).description([`\`${ko.command}\`: ${ko.summary}; \`--key\` ${Ao[0].summary.toLowerCase()}.`,`\`${jo.command}\`: ${jo.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(`
34
+ `))}function Lo(e){let t=e.optsWithGlobals();t.environment!==void 0&&(process.env.API_ENV=t.environment)}async function Ro(e,t){let n;try{n=C(v().host)}catch(e){return g(`auth status: invalid API host — ${S(e)}`)}let r=qe(),i=ia(e),[a,o,s]=await Promise.all([Go(`/v1/status`,`GET /v1/status`),Go(`/info`,`GET /info`),Vo()]),c=await i,[l,u]=await Promise.all([ut(n),zo(n)]),d=t===void 0?null:await aa(t,l,u.inspection,c),f=b().version,p=la(n,u.inspection,u.verification),m=ya({cliName:e,cliVersion:f,apiVersion:o.ok?Uo(o.data):null,oauth:l,apiKey:p,providers:s,resolved:r,refresh:c,systemOk:a.ok,live:d}),h={cli:{version:f},api:o.ok?o.data??null:null,auth:{[y.authToken]:r},selected:c.materialized,oauth:ua(n,l),apiKey:p,providers:s,live:d,system:a.ok?a.data??null:null,...o.ok?{}:{apiError:o.summary},...a.ok?{}:{systemError:a.summary}};return c.failure===null?!o.ok&&o.httpStatus===401?{...g(`auth status: the API rejected the selected credential (401) | ${m}`,[`Replace or unset ${y.authToken}, or run \`${e} auth login\`.`]),data:h}:d!==null&&d.error!==null?{...g(`auth status: ${d.scope} permission probe failed — ${d.error}`,[d.error]),data:h}:d!==null||r.present||l.state===`found`||u.inspection.state===`found`?_(m,h):Ko(`auth status: no credentials resolved | ${m}`,h,e,{oauth:l.state===`missing`,apiKey:u.inspection.state===`missing`}):{...g(`auth status: ${c.failure} | ${m}`,[c.failure]),data:h}}async function zo(e){let t=await Ho(e);if(t.state!==`found`)return{inspection:t,verification:null};let{stored:n,verification:r}=await Ni(t.stored);return{inspection:{state:`found`,stored:n},verification:r}}async function Bo(){let e=await Vo();return e.state===`found`?_(`Sign-in providers for the selected API host`,e.catalog):g(`auth login --providers: ${e.summary}`)}async function Vo(){try{return{state:`found`,catalog:await pt()}}catch(e){return{state:`unavailable`,summary:S(e)}}}async function Ho(e){try{return await Qe(e)}catch(e){return{state:`invalid`,summary:S(e)}}}function Uo(e){if(!Wo(e))return null;let t=ci.safeParse(Reflect.get(e,`response`));if(!t.success)return null;let n=t.data.build.version?.trim();return n&&n.length>0?n:null}function Wo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Go(e,t){return await p({method:`GET`,path:e,auth:`none`,responseFormat:`json`}).catch(e=>g(`${t} failed: ${e instanceof Error?e.message:String(e)}`))}function Ko(e,t,n,r){return{...g(e,[...r.apiKey?[`For an API key (works over SSH), run \`${n} auth login --key\`.`]:[],...r.oauth?[`For OAuth, run \`${n} auth login\`; without a browser it prints a device code.`]:[],`For non-interactive use, set ${y.authToken} to an aVenture API key (create one at ${se}/settings/api-keys).`]),data:t}}function qo(e,t=w,n=b().bin[0]){let r=e.command(`completion`).summary(`Generate shell completion scripts`).description(`Generate shell completion scripts for the aVenture CLI.`);for(let i of[`bash`,`fish`,`zsh`])r.command(i).summary(`Print ${i} shell completions`).description(`Print ${i} completion definitions for ${n}.`).action(()=>{j.stdout.write(Yo(e,i,t))});Ma(r,n),Na(r,n)}function Jo(){return b().bin}function Yo(e,t,n=w,r=Jo()){let i=is(n);return t===`fish`?[`# fish completions for ${r.join(`, `)}`,...Zo(e),...r.map(e=>`complete -c ${q(e)} -e`),`${_s(r)} -f`,...Qo(e,r),...$o(e,i,r),``].join(`
35
+ `):Xo(e,t,i,r)}function Xo(e,t,n,r){let i=t===`zsh`?`typeset -ga `:``,a=`complete -F _aventure_cli ${r.map(e=>e.replaceAll(`'`,`'\\''`)).join(` `)}`,[o,s,c]=ss(e,n);return[...t===`zsh`?[`#compdef ${r.join(` `)}`]:[],`# ${t} completions for ${r.join(`, `)}`,`${i}_aventure_cli_commands=(`,...o.map(e=>` ${e}`),`)`,`${i}_aventure_cli_options=(`,...s.map(e=>` ${e}`),`)`,`${i}_aventure_cli_values=(`,...c.map(e=>` ${e}`),`)`,``,...us(t),...t===`bash`?[a,``]:[``]].join(`
36
+ `)}function Zo(e){return[`function __aventure_cli_command_path\n set -l global_value_options ${es(e).filter(e=>e.required||e.optional).flatMap(e=>ps(e)??[]).map(q).join(` `)}\n set -l tokens (commandline -xpc)\n if test (count $tokens) -gt 0\n set -e tokens[1]\n end\n set -l path\n set -l skip_next 0\n for token in $tokens\n if test $skip_next -eq 1\n set skip_next 0\n continue\n end\n if string match -q -- '--*=*' $token\n set -l name (string replace -r '^--([^=]+)=.*$' '$1' -- $token)\n contains -- $name $global_value_options; and continue\n end\n if string match -q -- '--*' $token\n set -l name (string replace -r '^--' '' -- $token)\n if contains -- $name $global_value_options\n set skip_next 1\n continue\n end\n break\n end\n if string match -q -- '-*' $token\n break\n end\n set -a path $token\n end\n printf '%s\\n' $path\nend\n`,`function __aventure_cli_path_is
37
37
  set -l expected $argv
38
38
  set -l actual (__aventure_cli_command_path)
39
39
  if test (count $actual) -ne (count $expected)
@@ -50,18 +50,18 @@ import{n as e,o as t,r as n,t as r}from"./commander-BB7CDPLs.js";import{i,o as a
50
50
  return 0
51
51
  end
52
52
  `].flatMap(e=>e.split(`
53
- `))}function Zo(e,t){return as(e).map(e=>`${gs(t)} -f -n ${q(_s(e.parentPath))} -a ${q(e.name)} -d ${q(e.description)}`).toSorted((e,t)=>e.localeCompare(t))}function Qo(e,t,n){return ps(e).flatMap(e=>{let r=hs(e),i=r.length===0?void 0:_s(r);return $o(e).flatMap(e=>{let a=t.get(is(r,e));return cs(a)?es(e,i,a,n):[]})}).toSorted((e,t)=>e.localeCompare(t))}function $o(e){return e.parent===null?e.createHelp().visibleOptions(e):e.options}function es(e,t,n,r){let i=fs(e);if(i===void 0)return[];let a=e.argChoices??ss(n),o=[`-l ${q(i)}`,e.short===void 0?``:`${e.short.startsWith(`--`)?`-l`:`-s`} ${q(e.short.replace(/^-+/,``))}`].filter(Boolean),s=t===void 0?``:` -n ${q(t)}`,c=e.required||e.optional?ts(a,ns(i,n)):`-f`,l=`${gs(r)}${s} ${o.join(` `)} ${c}`;return a===void 0||a.length===0?[`${l} -d ${q(vs(e.description))}`]:a.map(t=>`${l} -a ${q(t)} -d ${q(vs(e.description))}`)}function ts(e,t){return e!==void 0&&e.length>0?`-x`:t?`-r -F`:`-r -f`}function ns(e,t){return e===`from-file`?!0:t===void 0||t.some(({location:e})=>e!==`body`)?!1:t.every(({schemaFormat:e})=>e===`binary`)?!0:t.length===1&&[`file`,`path`].includes(e.split(`-`).at(-1)??``)}function rs(e){return new Map(e.flatMap(e=>[...e.parameters.map(e=>[e]),...An(e.requestBody??[]).map(({variant:e})=>e.map(({parameter:e})=>e))].flatMap(t=>{let n=t[0];if(n===void 0)throw Error(`Generated CLI option has no parameter`);return[[is(e.cliPath,n),t]]})))}function is(e,t){let n=`flag`in t?t.flag.split(/\s+/)[0]?.replace(/^--/,``):fs(t);if(`flag`in t&&(n===void 0||n.length===0||n===t.flag))throw Error(`Cannot render completion for option flag: ${t.flag}`);return`${e.join(`\0`)}\u0000${n??``}`}function as(e){return ps(e).flatMap(e=>e.commands.map(t=>({parentPath:hs(e),name:t.name(),description:vs(t.summary()||t.description()||t.name())})))}function os(e,t){let n=[],r=[];for(let i of ps(e)){let e=hs(i);for(let a of $o(i)){let i=fs(a);if(i===void 0)continue;let o=t.get(is(e,a));if(!cs(o))continue;let s=a.argChoices??ss(o),c=`none`;(a.required||a.optional)&&(c=s!==void 0&&s.length>0?`choice`:`scalar`,c===`scalar`&&ns(i,o)&&(c=`file`)),n.push(us([e.join(` `),`--${i}`,a.short??``,a.description,c]));for(let t of s??[])r.push(us([e.join(` `),`--${i}`,t,a.description]))}}return[as(e).map(e=>us([e.parentPath.join(` `),e.name,e.description])).toSorted((e,t)=>e.localeCompare(t)),n.toSorted((e,t)=>e.localeCompare(t)),r.toSorted((e,t)=>e.localeCompare(t))]}function ss(e){let t=e?.[0]?.choices;if(e!==void 0&&t!==void 0)return e.every(e=>e.choices?.length===t.length&&e.choices.every((e,n)=>e===t[n]))?t:void 0}function cs(e){return e?.some(({visibility:e})=>e!==`private`)??!0}function ls(e){let t=e===`bash`,n=t?`COMP_WORDS`:`words`,r=t?`COMP_CWORD`:`CURRENT`,i=t?"${path[*]}":"${(j: :)path}",a=t?'"${_aventure_cli_options[@]}"':`$_aventure_cli_options`,o=t?'"${_aventure_cli_values[@]}"':`$_aventure_cli_values`,s=t?'"${_aventure_cli_commands[@]}"':`$_aventure_cli_commands`;return[`function _aventure_cli {`,` local current="\${${n}[${r}]}" previous="\${${n}[${r}-1]}" row row_path long short description mode name value option token key prefix candidate file_current`,...t?[` COMPREPLY=()`]:[],` local index=${t?1:2} skip_next=0; local -a path names descriptions`,` while (( index < ${r} )); do`,` token="\${${n}[index]}"; (( skip_next )) && { skip_next=0; (( index++ )); continue; }`,` if [[ "$token" == -* && "$token" != "-" && "$token" != "--" ]]; then`,` option="\${token%%=*}"; key="${i}"; mode=''`,` for row in ${a}; do IFS='|' read -r row_path long short description mode <<< "$row"; [[ "$row_path" == "$key" && ( "$long" == "$option" || "$short" == "$option" ) ]] && break; mode=''; done`,` [[ -n "$mode" && "$mode" != none && "$token" != *=* ]] && skip_next=1`,` elif [[ "$token" != -* ]]; then path+=("$token"); fi`,` (( index++ ))`,` done`,` key="${i}"`,` if [[ "$current" == --*=* || ( "$previous" == -* && "$current" != -* ) ]]; then`,` option="$previous"; prefix=''; file_current="$current"; [[ "$current" == --*=* ]] && { option="\${current%%=*}"; prefix="$option="; file_current="\${current#*=}"; }`,` for row in ${a}; do IFS='|' read -r row_path long short description mode <<< "$row"; [[ "$row_path" == "$key" && ( "$long" == "$option" || "$short" == "$option" ) ]] && { option="$long"; break; }; mode=''; done`,t?` [[ "$mode" == file ]] && { while IFS= read -r candidate; do COMPREPLY+=("$prefix$candidate"); done < <(compgen -f -- "$file_current"); return 0; }`:` [[ "$mode" == file ]] && { _files; return 0; }`,t?` [[ "$mode" == choice ]] && for row in ${o}; do IFS='|' read -r row_path long value description <<< "$row"; [[ "$row_path" == "$key" && "$long" == "$option" ]] && { candidate="$prefix$value"; [[ "$candidate" == "$current"* ]] && COMPREPLY+=("$candidate"); }; done`:` [[ "$mode" == choice ]] && for row in ${o}; do IFS='|' read -r row_path long value description <<< "$row"; [[ "$row_path" == "$key" && "$long" == "$option" ]] && { names+=("$prefix$value"); descriptions+=("$description"); }; done`,` elif [[ "$current" == -* ]]; then`,` for row in ${a}; do`,` IFS='|' read -r row_path long short description mode <<< "$row"`,t?` [[ "$row_path" == "$key" ]] && { [[ "$long" == "$current"* ]] && COMPREPLY+=("$long"); [[ -n "$short" && "$short" == "$current"* ]] && COMPREPLY+=("$short"); }`:` [[ "$row_path" == "$key" ]] && { names+=("$long"); descriptions+=("$description"); [[ -n "$short" ]] && { names+=("$short"); descriptions+=("$description"); }; }`,` done`,` elif [[ "$previous" != -* ]]; then`,` for row in ${s}; do`,` IFS='|' read -r row_path name description <<< "$row"`,t?` [[ "$row_path" == "$key" ]] && { [[ "$name" == "$current"* ]] && COMPREPLY+=("$name"); }`:` [[ "$row_path" == "$key" ]] && { names+=("$name"); descriptions+=("$description"); }`,` done`,` fi`,...t?[]:[" (( ${#names} )) && compadd -d descriptions -a names"],` return 0`,`}`,...t?[]:[`_aventure_cli "$@"`]]}function us(e){return`$'${e.map(ds).join(`|`)}'`}function ds(e){return vs(e).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replaceAll(`|`,` `)}function fs(e){return e.long?.replace(/^--/,``)}function ps(e){return[e,...e.commands.filter(ms).flatMap(e=>ps(e))]}var ms=e=>e.parent?.createHelp().visibleCommands(e.parent).includes(e)??!0;function hs(e){let t=[];for(let n=e;n?.parent!==null;n=n.parent)t.unshift(n.name());return t}function gs(e){return`complete ${e.map(e=>`-c ${q(e)}`).join(` `)}`}function _s(e){return[`__aventure_cli_path_is`,...e.map(q)].join(` `)}function vs(e){return e.replace(/\s+/g,` `).trim()}function q(e){return`'${e.replace(/[\r\n\t]/g,` `).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`}function ys(e,t){if(e!==t)return;let n=bs(t);n!==void 0&&t.error(`error: ${Ss(t)} takes text input, not a JSON object.\n${n}`,{code:`aventure.payloadOperand`})}function bs(e){if(!process.argv.includes(`--`)&&e.args.some(xs))return`hint: use the command's named options instead of a JSON payload; run --help to list them.`}function xs(e){if(!e.startsWith(`{`))return!1;try{return typeof JSON.parse(e)==`object`}catch{return!1}}function Ss(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(` `)}function Cs(e,t){return e.message.match(RegExp(`${t} '([^']+)'`,`iu`))?.[1]?.split(/\s+/u)[0]}function J(e){return e.flags.split(` `)[0]??e.flags}function ws(e,t){let n=Cs(t,`required option`),r=e.options.findIndex(e=>J(e)===n);if(r<0)return;let i=new Set((Us(Y(e))?.parameters??[]).flatMap(e=>e.location===`path`?[e.optionKey]:[])),a=e.options.slice(r+1).find(t=>{let n=e.getOptionValue(t.attributeName());return i.has(t.attributeName())&&typeof n==`string`&&n!==``});if(a!==void 0)return`hint: ${n} is still required for this nested command; supplied child selector ${J(a)} does not replace the parent selector.`}var Ts=[[`--search`,`--query`,`--q`,`--term`,`--keyword`],[`--size`,`--limit`,`--page-size`,`--per-page`],[`--transaction-id`,`--fundraise-round-id`]];function Es(e){let t=new Set(e.options.map(J)),n=process.argv.indexOf(`--`),r=new Set(n<0?process.argv:process.argv.slice(0,n));return e.args.filter(e=>r.has(e)&&/^--[^-=]/u.test(e)).map(e=>e.split(`=`)[0]??e).filter(e=>!t.has(e))}function Ds(e){let t=Us(Y(e))?.parameters??[],n=Es(e).flatMap(n=>{let r=Ts.find(e=>e.includes(n))?.find(t=>e.options.some(e=>J(e)===t))??t.filter(({name:e})=>`--${e.replace(/[A-Z]/gu,`-$&`).toLowerCase()}`===n).map(e=>e.flag.split(` `)[0])[0];return r===void 0?[]:[`use ${r}, not ${n}`]});return n.length===0?void 0:`hint: ${n.join(`; `)}`}function Y(e){return e.parent===null?[]:[...Y(e.parent),e.name()]}function Os(e){return e.commands.length===0?[e]:e.commands.flatMap(Os)}function ks(e,t){return Y(t).slice(Y(e).length)}function X(e){return e.parent===null?e:X(e.parent)}function As(e,t){let n=t=>{let n=ks(e,t);return n.length*2+ +![`get`,`list`].includes(n.at(-1)??``)};return t.toSorted((e,t)=>n(e)-n(t))[0]}function js(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function Ms(e,t){let n=[...e.options,...e.createHelp().visibleOptions(e)];for(let t=e.parent;t!==null;t=t.parent)n.push(...t.options);let r=t,i;for(let e=0;e<t.length;e++){let a=t[e];if(a===void 0||a===`--`)break;if(!a.startsWith(`-`)||a===`-`||i?.variadic&&Number.isFinite(Number(a)))continue;let o=a.indexOf(`=`),s=o<0?a:a.slice(0,o);if(i=n.find(e=>e.short===s||e.long===s),i===void 0||o>=0&&!i.required&&!i.optional){r=[`--help`];break}o<0&&(i.required||i.optional&&!t[e+1]?.startsWith(`-`))&&e++}return[X(e).name(),...Y(e),...r].map(js).join(` `)}function Ns(e,t){let n=Cs(t,`unknown option`);if(n===void 0||e.commands.length===0)return;let r=As(e,Os(e).filter(e=>e.options.some(e=>J(e)===n)));return r===void 0?void 0:`hint: run: ${Ms(r,process.argv.slice(2+Y(e).length))}`}function Z(e){return e!==void 0&&Object.hasOwn(gt,e)}function Ps(e,t){return t.reduce((e,t)=>e?.commands.find(e=>e.name()===t),e)}function Fs(e,t){let n=Y(e),r=[...n.slice(1),t];if(!Z(n.at(0))||!Z(r.at(0)))return;let i=Ps(X(e),r);if(i===void 0)return;let a=i;for(let e of process.argv.slice(2+n.length+1)){if(e.startsWith(`-`))break;let t=a.commands.find(t=>t.name()===e);if(t===void 0)break;r.push(e),a=t}return r}function Is(e,t){let[n]=Y(e);if(!Z(n))return;let r=[n,t];return Ps(X(e),r)?.commands.length===0?r:void 0}function Ls(e){let[t,...n]=e.args;if(t===void 0)return[];let r=Os(X(e)).map(Y),i=n.findIndex((e,t)=>{let i=[...n.slice(0,t),e];return!r.some(e=>e.some((t,n)=>t===i[0]&&i.every((t,r)=>e[n+r]===t)))});return[t,...i<0?n:n.slice(0,i)]}function Rs(e,t){let n=process.argv.slice(2+Y(e).length);if(!(t.length===0||t.some((e,t)=>n[t]!==e)))return zs(e,t)}function zs(e,t,n=[]){let r=Y(e),i=yt(w).map(e=>e.cliPath).filter(e=>e[0]!==r[0]&&e.length>=t.length&&t.every((n,r)=>e[e.length-t.length+r]===n)),a=i.find(e=>e.length===t.length&&e.every((e,n)=>e===t[n]))??(i.length===1?i[0]:void 0);if(a===void 0)return;let o=Ps(X(e),a);return o===void 0?void 0:`hint: run: ${Ms(o,n)}`}function Bs(e,t,n){if(!Hs(t))return;let r=Ps(X(e),t);if(r===void 0)return;let i=e.args.slice(n.length),a=i.findIndex(e=>e.startsWith(`-`));return`hint: Did you mean: ${Ms(r,a<0?[]:i.slice(a))}`}function Vs(e){let t=Y(e);if(t.at(1)!==void 0&&Z(t.at(0)))return`hint: inspect generated command group: ${[X(e).name(),...t,`--help`].map(js).join(` `)}`}function Hs(e,t){let n=Us(e);return n!==void 0&&(t===void 0||_e(n.intent)===t)}function Us(e){return w.find(t=>t.cliPath.join(` `)===e.join(` `))}function Ws(e){let t=Y(e).join(` `),n=yt(w),r=n.find(e=>e.cliPath.join(` `)===t);return r===void 0?[]:Ae(r.operationId,n,X(e).name()).map(e=>`hint: ${e}`)}function Gs(e){let t=Y(e);if(Z(t.at(0))&&Hs(t))return`hint: inspect generated command: ${[X(e).name(),...t,`--help`].map(js).join(` `)}`}function Ks(e){let t=new Set,n=[];for(let r of w){let i=Ps(e,r.cliPath);if(i===void 0)continue;let a=i.options.map(J);if(_e(r.intent))n.push(a);else for(let e of a)t.add(e)}let[r=[],...i]=n;return new Set(r.filter(e=>!t.has(e)&&i.every(t=>t.includes(e))))}function qs(e,t){let n=Y(e);if(Hs(n,!1)&&Ks(X(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function Js(e,t,n=!0){let r=X(e),i=r.commands.find(e=>e.name()===`command-catalog`),a=i?.commands.find(e=>e.name()===`search`);if(i===void 0||a===void 0)return;let o=[r.name(),i.name(),a.name(),t],s=Y(e).at(0),c=a.options.find(e=>J(e)===`--root`),l=n&&c!==void 0&&Z(s)?s:void 0;c!==void 0&&l!==void 0&&o.push(J(c),l);let u=yt(w),d=_r({q:t,root:l,limit:`3`},u,r.name()),f=d.ok&&d.data!==null?Lr(d.data,`compact`):``;return[`hint: search generated commands: ${o.map(js).join(` `)}`,...f===``?[]:[`hint: closest commands (command · summary · required flags):`],...f.split(`
53
+ `))}function Qo(e,t){return os(e).map(e=>`${_s(t)} -f -n ${q(vs(e.parentPath))} -a ${q(e.name)} -d ${q(e.description)}`).toSorted((e,t)=>e.localeCompare(t))}function $o(e,t,n){return ms(e).flatMap(e=>{let r=gs(e),i=r.length===0?void 0:vs(r);return es(e).flatMap(e=>{let a=t.get(as(r,e));return ls(a)?ts(e,i,a,n):[]})}).toSorted((e,t)=>e.localeCompare(t))}function es(e){return e.parent===null?e.createHelp().visibleOptions(e):e.options}function ts(e,t,n,r){let i=ps(e);if(i===void 0)return[];let a=e.argChoices??cs(n),o=[`-l ${q(i)}`,e.short===void 0?``:`${e.short.startsWith(`--`)?`-l`:`-s`} ${q(e.short.replace(/^-+/,``))}`].filter(Boolean),s=t===void 0?``:` -n ${q(t)}`,c=e.required||e.optional?ns(a,rs(i,n)):`-f`,l=`${_s(r)}${s} ${o.join(` `)} ${c}`;return a===void 0||a.length===0?[`${l} -d ${q(ys(e.description))}`]:a.map(t=>`${l} -a ${q(t)} -d ${q(ys(e.description))}`)}function ns(e,t){return e!==void 0&&e.length>0?`-x`:t?`-r -F`:`-r -f`}function rs(e,t){return e===`from-file`?!0:t===void 0||t.some(({location:e})=>e!==`body`)?!1:t.every(({schemaFormat:e})=>e===`binary`)?!0:t.length===1&&[`file`,`path`].includes(e.split(`-`).at(-1)??``)}function is(e){return new Map(e.flatMap(e=>[...e.parameters.map(e=>[e]),...jn(e.requestBody??[]).map(({variant:e})=>e.map(({parameter:e})=>e))].flatMap(t=>{let n=t[0];if(n===void 0)throw Error(`Generated CLI option has no parameter`);return[[as(e.cliPath,n),t]]})))}function as(e,t){let n=`flag`in t?t.flag.split(/\s+/)[0]?.replace(/^--/,``):ps(t);if(`flag`in t&&(n===void 0||n.length===0||n===t.flag))throw Error(`Cannot render completion for option flag: ${t.flag}`);return`${e.join(`\0`)}\u0000${n??``}`}function os(e){return ms(e).flatMap(e=>e.commands.map(t=>({parentPath:gs(e),name:t.name(),description:ys(t.summary()||t.description()||t.name())})))}function ss(e,t){let n=[],r=[];for(let i of ms(e)){let e=gs(i);for(let a of es(i)){let i=ps(a);if(i===void 0)continue;let o=t.get(as(e,a));if(!ls(o))continue;let s=a.argChoices??cs(o),c=`none`;(a.required||a.optional)&&(c=s!==void 0&&s.length>0?`choice`:`scalar`,c===`scalar`&&rs(i,o)&&(c=`file`)),n.push(ds([e.join(` `),`--${i}`,a.short??``,a.description,c]));for(let t of s??[])r.push(ds([e.join(` `),`--${i}`,t,a.description]))}}return[os(e).map(e=>ds([e.parentPath.join(` `),e.name,e.description])).toSorted((e,t)=>e.localeCompare(t)),n.toSorted((e,t)=>e.localeCompare(t)),r.toSorted((e,t)=>e.localeCompare(t))]}function cs(e){let t=e?.[0]?.choices;if(e!==void 0&&t!==void 0)return e.every(e=>e.choices?.length===t.length&&e.choices.every((e,n)=>e===t[n]))?t:void 0}function ls(e){return e?.some(({visibility:e})=>e!==`private`)??!0}function us(e){let t=e===`bash`,n=t?`COMP_WORDS`:`words`,r=t?`COMP_CWORD`:`CURRENT`,i=t?"${path[*]}":"${(j: :)path}",a=t?'"${_aventure_cli_options[@]}"':`$_aventure_cli_options`,o=t?'"${_aventure_cli_values[@]}"':`$_aventure_cli_values`,s=t?'"${_aventure_cli_commands[@]}"':`$_aventure_cli_commands`;return[`function _aventure_cli {`,` local current="\${${n}[${r}]}" previous="\${${n}[${r}-1]}" row row_path long short description mode name value option token key prefix candidate file_current`,...t?[` COMPREPLY=()`]:[],` local index=${t?1:2} skip_next=0; local -a path names descriptions`,` while (( index < ${r} )); do`,` token="\${${n}[index]}"; (( skip_next )) && { skip_next=0; (( index++ )); continue; }`,` if [[ "$token" == -* && "$token" != "-" && "$token" != "--" ]]; then`,` option="\${token%%=*}"; key="${i}"; mode=''`,` for row in ${a}; do IFS='|' read -r row_path long short description mode <<< "$row"; [[ "$row_path" == "$key" && ( "$long" == "$option" || "$short" == "$option" ) ]] && break; mode=''; done`,` [[ -n "$mode" && "$mode" != none && "$token" != *=* ]] && skip_next=1`,` elif [[ "$token" != -* ]]; then path+=("$token"); fi`,` (( index++ ))`,` done`,` key="${i}"`,` if [[ "$current" == --*=* || ( "$previous" == -* && "$current" != -* ) ]]; then`,` option="$previous"; prefix=''; file_current="$current"; [[ "$current" == --*=* ]] && { option="\${current%%=*}"; prefix="$option="; file_current="\${current#*=}"; }`,` for row in ${a}; do IFS='|' read -r row_path long short description mode <<< "$row"; [[ "$row_path" == "$key" && ( "$long" == "$option" || "$short" == "$option" ) ]] && { option="$long"; break; }; mode=''; done`,t?` [[ "$mode" == file ]] && { while IFS= read -r candidate; do COMPREPLY+=("$prefix$candidate"); done < <(compgen -f -- "$file_current"); return 0; }`:` [[ "$mode" == file ]] && { _files; return 0; }`,t?` [[ "$mode" == choice ]] && for row in ${o}; do IFS='|' read -r row_path long value description <<< "$row"; [[ "$row_path" == "$key" && "$long" == "$option" ]] && { candidate="$prefix$value"; [[ "$candidate" == "$current"* ]] && COMPREPLY+=("$candidate"); }; done`:` [[ "$mode" == choice ]] && for row in ${o}; do IFS='|' read -r row_path long value description <<< "$row"; [[ "$row_path" == "$key" && "$long" == "$option" ]] && { names+=("$prefix$value"); descriptions+=("$description"); }; done`,` elif [[ "$current" == -* ]]; then`,` for row in ${a}; do`,` IFS='|' read -r row_path long short description mode <<< "$row"`,t?` [[ "$row_path" == "$key" ]] && { [[ "$long" == "$current"* ]] && COMPREPLY+=("$long"); [[ -n "$short" && "$short" == "$current"* ]] && COMPREPLY+=("$short"); }`:` [[ "$row_path" == "$key" ]] && { names+=("$long"); descriptions+=("$description"); [[ -n "$short" ]] && { names+=("$short"); descriptions+=("$description"); }; }`,` done`,` elif [[ "$previous" != -* ]]; then`,` for row in ${s}; do`,` IFS='|' read -r row_path name description <<< "$row"`,t?` [[ "$row_path" == "$key" ]] && { [[ "$name" == "$current"* ]] && COMPREPLY+=("$name"); }`:` [[ "$row_path" == "$key" ]] && { names+=("$name"); descriptions+=("$description"); }`,` done`,` fi`,...t?[]:[" (( ${#names} )) && compadd -d descriptions -a names"],` return 0`,`}`,...t?[]:[`_aventure_cli "$@"`]]}function ds(e){return`$'${e.map(fs).join(`|`)}'`}function fs(e){return ys(e).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`).replaceAll(`|`,` `)}function ps(e){return e.long?.replace(/^--/,``)}function ms(e){return[e,...e.commands.filter(hs).flatMap(e=>ms(e))]}var hs=e=>e.parent?.createHelp().visibleCommands(e.parent).includes(e)??!0;function gs(e){let t=[];for(let n=e;n?.parent!==null;n=n.parent)t.unshift(n.name());return t}function _s(e){return`complete ${e.map(e=>`-c ${q(e)}`).join(` `)}`}function vs(e){return[`__aventure_cli_path_is`,...e.map(q)].join(` `)}function ys(e){return e.replace(/\s+/g,` `).trim()}function q(e){return`'${e.replace(/[\r\n\t]/g,` `).replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`}function bs(e,t){if(e!==t)return;let n=xs(t);n!==void 0&&t.error(`error: ${Cs(t)} takes text input, not a JSON object.\n${n}`,{code:`aventure.payloadOperand`})}function xs(e){if(!process.argv.includes(`--`)&&e.args.some(Ss))return`hint: use the command's named options instead of a JSON payload; run --help to list them.`}function Ss(e){if(!e.startsWith(`{`))return!1;try{return typeof JSON.parse(e)==`object`}catch{return!1}}function Cs(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(` `)}function ws(e,t){return e.message.match(RegExp(`${t} '([^']+)'`,`iu`))?.[1]?.split(/\s+/u)[0]}function J(e){return e.flags.split(` `)[0]??e.flags}function Ts(e,t){let n=ws(t,`required option`),r=e.options.findIndex(e=>J(e)===n);if(r<0)return;let i=new Set((Ws(Y(e))?.parameters??[]).flatMap(e=>e.location===`path`?[e.optionKey]:[])),a=e.options.slice(r+1).find(t=>{let n=e.getOptionValue(t.attributeName());return i.has(t.attributeName())&&typeof n==`string`&&n!==``});if(a!==void 0)return`hint: ${n} is still required for this nested command; supplied child selector ${J(a)} does not replace the parent selector.`}var Es=[[`--search`,`--query`,`--q`,`--term`,`--keyword`],[`--size`,`--limit`,`--page-size`,`--per-page`],[`--transaction-id`,`--fundraise-round-id`]];function Ds(e){let t=new Set(e.options.map(J)),n=process.argv.indexOf(`--`),r=new Set(n<0?process.argv:process.argv.slice(0,n));return e.args.filter(e=>r.has(e)&&/^--[^-=]/u.test(e)).map(e=>e.split(`=`)[0]??e).filter(e=>!t.has(e))}function Os(e){let t=Ws(Y(e))?.parameters??[],n=Ds(e).flatMap(n=>{let r=Es.find(e=>e.includes(n))?.find(t=>e.options.some(e=>J(e)===t))??t.filter(({name:e})=>`--${e.replace(/[A-Z]/gu,`-$&`).toLowerCase()}`===n).map(e=>e.flag.split(` `)[0])[0];return r===void 0?[]:[`use ${r}, not ${n}`]});return n.length===0?void 0:`hint: ${n.join(`; `)}`}function Y(e){return e.parent===null?[]:[...Y(e.parent),e.name()]}function ks(e){return e.commands.length===0?[e]:e.commands.flatMap(ks)}function As(e,t){return Y(t).slice(Y(e).length)}function X(e){return e.parent===null?e:X(e.parent)}function js(e,t){let n=t=>{let n=As(e,t);return n.length*2+ +![`get`,`list`].includes(n.at(-1)??``)};return t.toSorted((e,t)=>n(e)-n(t))[0]}function Ms(e){return/^[A-Za-z0-9_./:=@+-]+$/u.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function Ns(e,t){let n=[...e.options,...e.createHelp().visibleOptions(e)];for(let t=e.parent;t!==null;t=t.parent)n.push(...t.options);let r=t,i;for(let e=0;e<t.length;e++){let a=t[e];if(a===void 0||a===`--`)break;if(!a.startsWith(`-`)||a===`-`||i?.variadic&&Number.isFinite(Number(a)))continue;let o=a.indexOf(`=`),s=o<0?a:a.slice(0,o);if(i=n.find(e=>e.short===s||e.long===s),i===void 0||o>=0&&!i.required&&!i.optional){r=[`--help`];break}o<0&&(i.required||i.optional&&!t[e+1]?.startsWith(`-`))&&e++}return[X(e).name(),...Y(e),...r].map(Ms).join(` `)}function Ps(e,t){let n=ws(t,`unknown option`);if(n===void 0||e.commands.length===0)return;let r=js(e,ks(e).filter(e=>e.options.some(e=>J(e)===n)));return r===void 0?void 0:`hint: run: ${Ns(r,process.argv.slice(2+Y(e).length))}`}function Z(e){return e!==void 0&&Object.hasOwn(gt,e)}function Fs(e,t){return t.reduce((e,t)=>e?.commands.find(e=>e.name()===t),e)}function Is(e,t){let n=Y(e),r=[...n.slice(1),t];if(!Z(n.at(0))||!Z(r.at(0)))return;let i=Fs(X(e),r);if(i===void 0)return;let a=i;for(let e of process.argv.slice(2+n.length+1)){if(e.startsWith(`-`))break;let t=a.commands.find(t=>t.name()===e);if(t===void 0)break;r.push(e),a=t}return r}function Ls(e,t){let[n]=Y(e);if(n===void 0||!Z(n))return;let r=[n,t];return Fs(X(e),r)?.commands.length===0?r:void 0}function Rs(e){let[t,...n]=e.args;if(t===void 0)return[];let r=ks(X(e)).map(Y),i=n.findIndex((e,t)=>{let i=[...n.slice(0,t),e];return!r.some(e=>e.some((t,n)=>t===i[0]&&i.every((t,r)=>e[n+r]===t)))});return[t,...i<0?n:n.slice(0,i)]}function zs(e,t){let n=process.argv.slice(2+Y(e).length);if(!(t.length===0||t.some((e,t)=>n[t]!==e)))return Bs(e,t)}function Bs(e,t,n=[]){let r=Y(e),i=yt(w).map(e=>e.cliPath).filter(e=>e[0]!==r[0]&&e.length>=t.length&&t.every((n,r)=>e[e.length-t.length+r]===n)),a=i.find(e=>e.length===t.length&&e.every((e,n)=>e===t[n]))??(i.length===1?i[0]:void 0);if(a===void 0)return;let o=Fs(X(e),a);return o===void 0?void 0:`hint: run: ${Ns(o,n)}`}function Vs(e,t,n){if(!Us(t))return;let r=Fs(X(e),t);if(r===void 0)return;let i=e.args.slice(n.length),a=i.findIndex(e=>e.startsWith(`-`));return`hint: Did you mean: ${Ns(r,a<0?[]:i.slice(a))}`}function Hs(e){let t=Y(e);if(t.at(1)!==void 0&&Z(t.at(0)))return`hint: inspect generated command group: ${[X(e).name(),...t,`--help`].map(Ms).join(` `)}`}function Us(e,t){let n=Ws(e);return n!==void 0&&(t===void 0||_e(n.intent)===t)}function Ws(e){return w.find(t=>t.cliPath.join(` `)===e.join(` `))}function Gs(e){let t=Y(e).join(` `),n=yt(w),r=n.find(e=>e.cliPath.join(` `)===t);return r===void 0?[]:Ae(r.operationId,n,X(e).name()).map(e=>`hint: ${e}`)}function Ks(e){let t=Y(e);if(Z(t.at(0))&&Us(t))return`hint: inspect generated command: ${[X(e).name(),...t,`--help`].map(Ms).join(` `)}`}function qs(e){let t=new Set,n=[];for(let r of w){let i=Fs(e,r.cliPath);if(i===void 0)continue;let a=i.options.map(J);if(_e(r.intent))n.push(a);else for(let e of a)t.add(e)}let[r=[],...i]=n;return new Set(r.filter(e=>!t.has(e)&&i.every(t=>t.includes(e))))}function Js(e,t){let n=Y(e);if(Us(n,!1)&&qs(X(e)).has(t))return`hint: ${n.join(` `)} is a read operation; ${t} is a deprecated compatibility option only on mutation commands`}function Ys(e,t,n=!0){let r=X(e),i=r.commands.find(e=>e.name()===`command-catalog`),a=i?.commands.find(e=>e.name()===`search`);if(i===void 0||a===void 0)return;let o=[r.name(),i.name(),a.name(),t],s=Y(e).at(0),c=a.options.find(e=>J(e)===`--root`),l=n&&c!==void 0&&Z(s)?s:void 0;c!==void 0&&l!==void 0&&o.push(J(c),l);let u=yt(w),d=vr({q:t,root:l,limit:`3`},u,r.name()),f=d.ok&&d.data!==null?Rr(d.data,`compact`):``;return[`hint: search generated commands: ${o.map(Ms).join(` `)}`,...f===``?[]:[`hint: closest commands (command · summary · required flags):`],...f.split(`
54
54
  `).filter(Boolean).map(e=>` ${e}`)].join(`
55
- `)}function Ys(e,t=``){if(e.commands.length>0&&!Hs(Y(e)))return;let n=e.options.flatMap(e=>e.hidden?[]:[J(e)]),r=yt(w),i=Fe(t,r,Y(e),X(e).name());return`${i===void 0?``:`hint: an id you already hold is read with: ${i}\n`}hint: ${Y(e).join(` `)} accepts: ${n.join(` `)}`}function Xs(e,t){let n=Cs(t,`unknown command`);if(n===void 0||t.message.includes(`
56
- (Did you mean `))return;let r=Ls(e),i=Rs(e,r);if(i!==void 0)return i;let a=Y(e),o=[...a.slice(0,-1),`${a.at(-1)}-${n}`,...r.slice(1)],s=(Hs(o)?o:void 0)??Fs(e,n)??Is(e,n);if(s!==void 0)return Bs(e,s,r)??Js(e,s.join(` `),!1);let c=r.join(` `)||n,l=Vs(e)??Js(e,c),u=[...a,...r.slice(1)];return[l,r.length===a.length+a.length&&a.at(-1)===a.at(0)?Bs(e,u,r)?.replace(/^hint: Did you mean: /u,` `)+` · `:u.slice(1,-1).length>0?Bs(e,u,r):void 0].filter(e=>e!==void 0).join(`
57
- `)||void 0}function Zs(e){return t=>{if(t.code===`commander.missingMandatoryOptionValue`){let n=e.options.filter(t=>t.mandatory&&e.getOptionValue(t.attributeName())===void 0);if(n.length>1){let e=n.map(e=>e.flags.split(`, `).at(-1)??e.flags);process.stderr.write(`error: missing required options: ${e.join(`, `)}\n`)}let r=Es(e);for(let e of r)process.stderr.write(`error: unknown option '${e}'\n`);for(let n of[Ds(e)??(r.length>0?Ys(e):void 0),bs(e),ws(e,t),...Ws(e)])n!==void 0&&process.stderr.write(`${n}\n`)}else if(t.code===`commander.excessArguments`){let t=bs(e)??Gs(e);t!==void 0&&process.stderr.write(`${t}\n`)}else if(t.code===`commander.unknownOption`){let n=Cs(t,`unknown option`),r=Ds(e)??Ns(e,t)??(n!==void 0&&!t.message.includes(`
58
- (Did you mean `)?qs(e,n)??zs(e,[n.replace(/^--/u,``)],process.argv.slice(process.argv.indexOf(n)+1))??Ys(e,n)??Js(e,Y(e).slice(1).join(` `)||n.replace(/^--/u,``)):void 0);r!==void 0&&process.stderr.write(`${r}\n`)}else if(t.code===`commander.unknownCommand`){let n=Xs(e,t);n!==void 0&&process.stderr.write(`${n}\n`)}process.exit(t.exitCode)}}var Qs=class extends e{group;constructor(e){super(`-h, --help`,`display help for command`),this.group=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.group.args.at(0);return t===void 0||t.startsWith(`-`)?!0:this.group.commands.some(e=>e.name()===t||e.aliases().includes(t))}};function $s(e){e.showHelpAfterError(!1).exitOverride(Zs(e)),e.commands.length===0?e.hook(`preAction`,ys):e.registeredArguments.length===0&&e.addHelpOption(new Qs(e));for(let t of e.commands)$s(t)}function ec(e,t=new Date){let n=rc(e);return{schemaVersion:1,generatedFrom:`MCP_GENERATION_CONTRACT`,generatedAt:t.toISOString(),totalOperations:n.length,note:`Projection of MCP_GENERATION_CONTRACT - see mcp/scripts/build-unified-operations.ts header for SSOT rules.`,operations:n}}function tc(e){return`${JSON.stringify(e,null,2)}\n`}function nc(e,t){let n=k(e),r=tc(t);return Nt(O(n),{recursive:!0}),Vt(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function rc(e){return e.map(e=>({operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,cliCommand:e.projection.cliPath.join(` `),cliPath:e.projection.cliPath,mcpTool:be(e.intent),bodySchemaName:e.requestBody?.[0]?.schemaName??null,bodySchemaImport:e.requestBody?.[0]?.schemaImport??null,auth:e.projection.auth,scope:e.projection.scope,destructive:e.projection.destructive})).toSorted((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)||e.operationId.localeCompare(t.operationId))}var ic=`Match only the first canonical or CLI-alias command segment`,ac=[`text`,`lines`,`compact`,`json`,`ndjson`];function oc(e,t,n=b().bin[0]){let r=e.command(`command-catalog`).summary(`LLM agent only: search generated CLI metadata`).description([`LLM agent only: search and dump generated ${n} command metadata.`,`This is read-only command metadata derived from the generated OpenAPI command specs.`,`Use --format lines for rg/grep/ag/ack and --format ndjson|json for ast-grep/sg/parsers.`,"Use --format compact for one `cli · summary · requiredFlags` row per operation."].join(`
59
- `));r.addHelpText(`after`,()=>`\nShipped compact catalog of operations callable without an admin grant, greppable without\nrunning this CLI (dump --format compact lists every operation your credential reaches):\n ${kr(n)}\n`),sc(r,t,n),cc(r,t,n),lc(r,t,n),uc(r)}function sc(t,n,r){let i=t.command(`search`).summary(`Search generated operations`).description(`Search generated operation metadata without calling the API.`).argument(`[query...]`,`Search query; same as --q.`).option(`--q <query>`,`Search generated command metadata`).option(`--root <root>`,ic).addOption(new e(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new e(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new e(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new e(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new e(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`,`20`).addOption(new e(`--format <format>`,`Text/file render format`).choices(ac)).option(`--output <path>`,`Write rendered output to a file`);E(i),i.action(function(e){let t=this.optsWithGlobals(),i=T(t,`text`);Mr(jr(t,e),n,i,r)})}function cc(t,n,r){let i=t.command(`show`).summary(`Show one generated operation`).description(`Show one generated operation by command path or operationId.`).option(`--command <command>`,`CLI command path, with or without ${r} prefix`).option(`--operation-id <operationId>`,`Generated OpenAPI operationId`).addOption(new e(`--format <format>`,`Text/file render format`).choices([`usage`,`lines`,`compact`,`json`,`ndjson`]).default(`usage`)).option(`--output <path>`,`Write rendered output to a file`);E(i),i.action(function(){let e=this.optsWithGlobals();Nr(e,n,T(e,`text`),r)})}function lc(t,n,r){let i=t.command(`dump`).summary(`Dump generated operations`).description(`Dump generated operations for rg/grep/ag/ack or JSON/NDJSON tooling.`).option(`--root <root>`,ic).addOption(new e(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new e(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new e(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new e(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new e(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`).addOption(new e(`--format <format>`,`Text/file render format`).choices(ac)).option(`--output <path>`,`Write rendered output to a file`);E(i),i.action(function(){let e=this.optsWithGlobals();Mr(e,n,T(e,`text`),r)})}function uc(e){let t=e.command(`unified`).summary(`Dump unified CLI/API/MCP operation JSON`).description(`Dump the flat unified operations JSON projected from MCP_GENERATION_CONTRACT.`).option(`--output <path>`,`Write unified operations JSON to a file`);E(t),t.action(async function(){let e=this.optsWithGlobals(),t=T(e,`text`),{MCP_GENERATION_CONTRACT:n}=await import(`./mcp-generation-contract-C9hxM3KU.js`);if(t===`text`&&e.output===void 0&&(e.text===!0||e.allFields===!0)){L({mode:t},_(`Unified operations JSON`,`Use --output <path> to write the unified operations JSON.`,{counts:{totalOperations:n.length}}));return}let r=ec(n);if(e.output!==void 0){let n=nc(e.output,r);L({mode:t},_(`Unified operations JSON written`,{outputPath:n.target,byteLength:n.byteLength,schemaVersion:r.schemaVersion},{counts:{totalOperations:n.totalOperations}}));return}if(t===`text`){Fr(`Unified operations JSON`,tc(r));return}L({mode:t},_(`Unified operations JSON`,r,{counts:{totalOperations:r.totalOperations}}))})}var dc=b(Jt(import.meta.url)),Q=dc.bin[0];function fc(e,t){i({component:Q,event:`fatal`,message:e.message,error:e}),process.stderr.write(`${Q} fatal (${t}): ${e.stack??e.message}\n`);let n=e instanceof h?{httpStatus:e.problem.status,problem:e.problem}:{};sr({...g(`${Q} ${t}: ${e.message}`,[e.name||`Error`],n),counts:{exitCode:1}}),process.exit(1)}function pc(e){return Ue[ze(e,gt)??`cli`]}function mc(e,t){let n=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:pc(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec),r=new Set(n.filter(e=>wt(e.cliPath[0])).map(e=>e.cliPath[0]??``)),i=new Set,a=new Set;for(let{cliPath:e,deprecated:t}of n)for(let n=1;n<e.length;n++){let r=e.slice(0,n).join(` `);i.add(r),t!==!0&&a.add(r)}for(let t of n)hc(e,t,r,a,i.has(t.cliPath.join(` `)))}function hc(e,t,n,r,i){let a=t.cliPath,o=e,s=``,c=!n.has(a[0]??``);for(let e of a.slice(0,-1)){s=s===``?e:`${s} ${e}`;let t=c&&s===e||!r.has(s);o=gc(o,e,s,t)}let l=a.at(-1)??t.operationId,u=o.commands.find(e=>e.name()===l)??o.command(l,t.deprecated===!0?{hidden:!0}:{}),d=t.requestBody?.flatMap(({parameter:e})=>e)??[];u.summary(t.summary||t.operationId).description([`${t.method} ${t.path}.`,t.summary||t.description,`Full documentation: ${Q} help ${t.cliPath.join(` `)}`,t.requestBody?.[0]?.kind===`json`||[...t.parameters,...d].some(e=>ye(e.schemaType,e.itemSchemaType))?xe:``].filter(Boolean).join(`
60
- `));let f=Tt(t);for(let e of t.parameters)_c(u,e,i||e===f);if(Bn(u,t),_e(t.intent)&&u.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),E(u),u.hook(`preAction`,e=>bt(e,t)),t.explain===!0&&u.option(`--explain`,`Print the search strategy and parsed constraints before the results`),f!==void 0){u.argument(`[text...]`,f.description||`Same as ${Ct(f.flag)}.`),u.action(async function(e){let n=this.optsWithGlobals(),r=T(n),i=vt(f,e,n);if(!i.ok||i.data===null)return L({mode:r},i);let a=_t(t,i.data);if(a.length>0)return L({mode:r},g(`missing required options: ${a.join(`, `)}`));let o=await vc(t,i.data,r),s=ri(t,i.data,o);if(s!==null)return L({mode:r},s);n.explain===!0&&o.ok&&dr(r,o.data),o.ok&&o.data instanceof Uint8Array?process.stdout.write(o.data):L({mode:r},o)});return}u.action(async function(){let e=this.optsWithGlobals(),n=T(e),r=_t(t,e);if(r.length>0)return L({mode:n},g(`missing required options: ${r.join(`, `)}`));let i=await vc(t,e,n),a=ri(t,e,i);if(a!==null)return L({mode:n},a);e.explain===!0&&i.ok&&dr(n,i.data),i.ok&&i.data instanceof Uint8Array?process.stdout.write(i.data):L({mode:n},i)})}function gc(e,t,n,r){let i=e.commands.find(e=>e.name()===t);if(i!==void 0)return i;let a=gt[n],o=e.command(t,r?{hidden:!0}:{}).helpCommand(!1);return a!==void 0&&o.summary(a.summary).description(a.summary),o}function _c(t,n,r=!1){let i=n.description||`${n.name} ${n.location} parameter`,a=n.defaultValue===void 0?void 0:typeof n.defaultValue==`string`||typeof n.defaultValue==`boolean`?n.defaultValue:[...n.defaultValue];if(n.legacyFlag!==void 0){let o=new e(n.flag,i);a!==void 0&&o.default(a);let s=new e(n.legacyFlag,i).conflicts(n.optionKey);t.addOption(o).addOption(s),t.hook(`preAction`,e=>{let t=e.opts(),i=t[n.optionKey],a=t[s.attributeName()];if(a!==void 0){(i===void 0||e.getOptionValueSource(n.optionKey)==="default")&&e.setOptionValueWithSource(n.optionKey,a,`cli`);return}!r&&n.required&&i===void 0&&e.error(`error: required option '${o.flags}' not specified`,{code:`commander.missingMandatoryOptionValue`})});return}if(a!==void 0){t.option(n.flag,i,a);return}if(n.required&&!r){t.requiredOption(n.flag,i);return}t.option(n.flag,i)}async function vc(e,t,n){if(t.environment!==void 0){let e=ue(t.environment);if(e===null)return g(`Unknown aVenture environment '${t.environment}'`,[`Use one of: ${ce().join(`, `)}`]);process.env.API_ENV=e}let r=await Gn(e,t);if(!r.ok)return r;let i=Object.fromEntries(e.parameters.filter(e=>e.location===`path`).map(e=>{let n=t[e.optionKey];if(Array.isArray(n))return[e.name,n.at(0)??``];if(n===void 0)throw Error(`Missing required option ${e.optionKey}`);return[e.name,String(n)]})),a=Object.fromEntries(e.parameters.filter(e=>e.location===`query`).flatMap(e=>{let n=t[e.optionKey];if(n===void 0||Array.isArray(n)&&n.length===0)return[];let r=Array.isArray(n)||typeof n==`boolean`?n:String(n);return[[e.name,r]]})),o=Object.fromEntries(e.parameters.filter(e=>e.location===`header`).flatMap(e=>{let n=t[e.optionKey];return n===void 0||Array.isArray(n)&&n.length===0?[]:[[e.name,Array.isArray(n)?n.join(`,`):String(n)]]}));return ai(e,await p({method:e.method,path:m(e.operationId,i),searchParams:a,headers:o,body:r.data,contentType:St(e,t),auth:e.auth,responseFormat:Dt(n)?`json`:`auto`,responseBytes:e.binaryResponse===!0}))}process.on(`uncaughtException`,e=>fc(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>fc(e instanceof Error?e:Error(String(e)),`unhandledRejection`));var yc=xt(process.argv.slice(2),w),bc=yc===`required`?w:yt(w),$=new r;$.name(Q).usage(`<command> [subcommand] [options]`).configureHelp(Jr).version(dc.version).summary(`CLI for the aVenture API: companies, people, and news, with the funding, publications, and classifications attached to them`).description([`The aVenture research API from your terminal. Three records — companies,`,`people, and news — carry everything else: funding, publications, and tags.
55
+ `)}function Xs(e,t=``){if(e.commands.length>0&&!Us(Y(e)))return;let n=e.options.flatMap(e=>e.hidden?[]:[J(e)]),r=yt(w),i=Fe(t,r,Y(e),X(e).name());return`${i===void 0?``:`hint: an id you already hold is read with: ${i}\n`}hint: ${Y(e).join(` `)} accepts: ${n.join(` `)}`}function Zs(e,t){let n=ws(t,`unknown command`);if(n===void 0||t.message.includes(`
56
+ (Did you mean `))return;let r=Rs(e),i=zs(e,r);if(i!==void 0)return i;let a=Y(e),o=[...a.slice(0,-1),`${a.at(-1)}-${n}`,...r.slice(1)],s=(Us(o)?o:void 0)??Is(e,n)??Ls(e,n);if(s!==void 0)return Vs(e,s,r)??Ys(e,s.join(` `),!1);let c=r.join(` `)||n,l=Hs(e)??Ys(e,c),u=[...a,...r.slice(1)];return[l,r.length===a.length+a.length&&a.at(-1)===a.at(0)?Vs(e,u,r)?.replace(/^hint: Did you mean: /u,` `)+` · `:u.slice(1,-1).length>0?Vs(e,u,r):void 0].filter(e=>e!==void 0).join(`
57
+ `)||void 0}function Qs(e){return t=>{if(t.code===`commander.missingMandatoryOptionValue`){let n=e.options.filter(t=>t.mandatory&&e.getOptionValue(t.attributeName())===void 0);if(n.length>1){let e=n.map(e=>e.flags.split(`, `).at(-1)??e.flags);process.stderr.write(`error: missing required options: ${e.join(`, `)}\n`)}let r=Ds(e);for(let e of r)process.stderr.write(`error: unknown option '${e}'\n`);for(let n of[Os(e)??(r.length>0?Xs(e):void 0),xs(e),Ts(e,t),...Gs(e)])n!==void 0&&process.stderr.write(`${n}\n`)}else if(t.code===`commander.excessArguments`){let t=xs(e)??Ks(e);t!==void 0&&process.stderr.write(`${t}\n`)}else if(t.code===`commander.unknownOption`){let n=ws(t,`unknown option`),r=Os(e)??Ps(e,t)??(n!==void 0&&!t.message.includes(`
58
+ (Did you mean `)?Js(e,n)??Bs(e,[n.replace(/^--/u,``)],process.argv.slice(process.argv.indexOf(n)+1))??Xs(e,n)??Ys(e,Y(e).slice(1).join(` `)||n.replace(/^--/u,``)):void 0);r!==void 0&&process.stderr.write(`${r}\n`)}else if(t.code===`commander.unknownCommand`){let n=Zs(e,t);n!==void 0&&process.stderr.write(`${n}\n`)}process.exit(t.exitCode)}}var $s=class extends e{group;constructor(e){super(`-h, --help`,`display help for command`),this.group=e}is(e){if(e!==this.short&&e!==this.long)return!1;let t=this.group.args.at(0);return t===void 0||t.startsWith(`-`)?!0:this.group.commands.some(e=>e.name()===t||e.aliases().includes(t))}};function ec(e){e.showHelpAfterError(!1).exitOverride(Qs(e)),e.commands.length===0?e.hook(`preAction`,bs):e.registeredArguments.length===0&&e.addHelpOption(new $s(e));for(let t of e.commands)ec(t)}function tc(e,t=new Date){let n=ic(e);return{schemaVersion:1,generatedFrom:`MCP_GENERATION_CONTRACT`,generatedAt:t.toISOString(),totalOperations:n.length,note:`Projection of MCP_GENERATION_CONTRACT - see mcp/scripts/build-unified-operations.ts header for SSOT rules.`,operations:n}}function nc(e){return`${JSON.stringify(e,null,2)}\n`}function rc(e,t){let n=k(e),r=nc(t);return Nt(O(n),{recursive:!0}),Vt(n,r),{target:n,byteLength:Buffer.byteLength(r,`utf8`),totalOperations:t.totalOperations}}function ic(e){return e.map(e=>({operationId:e.operationId,method:e.method,path:e.path,resource:e.resource,intent:e.intent,cliCommand:e.projection.cliPath.join(` `),cliPath:e.projection.cliPath,mcpTool:be(e.intent),bodySchemaName:e.requestBody?.[0]?.schemaName??null,bodySchemaImport:e.requestBody?.[0]?.schemaImport??null,auth:e.projection.auth,scope:e.projection.scope,destructive:e.projection.destructive})).toSorted((e,t)=>e.path.localeCompare(t.path)||e.method.localeCompare(t.method)||e.operationId.localeCompare(t.operationId))}var ac=`Match only the first canonical or CLI-alias command segment`,oc=[`text`,`lines`,`compact`,`json`,`ndjson`];function sc(e,t,n=b().bin[0]){let r=e.command(`command-catalog`).summary(`LLM agent only: search generated CLI metadata`).description([`LLM agent only: search and dump generated ${n} command metadata.`,`This is read-only command metadata derived from the generated OpenAPI command specs.`,`Use --format lines for rg/grep/ag/ack and --format ndjson|json for ast-grep/sg/parsers.`,"Use --format compact for one `cli · summary · requiredFlags` row per operation."].join(`
59
+ `));r.addHelpText(`after`,()=>`\nShipped compact catalog of operations callable without an admin grant, greppable without\nrunning this CLI (dump --format compact lists every operation your credential reaches):\n ${Ar(n)}\n`),cc(r,t,n),lc(r,t,n),uc(r,t,n),dc(r)}function cc(t,n,r){let i=t.command(`search`).summary(`Search generated operations`).description(`Search generated operation metadata without calling the API.`).argument(`[query...]`,`Search query; same as --q.`).option(`--q <query>`,`Search generated command metadata`).option(`--root <root>`,ac).addOption(new e(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new e(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new e(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new e(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new e(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`,`20`).addOption(new e(`--format <format>`,`Text/file render format`).choices(oc)).option(`--output <path>`,`Write rendered output to a file`);E(i),i.action(function(e){let t=this.optsWithGlobals(),i=T(t,`text`);Nr(Mr(t,e),n,i,r)})}function lc(t,n,r){let i=t.command(`show`).summary(`Show one generated operation`).description(`Show one generated operation by command path or operationId.`).option(`--command <command>`,`CLI command path, with or without ${r} prefix`).option(`--operation-id <operationId>`,`Generated OpenAPI operationId`).addOption(new e(`--format <format>`,`Text/file render format`).choices([`usage`,`lines`,`compact`,`json`,`ndjson`]).default(`usage`)).option(`--output <path>`,`Write rendered output to a file`);E(i),i.action(function(){let e=this.optsWithGlobals();Pr(e,n,T(e,`text`),r)})}function uc(t,n,r){let i=t.command(`dump`).summary(`Dump generated operations`).description(`Dump generated operations for rg/grep/ag/ack or JSON/NDJSON tooling.`).option(`--root <root>`,ac).addOption(new e(`--scope <scope>`,`Filter by required auth scope`).choices([`read`,`write`,`all`]).default(`all`)).addOption(new e(`--mutates <mutates>`,`Filter mutating operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new e(`--destructive <destructive>`,`Filter destructive operations`).choices([`true`,`false`,`any`]).default(`any`)).addOption(new e(`--intent <intent>`,`Filter by operation intent`).choices([`read`,`lookup`,`search`,`write`,`delete`,`status`,`all`]).default(`all`)).addOption(new e(`--method <method>`,`Filter by HTTP method`).choices([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`all`]).default(`all`)).option(`--limit <count>`,`Maximum rows to return`).addOption(new e(`--format <format>`,`Text/file render format`).choices(oc)).option(`--output <path>`,`Write rendered output to a file`);E(i),i.action(function(){let e=this.optsWithGlobals();Nr(e,n,T(e,`text`),r)})}function dc(e){let t=e.command(`unified`).summary(`Dump unified CLI/API/MCP operation JSON`).description(`Dump the flat unified operations JSON projected from MCP_GENERATION_CONTRACT.`).option(`--output <path>`,`Write unified operations JSON to a file`);E(t),t.action(async function(){let e=this.optsWithGlobals(),t=T(e,`text`),{MCP_GENERATION_CONTRACT:n}=await import(`./mcp-generation-contract-C9hxM3KU.js`);if(t===`text`&&e.output===void 0&&(e.text===!0||e.allFields===!0)){L({mode:t},_(`Unified operations JSON`,`Use --output <path> to write the unified operations JSON.`,{counts:{totalOperations:n.length}}));return}let r=tc(n);if(e.output!==void 0){let n=rc(e.output,r);L({mode:t},_(`Unified operations JSON written`,{outputPath:n.target,byteLength:n.byteLength,schemaVersion:r.schemaVersion},{counts:{totalOperations:n.totalOperations}}));return}if(t===`text`){Ir(`Unified operations JSON`,nc(r));return}L({mode:t},_(`Unified operations JSON`,r,{counts:{totalOperations:r.totalOperations}}))})}var fc=b(Jt(import.meta.url)),Q=fc.bin[0];function pc(e,t){i({component:Q,event:`fatal`,message:e.message,error:e}),process.stderr.write(`${Q} fatal (${t}): ${e.stack??e.message}\n`);let n=e instanceof h?{httpStatus:e.problem.status,problem:e.problem}:{};cr({...g(`${Q} ${t}: ${e.message}`,[e.name||`Error`],n),counts:{exitCode:1}}),process.exit(1)}function mc(e){return Ue[ze(e,gt)??`cli`]}function hc(e,t){let n=t.map(e=>{let t=e.cliPath[0]??``;return{spec:e,top:t,rank:mc(t).rank}}).toSorted((e,t)=>e.rank-t.rank||e.top.localeCompare(t.top)).map(e=>e.spec),r=new Set(n.filter(e=>wt(e.cliPath[0])).map(e=>e.cliPath[0]??``)),i=new Set,a=new Set;for(let{cliPath:e,deprecated:t}of n)for(let n=1;n<e.length;n++){let r=e.slice(0,n).join(` `);i.add(r),t!==!0&&a.add(r)}for(let t of n)gc(e,t,r,a,i.has(t.cliPath.join(` `)))}function gc(e,t,n,r,i){let a=t.cliPath,o=e,s=``,c=!n.has(a[0]??``);for(let e of a.slice(0,-1)){s=s===``?e:`${s} ${e}`;let t=c&&s===e||!r.has(s);o=_c(o,e,s,t)}let l=a.at(-1)??t.operationId,u=o.commands.find(e=>e.name()===l)??o.command(l,t.deprecated===!0?{hidden:!0}:{}),d=t.requestBody?.flatMap(({parameter:e})=>e)??[];u.summary(t.summary||t.operationId).description([`${t.method} ${t.path}.`,t.summary||t.description,`Full documentation: ${Q} help ${t.cliPath.join(` `)}`,t.requestBody?.[0]?.kind===`json`||[...t.parameters,...d].some(e=>ye(e.schemaType,e.itemSchemaType))?xe:``].filter(Boolean).join(`
60
+ `));let f=Tt(t);for(let e of t.parameters)vc(u,e,i||e===f);if(Vn(u,t),_e(t.intent)&&u.option(`--execute`,`Deprecated; accepted and ignored. This command executes by its verb.`,!1),E(u),u.hook(`preAction`,e=>bt(e,t)),t.explain===!0&&u.option(`--explain`,`Print the search strategy and parsed constraints before the results`),f!==void 0){u.argument(`[text...]`,f.description||`Same as ${Ct(f.flag)}.`),u.action(async function(e){let n=this.optsWithGlobals(),r=T(n),i=vt(f,e,n);if(!i.ok||i.data===null)return L({mode:r},i);let a=_t(t,i.data);if(a.length>0)return L({mode:r},g(`missing required options: ${a.join(`, `)}`));let o=await yc(t,i.data,r),s=ii(t,i.data,o);if(s!==null)return L({mode:r},s);n.explain===!0&&o.ok&&fr(r,o.data),o.ok&&o.data instanceof Uint8Array?process.stdout.write(o.data):L({mode:r},o)});return}u.action(async function(){let e=this.optsWithGlobals(),n=T(e),r=_t(t,e);if(r.length>0)return L({mode:n},g(`missing required options: ${r.join(`, `)}`));let i=await yc(t,e,n),a=ii(t,e,i);if(a!==null)return L({mode:n},a);e.explain===!0&&i.ok&&fr(n,i.data),i.ok&&i.data instanceof Uint8Array?process.stdout.write(i.data):L({mode:n},i)})}function _c(e,t,n,r){let i=e.commands.find(e=>e.name()===t);if(i!==void 0)return i;let a=gt[n],o=e.command(t,r?{hidden:!0}:{}).helpCommand(!1);return a!==void 0&&o.summary(a.summary).description(a.summary),o}function vc(t,n,r=!1){let i=n.description||`${n.name} ${n.location} parameter`,a=n.defaultValue===void 0?void 0:typeof n.defaultValue==`string`||typeof n.defaultValue==`boolean`?n.defaultValue:[...n.defaultValue];if(n.legacyFlag!==void 0){let o=new e(n.flag,i);a!==void 0&&o.default(a);let s=new e(n.legacyFlag,i).conflicts(n.optionKey);t.addOption(o).addOption(s),t.hook(`preAction`,e=>{let t=e.opts(),i=t[n.optionKey],a=t[s.attributeName()];if(a!==void 0){(i===void 0||e.getOptionValueSource(n.optionKey)==="default")&&e.setOptionValueWithSource(n.optionKey,a,`cli`);return}!r&&n.required&&i===void 0&&e.error(`error: required option '${o.flags}' not specified`,{code:`commander.missingMandatoryOptionValue`})});return}if(a!==void 0){t.option(n.flag,i,a);return}if(n.required&&!r){t.requiredOption(n.flag,i);return}t.option(n.flag,i)}async function yc(e,t,n){if(t.environment!==void 0){let e=ue(t.environment);if(e===null)return g(`Unknown aVenture environment '${t.environment}'`,[`Use one of: ${ce().join(`, `)}`]);process.env.API_ENV=e}let r=await Kn(e,t);if(!r.ok)return r;let i=Object.fromEntries(e.parameters.filter(e=>e.location===`path`).map(e=>{let n=t[e.optionKey];if(Array.isArray(n))return[e.name,n.at(0)??``];if(n===void 0)throw Error(`Missing required option ${e.optionKey}`);return[e.name,String(n)]})),a=Object.fromEntries(e.parameters.filter(e=>e.location===`query`).flatMap(e=>{let n=t[e.optionKey];if(n===void 0||Array.isArray(n)&&n.length===0)return[];let r=Array.isArray(n)||typeof n==`boolean`?n:String(n);return[[e.name,r]]})),o=Object.fromEntries(e.parameters.filter(e=>e.location===`header`).flatMap(e=>{let n=t[e.optionKey];return n===void 0||Array.isArray(n)&&n.length===0?[]:[[e.name,Array.isArray(n)?n.join(`,`):String(n)]]}));return oi(e,await p({method:e.method,path:m(e.operationId,i),searchParams:a,headers:o,body:r.data,contentType:St(e,t),auth:e.auth,responseFormat:Dt(n)?`json`:`auto`,responseBytes:e.binaryResponse===!0}))}process.on(`uncaughtException`,e=>pc(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>pc(e instanceof Error?e:Error(String(e)),`unhandledRejection`));var bc=xt(process.argv.slice(2),w),xc=bc===`required`?w:yt(w),$=new r;$.name(Q).usage(`<command> [subcommand] [options]`).configureHelp(Yr).version(fc.version).summary(`CLI for the aVenture API: companies, people, and news, with the funding, publications, and classifications attached to them`).description([`The aVenture research API from your terminal. Three records — companies,`,`people, and news — carry everything else: funding, publications, and tags.
61
61
  `,`Mutations execute directly; --execute is a deprecated no-op.
62
62
  The aVenture MCP server tools execute through this same CLI.`].join(`
63
- `)).addOption(new e(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${le})`).choices([...ce()])).showHelpAfterError(`(run \`${Q} --help\` for usage)`),mc($,bc),jo($,Q),$a($,dc),Ko($,bc,Q),oc($,bc,Q),Wr($,bc,Q);for(let e of $.commands)e.helpGroup()||e.helpGroup(pc(e.name()).heading);if($s($),yc===`required`){let e=[$];for(;e.length>0;){let t=e.pop();t!==void 0&&(e.push(...t.commands),t.hook(`preAction`,async(e,t)=>{e===t&&(await dt(),await et())}))}}var xc=new Set($.commands.filter(e=>[`entities`,`people`,`news`].includes(e.name())).flatMap(e=>e.commands.map(e=>e.name())));$.addHelpText(`after`,[``,`Record subcommands under entities, people, and news:`,...[[`search`,` search Find many of that record from a plain-English query or a filter`],[`lookup`,` lookup Find one news article; companies and people use the root lookup`],[`get`,` get Read one record`],[`list`,` list Read many records`],[`create`,` create, update, delete Write; each needs a credential that permits it`]].flatMap(([e,t])=>xc.has(e)?[t]:[]),``,`Account (free or paid; every command that calls aVenture needs one):`,` Create one at ${se}/sign-up, then run: ${Q} auth login`,` AUTH_TOKEN aVenture API key, for CI and other non-interactive shells`,` Profile views, searches, and web searches count toward your monthly allowance.`,` Usage and upgrades: ${se}/settings/subscription`,` Plans and prices: ${Q} billing plans list`,` Check what this shell holds with: ${Q} auth status\n`,`Output modes (per command):`,` --text compact lines, the terminal default; --json the full envelope`,` --data response data as JSON, the default when piped or non-TTY`,` --data-full uncapped, for bounded programs, never LLM agents`,` --all-fields --text plus the detail fields it hides by default
63
+ `)).addOption(new e(`--environment <environment>`,`route all API calls to a mapped API environment (default: API_URL host, else API_ENV, else ${le})`).choices([...ce()])).showHelpAfterError(`(run \`${Q} --help\` for usage)`),hc($,xc),Mo($,Q),eo($,fc),qo($,xc,Q),sc($,xc,Q),Gr($,xc,Q);for(let e of $.commands)e.helpGroup()||e.helpGroup(mc(e.name()).heading);if(ec($),bc===`required`){let e=[$];for(;e.length>0;){let t=e.pop();t!==void 0&&(e.push(...t.commands),t.hook(`preAction`,async(e,t)=>{e===t&&(await dt(),await et())}))}}var Sc=new Set($.commands.filter(e=>[`entities`,`people`,`news`].includes(e.name())).flatMap(e=>e.commands.map(e=>e.name())));$.addHelpText(`after`,[``,`Record subcommands under entities, people, and news:`,...[[`search`,` search Find many of that record from a plain-English query or a filter`],[`lookup`,` lookup Find one news article; companies and people use the root lookup`],[`get`,` get Read one record`],[`list`,` list Read many records`],[`create`,` create, update, delete Write; each needs a credential that permits it`]].flatMap(([e,t])=>Sc.has(e)?[t]:[]),``,`Account (free or paid; every command that calls aVenture needs one):`,` Create one at ${se}/sign-up, then run: ${Q} auth login`,` AUTH_TOKEN aVenture API key, for CI and other non-interactive shells`,` Profile views, searches, and web searches count toward your monthly allowance.`,` Usage and upgrades: ${se}/settings/subscription`,` Plans and prices: ${Q} billing plans list`,` Check what this shell holds with: ${Q} auth status\n`,`Output modes (per command):`,` --text compact lines, the terminal default; --json the full envelope`,` --data response data as JSON, the default when piped or non-TTY`,` --data-full uncapped, for bounded programs, never LLM agents`,` --all-fields --text plus the detail fields it hides by default
64
64
  `,`Exit codes:`,` 0 envelope.ok === true
65
65
  1 envelope.ok === false
66
66
  `,`Examples:`,` $ ${Q} auth login`,` $ ${Q} lookup --name Stripe --url https://stripe.com`,` $ ${Q} search "fintech companies in Austin"\n`,`Run \`${Q} <command> --help\` for its subcommands and options,`,`or \`${Q} help <command>\` for its full documentation.`].join(`
67
- `));try{await $.parseAsync()}catch(e){fc(e instanceof Error?e:Error(String(e)),`parseAsync`)}export{};
67
+ `));try{await $.parseAsync()}catch(e){pc(e instanceof Error?e:Error(String(e)),`parseAsync`)}export{};