infra-kit 0.16.0 → 0.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-NJEEEHUY.js → chunk-5NW4ZWKT.js} +2 -2
- package/dist/chunk-MYUZOXKA.js +7 -0
- package/dist/chunk-MYUZOXKA.js.map +7 -0
- package/dist/{chunk-GIMZ4GTZ.js → chunk-QSIWRM6A.js} +2 -2
- package/dist/{chunk-OPYDLPHB.js → chunk-SK3GYE2K.js} +2 -2
- package/dist/{chunk-OPYDLPHB.js.map → chunk-SK3GYE2K.js.map} +1 -1
- package/dist/{chunk-4GXRGHU3.js → chunk-X33OD35Q.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/dev-server.js +2 -2
- package/dist/{dev-wizard-run-OXBPE3BF.js → dev-wizard-run-4XJYZTCO.js} +2 -2
- package/dist/{env-load-74P4WMXV.js → env-load-L3FLJR4O.js} +2 -2
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/dist/chunk-R6MPHCEI.js +0 -7
- package/dist/chunk-R6MPHCEI.js.map +0 -7
- /package/dist/{chunk-NJEEEHUY.js.map → chunk-5NW4ZWKT.js.map} +0 -0
- /package/dist/{chunk-GIMZ4GTZ.js.map → chunk-QSIWRM6A.js.map} +0 -0
- /package/dist/{chunk-4GXRGHU3.js.map → chunk-X33OD35Q.js.map} +0 -0
- /package/dist/{dev-wizard-run-OXBPE3BF.js.map → dev-wizard-run-4XJYZTCO.js.map} +0 -0
- /package/dist/{env-load-74P4WMXV.js.map → env-load-L3FLJR4O.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{l as F}from"./chunk-Y3RW74TE.js";import{P as f,l as G,r as $}from"./chunk-
|
|
1
|
+
import{l as F}from"./chunk-Y3RW74TE.js";import{P as f,l as G,r as $}from"./chunk-X33OD35Q.js";import{execFile as oe,execFileSync as ne}from"node:child_process";import b from"node:process";var ae=5e3,se=100,W=2e3,J="/bin/ps",ie=1e3,B=["-eo","pid=,ppid=,pgid=,lstart="],V=8<<20,j=e=>e.split(`
|
|
2
2
|
`).flatMap(r=>{let[t,o,n,...a]=r.trim().split(/\s+/);if(t==null||o==null||n==null)return[];let c=Number(t),s=Number(o),l=Number(n);return!Number.isInteger(c)||!Number.isInteger(s)||!Number.isInteger(l)?[]:[{pid:c,ppid:s,pgid:l,lstart:a.join(" ")}]}),H=e=>{let r=new Map;for(let t of e)t.pid===t.pgid&&r.set(t.pgid,t.lstart);return r},ce=(e,r,t)=>{let o=H(r);return q(e,r,t).flatMap(n=>{let a=o.get(n);return a==null||a===""?[]:[{pgid:n,leaderStart:a}]})},K=(e,r)=>{let t=H(r);return e.flatMap(({pgid:o,leaderStart:n})=>t.get(o)===n?[o]:[])},U=(e,r)=>K(e,r).flatMap(t=>{try{b.kill(-t,"SIGKILL")}catch{return[]}return[t]}),q=(e,r,t)=>{let o=new Map;for(let s of r){let l=o.get(s.ppid);l?l.push(s):o.set(s.ppid,[s])}let n=new Set([e]),a=new Set([e]),c=[e];for(let s=0;s<c.length;s+=1)for(let l of o.get(c[s]??-1)??[])a.has(l.pid)||(a.add(l.pid),n.add(l.pgid),c.push(l.pid));return[...n].filter(s=>s>1&&s!==t)},L=()=>{try{return j(ne(J,[...B],{encoding:"utf8",maxBuffer:V}))}catch{return[]}},le=async()=>new Promise(e=>{oe(J,[...B],{encoding:"utf8",maxBuffer:V},(r,t)=>{e(r?[]:j(t))})}),ue=(e,r,t)=>t.some(o=>o.pid===e&&o.ppid===r),A=(e,r)=>{let t=r.find(o=>o.pid===b.pid)?.pgid;return q(e,r,t)},z=e=>{try{return b.kill(-e,0),!0}catch{return!1}},C=(e,r)=>{for(let t of e)try{b.kill(-t,r)}catch{}},P=new Set,pe=(e,r,t)=>{let o=A(e,r),n=t.flatMap(a=>K(a,r));return[...new Set([...o,...n])]},X=()=>{let e=L(),r=[...P].map(t=>t());C(pe(b.pid,e,r),"SIGKILL")},de=async e=>new Promise(r=>{setTimeout(r,e)}),_=async(e,r)=>{let t=Date.now()+r,o=e;for(;o.length>0&&Date.now()<t&&(o=o.filter(z),o.length!==0);)await de(se);return o};function cr(e,r=ae,t,o=L){e.unref();let n=!1,a=!1,c=[],s=null,l=()=>c;P.add(l);let m=()=>{s&&clearInterval(s),s=null},w=async()=>{await _(c.map(i=>i.pgid),W),P.delete(l)},y=i=>{let u=e.pid;if(u==null||a||n||i.length===0)return;let T=i.find(v=>v.pid===b.pid)?.pgid,S=ce(u,i,T);S.length>0&&(c=S)},h=async()=>{e.pid==null||a||n||y(await le())};y(L()),s=setInterval(()=>{h()},ie),s.unref();let R=i=>{n||t?.(i)};return e.on("exit",(i,u)=>{a=!0,m(),n||(U(c,o()),w()),R(`exited unexpectedly (code=${i??"null"}, signal=${u??"null"})`)}),e.on("error",i=>{R(`failed to spawn: ${i.message}`)}),{kill:async()=>{n=!0,m();let i=e.pid;if(i==null){P.delete(l);return}if(e.exitCode!==null||e.signalCode!==null){U(c,o()),await w();return}let u=o();if(u.length>0&&!ue(i,b.pid,u))return;let T=A(i,u);C(T,"SIGTERM");let S=await _(T,r);if(S.length===0){P.delete(l);return}let v=A(i,o()),D=[...new Set([...S,...v])].filter(z);C(D,"SIGKILL"),await _(D,W),P.delete(l)}}}import{constants as me}from"node:os";import k from"node:process";var fe=["SIGINT","SIGTERM","SIGHUP"],ge=me.signals,Oe=2,N=e=>128+(ge[e]??Oe),be=2e4,we=e=>{k.exit(e)},ye=(e,r)=>{k.on(e,r)},he=(e,r)=>{k.off(e,r)},Pe=(e,r)=>{let t=setTimeout(e,r);return t.unref(),()=>{clearTimeout(t)}},I=e=>{try{k.stderr.write(e)}catch{}},xe=(e,r)=>{let t=r instanceof Error?`${r.message}
|
|
3
3
|
${r.stack??"(no stack)"}`:String(r);I(`
|
|
4
4
|
\u2717 Teardown failed while handling ${e}: ${t}
|
|
@@ -7,4 +7,4 @@ ${r.stack??"(no stack)"}`:String(r);I(`
|
|
|
7
7
|
`),w?.(),n(),h(),r(N(i));return}m=i,w=c(()=>{let u=`
|
|
8
8
|
\u26A0 Teardown deadline exceeded at stage=${s()} after ${a}ms \u2014 force-quitting.
|
|
9
9
|
`;I(u),l(u),n(),h(),r(N(i))},a),(async()=>{try{await e(i)}catch(u){xe(i,u)}finally{w?.(),h(),r(N(i))}})()};for(let i of fe){let u=()=>R(i);y.set(i,u),t(i,u)}return h};var Se=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),Y=e=>e instanceof Error&&Se.has(e.name),gr=e=>{if(Y(e))return!0;let r=e?.cause;return Y(r)};import{loadDev as Re}from"@slip-stream-kit/config/internal";import Te from"node:path";var ke=(e,r)=>{let t=new Set;for(let o of Object.values(e))for(let n of Object.keys(F(o,r).proxy))t.add(n);return[...t]},Ee=async(e,r)=>{let t={},o=[];return await Promise.all(r.map(async n=>{try{let c=(await Re(Te.join(e,"apps",n,"ui")))?.proxy?.routes;if(!c)return;t[n]=Object.fromEntries(Object.entries(c).map(([s,l])=>[s,l.packageName]))}catch(a){o.push({app:n,message:a instanceof Error?a.message:String(a)})}})),{routePkg:(n,a)=>t[n]?.[a],loadErrors:o}},hr=async(e,r,t,o)=>{let{routePkg:n,loadErrors:a}=await Ee(e,ke(r,t));return{ctx:{discovered:t,apiPkgByApp:Object.fromEntries(o.map(c=>[c.name,c.packageName])),routePkg:n},loadErrors:a}};import{$ as ve}from"zx";var d=class extends Error{code;data;constructor(r){super(r.message),this.name="OrcaError",this.code=r.code,this.data=r.data}},x=class extends Error{exitCode;stderrTail;constructor(r,t){super(`orca: stdout is not a JSON envelope (exit ${r??"signal"})`),this.name="OrcaMalformedError",this.exitCode=r,this.stderrTail=t}},g=class extends Error{constructor(){super("orca: command not found \u2014 the CLI is registered from Orca \u2192 Settings \u2192 Experimental \u2192 CLI"),this.name="OrcaAbsentError"}},_e=400,Le=127,Ae=e=>typeof e=="object"&&e!==null&&e.code==="ENOENT",Ce=async e=>{try{return await ve({nothrow:!0,quiet:!0})`orca ${e} --json`}catch(r){throw Ae(r)?new g:r}},Ne=e=>{try{let r=JSON.parse(e);return typeof r=="object"&&r!==null&&typeof r.ok=="boolean"?r:null}catch{return null}},p=async e=>{let r=await Ce(e),t=Ne(r.stdout);if(f.debug({argv:e,ok:t?.ok,code:t?.error?.code,exitCode:r.exitCode},"orca"),!t)throw r.exitCode===Le?new g:new x(r.exitCode,r.stderr.slice(-_e));if(!t.ok)throw new d(t.error??{code:"unknown",message:"orca: ok:false without an error payload"});return t.result};var Ie=async()=>{try{let e=await p(["status"]);return f.debug({appVersion:e.runtime?.appVersion},"orca: status"),e.app?.running===!0&&e.runtime?.reachable===!0?"ready":"unreachable"}catch(e){return e instanceof g?"absent":(f.debug({error:e},"orca: status probe failed"),"unreachable")}};import{realpath as Me}from"node:fs/promises";var O=async e=>{try{return await Me(e)}catch{return e}};var De=async e=>{let[{repos:r=[]},t]=await Promise.all([p(["repo","list"]),O(e)]);for(let o of r)if(await O(o.path)===t)return{registered:!0,visibility:o.externalWorktreeVisibility};return{registered:!1}},Ge=async e=>{let{repo:r}=await p(["repo","add","--path",e]);return{visibility:r?.externalWorktreeVisibility}};var $e="500",Fe=async(e,r)=>{let[{worktrees:t=[]},o]=await Promise.all([p(["worktree","list","--repo",`path:${e}`,"--limit",$e]),O(r)]);for(let n of t)if(await O(n.path)===o)return!0;return!1};import We from"node:process";var Q="::",Ue=e=>{let r=e.ORCA_WORKTREE_ID;if(!r)return null;let t=r.indexOf(Q);if(t<0)return null;let o=r.slice(t+Q.length);return o.length>0?o:null},Je=async(e,r=We.env)=>{let t=Ue(r);if(t===null)return null;let o=await O(t);for(let n of e)if(await O(n)===o)return n;return null};var Z="200",M=async e=>{try{let r=await p(["terminal","list","--worktree",`path:${e}`,"--limit",Z]),t=r.truncated===!0;return t&&f.debug({cwd:e,limit:Z},"orca: terminal list truncated"),{terminals:r.terminals??[],truncated:t}}catch(r){if(r instanceof d&&r.code==="selector_not_found")return{terminals:[],truncated:!1};throw r}};var Be=async e=>{try{return await p(["terminal","close","--worktree",`path:${e}`,"--all"]),"retired"}catch(r){if(r instanceof d&&r.code==="selector_not_found")return"not_found";if(r instanceof d&&r.code==="terminal_close_incomplete")return f.debug({cwd:e,error:r},"orca: surfaces not retired"),"retired";throw r}},Ve=async e=>{let{terminals:r}=await M(e);for(let o of r)await p(["terminal","close","--terminal",o.handle]);let t=await Be(e);return r.length===0&&t==="not_found"?{closed:!1,skipped:"not_found"}:{closed:!0,count:r.length}},je=(e,r)=>r instanceof g?{closed:!1,skipped:"absent"}:r instanceof d?{closed:!1,error:r}:r instanceof x?{closed:!1,error:new d({code:"orca_malformed_output",message:r.message,data:{exitCode:r.exitCode,stderrTail:r.stderrTail}})}:(f.debug({cwd:e,error:r},"orca: close failed outside the Orca contract"),{closed:!1,error:new d({code:"orca_close_failed",message:r instanceof Error?r.message:String(r)})}),He=async(e,r)=>{if(r!=="ready")return{closed:!1,skipped:r};try{return await Ve(e)}catch(t){return je(e,t)}};import{setTimeout as Ke}from"node:timers/promises";var qe=3,ze=300,re=(e={})=>({attempts:e.attempts??qe,delayMs:e.delayMs??ze,exhausted:!1}),Xe=async e=>{try{return{created:await p(e)}}catch(r){if(r instanceof d&&r.code==="selector_not_found")return{notSelectable:r};throw r}},Ye=async(e,r,t)=>{let o=t.exhausted?1:t.attempts,n=Array.from({length:o},(c,s)=>s+1),a;for(let c of n){let s=await Xe(e);if("created"in s)return s.created.terminal.handle;a=s.notSelectable,c<o&&await Ke(t.delayMs)}throw t.exhausted=!0,new d({code:"orca_worktree_not_selectable",message:`orca: worktree ${r} is not selectable after ${o} attempt(s): ${a?.message??""}`,data:{cwd:r,attempts:o,cause:a?.data}})},ee=async(e,r)=>(await p(["terminal","split","--terminal",e,"--direction",r])).split.handle,Qe=async e=>{let{cwd:r,title:t,focus:o,layout:n,panes:a,poll:c=re()}=e,s=["terminal","create","--worktree",`path:${r}`,"--title",t,...o?["--focus"]:[]],l=await Ye(s,r,c),m=[l];return n==="full"&&(m.push(await ee(l,"horizontal")),a==="three-pane"&&m.push(await ee(l,"vertical"))),{handles:m,layout:n}};var Ze=e=>{let{branch:r}=e,t=G(r);return t?$(t):r};var it=e=>typeof e=="object",E=async e=>(await e.body?.cancel(),{kind:"foreign",status:e.status,contentType:e.headers.get("content-type")}),ct=(e,r)=>{let t=r.contentType?.split(";")[0]?.trim(),o=t==null||t===""?`${r.status}`:`${r.status} ${t}`;return`port ${e} answered ${o}, not vite's ping \u2014 liveness cannot be verified`};var te={accept:"text/x-vite-ping"},er=e=>e.kind==="api"?`http://127.0.0.1:${e.port}/__health`:`http://127.0.0.1:${e.port}/`,rr=(e,r)=>{try{return new URL(e,r)}catch{return null}},tr=async(e,r)=>{let t=await fetch(e,{signal:r});return t.ok?(await t.body?.cancel(),"ok"):E(t)},or=async(e,r)=>{let t=await fetch(e,{headers:te,redirect:"manual",signal:r});if(t.status===204)return"ok";if(t.status<300||t.status>=400)return E(t);let o=t.headers.get("location"),n=o==null?null:rr(o,e);if(n==null||n.origin!==new URL(e).origin)return E(t);await t.body?.cancel();let a=await fetch(n,{headers:te,redirect:"manual",signal:r});return a.status!==204?E(a):(await a.body?.cancel(),"ok")},lt=async e=>{let r=er(e),t=AbortSignal.timeout(1500);try{return e.kind==="api"?await tr(r,t):await or(r,t)}catch{return"refused"}};import{readRelease as nr}from"@slip-stream-kit/config/internal";var ar=e=>nr(e);export{hr as a,X as b,cr as c,N as d,mr as e,d as f,p as g,Ie as h,Je as i,M as j,He as k,De as l,Ge as m,Fe as n,re as o,Qe as p,Ze as q,it as r,ct as s,lt as t,ar as u,gr as v};
|
|
10
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
//# sourceMappingURL=chunk-5NW4ZWKT.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{P as p,S as w,ca as C,d as f,f as u,ga as g}from"./chunk-X33OD35Q.js";import{p as b}from"./chunk-I23MDR4X.js";import{a as A,b as D}from"./chunk-QWVLAZ6N.js";var H=()=>{let e="",t=[],r=!1;return{start(n){e=n,t=[],r=!1},setInteractive(){r=!0},addOption(n,o){t.push({flag:n,value:o})},formatOptions(){return t.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} "${n.value}"`).filter(Boolean).join(" ")},snapshot(){return t.length===0?null:{formattedOptions:this.formatOptions()}},print(){!r||t.length===0||!e||p.info(`\u{1F4DF} Equivalent command:
|
|
2
|
+
pnpm exec infra-kit ${e} ${this.formatOptions()}
|
|
3
|
+
`)},reset(){e="",t=[],r=!1}}},x=H();import{isAbsolute as $,resolve as I}from"node:path";import M from"node:process";var E=null,y=null,K=e=>{E=[...e],y=M.cwd()},q=new Set(["--yes","-y"]),B=(e,t)=>{let r=[...e];for(let[n,o]of r.entries())o==="-C"&&r[n+1]!==void 0&&!$(r[n+1])?r[n+1]=I(t,r[n+1]):o.startsWith("-C")&&o.length>2&&!o.startsWith("--")&&!$(o.slice(2))&&(r[n]=`-C${I(t,o.slice(2))}`);return r},T=()=>{if(E===null||y===null)return["--yes"];let e=E.slice(2),t=e.indexOf("--"),r=t===-1?e.length:t,n=B(e.slice(0,r),y),o=e.slice(r);return n.some(i=>q.has(i))?[...n,...o]:[...n,"--yes",...o]};import _ from"node:process";var J=27,L=e=>e===null?"an interactive prompt was reached under --json, which never prompts":`an interactive prompt was reached in agent mode (${e==="flag"?"--agent":"INFRA_KIT_AGENT / CLAUDECODE"}), where there is no human to answer it`,W=e=>`${e===void 0?"pass the value explicitly instead of relying on the prompt":`pass --${e}`} on the re-run`,z=e=>{if(typeof e=="object"&&"value"in e)return e.value;let t=typeof e=="object"?e.refuse:void 0,{source:r}=f;throw new g(t===void 0?{status:"refused",agentMode:r}:{status:"argument_required",argument:t,agentMode:r},2,{operation:"interactive prompt",remediation:W(t),stderrExcerpt:L(r)})},j=async(e,t)=>{let r=new AbortController,{whenHeadless:n="refuse",...o}=t??{},s={...o,signal:r.signal};if(u())return z(n);if(!_.stdin.isTTY)return e(s);let i=_.stdin,P=d=>{d.length===1&&d[0]===J&&r.abort()};A();try{let d=e(s);return i.isPaused()&&i.resume(),i.on("data",P),await d}finally{i.removeListener("data",P),D()}};import U from"@inquirer/confirm";import Y from"node:process";var c=class extends Error{constructor(t="Operation cancelled by the operator"){super(t),this.name="CommandDeclinedError"}},fe=e=>e instanceof c;var N=(e,t,r=T())=>{let{source:n}=f;throw new g({status:"confirmation_required",message:e,plan:t,rerun:r,agentMode:n},2,{operation:"confirm before running",remediation:n===null?"pass `--yes` to confirm, or drop `--json` to be prompted":`show the plan to the human, then re-run \`infra-kit ${r.join(" ")}\` to confirm`,stderrExcerpt:"confirmation required and nobody to ask"})},G=async(e,t,r={})=>{!e&&u()&&N(t,r.plan,r.rerun);let n=e?!0:await j(o=>U({message:t},o),{whenHeadless:"refuse"});if(e||x.setInteractive(),!n){if(r.throwOnDecline)throw new c;p.info("Operation cancelled. Exiting..."),Y.exit(0)}};import h from"node:fs/promises";import m from"node:path";import{z as a}from"zod";var l=class extends Error{env;constructor(t,r=null){super(t),this.name="EnvAuthError",this.env=r}};var V="tokens.json",v=1,R=384,F=448,Q=a.object({version:a.literal(v).default(v),envs:a.record(a.string().min(1),a.string().min(1))}).strict(),k=async()=>{let e=await C();return m.join(m.dirname(e.userProject),V)},S=async()=>{let e=await k(),t;try{t=await h.readFile(e,"utf-8")}catch{return null}let r;try{r=JSON.parse(t)}catch(o){throw new l(`Invalid JSON in the token store at ${w(e)}: ${o.message}
|
|
4
|
+
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let n=Q.safeParse(r);if(!n.success)throw new l(`Invalid token store at ${w(e)}: ${a.prettifyError(n.error)}
|
|
5
|
+
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return n.data},O=async e=>{let t=await k(),r=m.dirname(t),n=m.dirname(r),o=m.dirname(n);for(let s of[o,n,r])await h.mkdir(s,{recursive:!0,mode:F}),await h.chmod(s,F);b(t,`${JSON.stringify(e,null,2)}
|
|
6
|
+
`,R),await h.chmod(t,R)};var X=async e=>{let t=await S();await O({version:v,envs:{...t?.envs,...e}})},Z=async e=>{let t=await S();if(!t||!(e in t.envs))return;let r={...t.envs};delete r[e],await O({version:v,envs:r})};export{x as a,fe as b,K as c,T as d,j as e,N as f,G as g,l as h,k as i,S as j,X as k,Z as l};
|
|
7
|
+
//# sourceMappingURL=chunk-MYUZOXKA.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/command-echo/command-echo.ts", "../src/lib/parsed-argv/parsed-argv.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/command-echo/confirm-or-exit.ts", "../src/lib/errors/command-declined-error.ts", "../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts"],
|
|
4
|
+
"sourcesContent": ["import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the handler was called off the CLI (a test, an in-process caller), where a\n * `pnpm exec` line would be nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be\n * worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import { isAbsolute, resolve } from 'node:path'\nimport process from 'node:process'\n\n/**\n * The argv Commander actually parsed for this run \u2014 captured by `entry/cli.ts` at the one place it\n * hands an argv to `parseAsync`, the interactive-menu re-entry included. Commands that need to name\n * their own invocation (a `confirmation_required` refusal's `rerun`) read it here instead of\n * `process.argv`, which the menu path never rewrites.\n */\n\nlet parsedArgv: readonly string[] | null = null\nlet launchCwd: string | null = null\n\n/**\n * Record the full node-style argv (`[node, script, ...args]`) handed to `parseAsync`, and the cwd it\n * was typed in \u2014 read NOW because the `-C` chdir in `preAction` runs later, and a relative `-C` only\n * means anything against this directory.\n */\nexport const setParsedArgv = (argv: readonly string[]): void => {\n parsedArgv = [...argv]\n launchCwd = process.cwd()\n}\n\nconst YES_FLAGS = new Set(['--yes', '-y'])\n\n/**\n * Make every `-C <dir>` in `args` absolute against `cwd`, in place. Commander accepts both\n * `-C dir` and `-Cdir`; both are handled so the re-run is cwd-independent whichever way it was typed.\n */\nconst absolutizeChangeDir = (args: string[], cwd: string): string[] => {\n const out = [...args]\n\n for (const [index, token] of out.entries()) {\n if (token === '-C' && out[index + 1] !== undefined && !isAbsolute(out[index + 1] as string)) {\n out[index + 1] = resolve(cwd, out[index + 1] as string)\n } else if (token.startsWith('-C') && token.length > 2 && !token.startsWith('--') && !isAbsolute(token.slice(2))) {\n out[index] = `-C${resolve(cwd, token.slice(2))}`\n }\n }\n\n return out\n}\n\n/**\n * The argv an agent re-runs to confirm what this run refused: the captured user args with `--yes`\n * appended and any relative `-C` made absolute, so the next Bash call may run from any cwd.\n *\n * `--yes` goes before the first `--`: `e2e` hands everything after it to Playwright, so a `--yes`\n * there never reaches Commander and the confirm fires again. The only variadic option\n * (`--project <names...>`) stops at `--yes`. An argv whose options already carry `--yes`/`-y` is\n * returned as-is \u2014 a second copy would be noise, and a confirm that fired despite it is not this\n * function's problem to hide.\n *\n * @example\n * // captured: ['node', 'infra-kit', '-C', 'app', 'release', 'remove', '1.2.3', '--json'], cwd /w\n * rerunArgv() // ['-C', '/w/app', 'release', 'remove', '1.2.3', '--json', '--yes']\n */\nexport const rerunArgv = (): string[] => {\n if (parsedArgv === null || launchCwd === null) return ['--yes']\n\n const userArgs = parsedArgv.slice(2)\n const separator = userArgs.indexOf('--')\n const optionsEnd = separator === -1 ? userArgs.length : separator\n const options = absolutizeChangeDir(userArgs.slice(0, optionsEnd), launchCwd)\n const passThrough = userArgs.slice(optionsEnd)\n\n const alreadyConfirmed = options.some((token) => {\n return YES_FLAGS.has(token)\n })\n\n return alreadyConfirmed ? [...options, ...passThrough] : [...options, '--yes', ...passThrough]\n}\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport type { AgentModeSource } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\n/**\n * What this call site does when there is no human: refuse, refuse NAMING the argument that would have\n * answered the prompt, or answer with a fixed value.\n *\n * - `'refuse'` \u2014 throw `{ status: 'refused' }`: the site has no single argument to name.\n * - `{ refuse: 'version' }` \u2014 throw `{ status: 'argument_required', argument: 'version' }`: the\n * agent is told exactly what to pass on the re-run. The name is the CLI flag / tool field without\n * its dashes; G8 (`headless-policy-guards`) checks it exists on every owning tool's schema.\n * - `{ value: T }` \u2014 answer with `value`, no throw.\n *\n * There is no `'unreachable'` any more: that was a claim about the retired server's schema making a\n * field required, and no schema stands between a Bash-driven agent and this prompt.\n */\nexport type HeadlessPolicy<T> = 'refuse' | { refuse: string } | { value: T }\n\n/** {@link withEscape}'s options: the prompt context, plus this site's headless policy. */\nexport type EscapeOptions<T> = PromptContext & { whenHeadless?: HeadlessPolicy<T> }\n\nconst ESC_BYTE = 0x1b\n\n// Widening the existing options object rather than adding a third parameter: six call sites already\n// pass a `PromptContext` (`entry/cli.ts`, `env-load`, `env-token-set`, and the wizard's shared\n// context used by three prompts), all of them `{ output: process.stderr }` for documented reasons \u2014\n// `env-token-set.ts:64-68` notes that some env commands run inside `$(\u2026)`, where a prompt on stdout\n// would leave the user typing a credential into a captured stream. A third parameter would have\n// forced every one of them to grow a positional `undefined`.\n//\n// Optional, and the default is `'refuse'`. That default is safe for the same reason the guard exists\n// at all: under `isAgentMode()` nobody is at the keyboard, so no prompt at any site can return a\n// usable answer, and refusing removes no\n// capability that exists. It is what CLI-only sites (the palette, the dev wizard, `env-token-set`)\n// keep, because they face a real human.\n//\n// It is NOT what an agent-reachable site may keep. There, omitting `whenHeadless` is indistinguishable\n// from never having considered the question, so G7 (`every-inquirer-site-is-escapable`) requires the\n// answer to be written out \u2014 `'refuse'` included.\n//\n// What the default is NOT is *correct* everywhere \u2014 that distinction is the whole point of the\n// parameter. `worktrees-add` documents a `false` fallback for agents in its own schema, so a refusal\n// there is right-outcome-by-accident at best and a regression at worst. The type cannot tell those\n// apart; G6 (description-to-policy) and G8 (argument-to-schema) are what check the answers,\n// because a wrong answer here compiles and can never fail a test on its own.\nconst headlessExcerpt = (source: AgentModeSource): string => {\n if (source === null) return 'an interactive prompt was reached under --json, which never prompts'\n\n return `an interactive prompt was reached in agent mode (${source === 'flag' ? '--agent' : 'INFRA_KIT_AGENT / CLAUDECODE'}), where there is no human to answer it`\n}\n\nconst headlessRemediation = (argument: string | undefined): string => {\n const passIt =\n argument === undefined ? 'pass the value explicitly instead of relying on the prompt' : `pass --${argument}`\n\n return `${passIt} on the re-run`\n}\n\nconst resolveHeadless = <T>(policy: HeadlessPolicy<T>): T => {\n if (typeof policy === 'object' && 'value' in policy) return policy.value\n\n const argument = typeof policy === 'object' ? policy.refuse : undefined\n const { source } = agentMode\n\n throw new StructuredRefusalError(\n argument === undefined\n ? { status: 'refused', agentMode: source }\n : { status: 'argument_required', argument, agentMode: source },\n 2,\n {\n operation: 'interactive prompt',\n remediation: headlessRemediation(argument),\n stderrExcerpt: headlessExcerpt(source),\n },\n )\n}\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation. On Esc the prompt rejects with an\n * `AbortPromptError`, which `entry/cli.ts` already catches at the top level -> \"Operation\n * cancelled.\" -> exit 0.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a sufficient\n * guard \u2014 see lib/agent-mode for why `stdio: 'inherit'` defeats it.\n */\n// The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal goes into the\n// prompt context, `@inquirer/core` rejects with an `AbortPromptError` when it fires, and that name\n// is already in `CANCELLATION_ERROR_NAMES` (lib/errors/is-prompt-cancellation). All this adds is\n// the thing that calls `abort()`.\n//\n// DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b` byte.\n// Deliberately NOT readline `keypress`: that delivers a lone Esc only after its escape-sequence\n// timeout (~523ms measured), and the `escapeCodeTimeout` dial that would shorten it is\n// process-global and first-armer-wins \u2014 a second `emitKeypressEvents` call on `process.stdin` is\n// SILENTLY IGNORED, so the dial degrades to a no-op with no error and no failing test. The raw\n// listener costs ~24ms and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n// (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is involved. Node\n// `data` listeners broadcast, so this one does not steal bytes from readline: arrows and Enter keep\n// working while it is attached.\n//\n// FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk. Focus events\n// (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports (`\\x1b[M\u2026`) are all\n// multi-byte, and inquirer enables none of them.\n//\n// FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE chunk, i.e.\n// Esc immediately followed by another key) is silently dropped and the prompt stays open. The fix\n// would be Ink's 20ms deferred abort \u2014 hold the lone Esc, cancel it if a follow-up chunk lands.\n// That is a logged NON-GOAL; do not pre-build it.\nexport const withEscape = async <T>(\n run: (context: PromptContext) => Promise<T>,\n base?: EscapeOptions<T>,\n): Promise<T> => {\n const controller = new AbortController()\n // `whenHeadless` is ours, not inquirer's \u2014 split it off so it never reaches a prompt's context.\n const { whenHeadless = 'refuse', ...promptBase } = base ?? {}\n const context: PromptContext = { ...promptBase, signal: controller.signal }\n\n // Keyed on `isHeadless()`. `!isTTY` deliberately does NOT ride along: a piped-but-human\n // run (`infra-kit worktrees add > log.txt`) has no TTY and still deserves its prompt, and the two\n // conditions were only ever collapsed here because both merely skipped the Esc listener. Now that\n // this branch decides an ANSWER rather than just a listener, conflating them would refuse prompts\n // no agent is waiting on. `release-picker.ts` keeps its own `!isTTY` clause for its own reason.\n //\n // `--json` joins because a prompt is stdout traffic on a stream a machine is parsing, and because\n // `release-picker`/`source-picker` already treat `--json` as never-prompt \u2014 this makes the 20 sites\n // agree with those two.\n if (isHeadless()) return resolveHeadless(whenHeadless)\n\n if (!process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "/**\n * @fileoverview\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (`--yes`, the argv a `confirmation_required`\n * refusal hands back) the prompt is skipped and execution proceeds. Otherwise, with no human to ask \u2014 agent mode, or `--json`, whose\n * stdout a machine is parsing \u2014 it throws a `confirmation_required` refusal\n * carrying the argv that confirms (preview-then-execute, no new flag). Otherwise\n * it prompts the user, marks the echo as interactive, and exits cleanly if the\n * user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path: headless\n * callers refuse above it, so a `--json` document is never cut short by it.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nimport confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { CommandDeclinedError } from 'src/lib/errors/command-declined-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport { rerunArgv } from 'src/lib/parsed-argv'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\nexport interface ConfirmOrExitOptions {\n /**\n * The structured form of what `message` renders, handed back verbatim in the\n * `confirmation_required` payload so an agent can show the human WHAT it is\n * about to confirm without parsing prose. JSON-safe and secret-free \u2014 it is\n * emitted to stdout. Sites with no structured plan pass nothing.\n */\n plan?: unknown\n /**\n * Throw {@link CommandDeclinedError} on a decline instead of `process.exit(0)`.\n *\n * **Defaults to false, and must stay that way.** Seven commands call this\n * helper; flipping the default would change the exit semantics of all of them\n * at once, inside a change whose tests cover none of them.\n *\n * Opt in when the command has already acquired something that needs releasing\n * by the time it prompts \u2014 `process.exit` skips every `finally`, so for those\n * commands the decline path is precisely where a resource leaks. The caller\n * owns catching it and exiting 0: a decline is a successful outcome.\n */\n throwOnDecline?: boolean\n /**\n * The argv that confirms, when it must carry more than this run's own argv plus `--yes` \u2014 e.g.\n * the content hash the human is approving. Defaults to `rerunArgv()`.\n */\n rerun?: string[]\n}\n\n/**\n * Throw the `confirmation_required` refusal an agent (or a `--json` run) gets in place of a confirm\n * prompt: the message, the site's plan, the argv that confirms, and the source. Exit 2 \u2014 nothing ran.\n *\n * Exported for the one confirm site that is not `confirmOrExit` (`lib/release-deploy/confirm-deploy`),\n * so both speak the same shape.\n */\n// Thrown from HERE, not from `withEscape`'s headless branch, because it needs what only a confirm\n// site has: the message, the plan, and the knowledge that `--yes` is the answer. Callers key it on\n// `isHeadless()`, never on `confirmedCommand`, so their `--yes` short-circuit stays as it was for\n// agent and human alike.\nexport const refuseUnconfirmed = (message: string, plan?: unknown, rerun: string[] = rerunArgv()): never => {\n const { source } = agentMode\n\n throw new StructuredRefusalError({ status: 'confirmation_required', message, plan, rerun, agentMode: source }, 2, {\n operation: 'confirm before running',\n remediation:\n source === null\n ? 'pass `--yes` to confirm, or drop `--json` to be prompted'\n : `show the plan to the human, then re-run \\`infra-kit ${rerun.join(' ')}\\` to confirm`,\n stderrExcerpt: 'confirmation required and nobody to ask',\n })\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n if (!confirmedCommand && isHeadless()) refuseUnconfirmed(message, options.plan, options.rerun)\n\n const answer = confirmedCommand\n ? true\n : await withEscape(\n (context) => {\n return confirm({ message }, context)\n },\n // Unreachable headless: the guard above already refused every agent / `--json` run that got\n // here without `confirmedCommand`. Written out anyway \u2014 G7 requires every reachable site to\n // answer, and `'refuse'` is the answer that costs nothing if the guard above ever moves.\n { whenHeadless: 'refuse' },\n )\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It is also not a prompt\n * cancellation \u2014 Esc means \"I never answered\" and has its own handling, while this means\n * \"I answered, and the answer was no.\" Callers that opt in via `throwOnDecline` are\n * responsible for catching it and exiting 0.\n */\n// It exists so a command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n// directory, a lock \u2014 can unwind through its own `finally` blocks and release it, instead of\n// `confirmOrExit` calling `process.exit(0)` and skipping every one of them.\n//\n// That distinction is load-bearing rather than stylistic. In a plan -> confirm -> apply design,\n// declining is a first-class expected outcome, not an edge case, so the most ordinary non-happy\n// path is exactly the one that would leak.\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n", "// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n */\n// HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were\n// dropped for it \u2014 do not re-add either without re-deciding that:\n//\n// - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version\n// key, and a store the CLI refuses to read is a store the human cannot write.\n// - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout.\n// That guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so\n// `~/work/api` and `~/oss/api` share ONE token directory and repo B could load (and then\n// overwrite) repo A's credentials. It was removed anyway, knowingly: it also made the CLI refuse\n// every hand-written store, which carries no such field. Hand-authorability wins; the\n// basename-collision risk is ACCEPTED. A weakened version of the guard (warn-and-continue, or\n// \"only check when present\") is NOT the compromise here \u2014 it would re-introduce the same refusal\n// for anyone who did write the field. If you want the guard back, key the store directory on\n// something collision-free instead.\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 only a human can fix it \u2014 and downstream callers classify on that\n // CLASS (see EnvAuthError's doc). `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n await setTokens({ [env]: token })\n}\n\n/**\n * Add or replace several environments' tokens in ONE read-modify-write, so a bulk import never leaves\n * the store half-written between two of its entries.\n *\n * @example\n * await setTokens({ dev: 'dp.st.dev.x', arthur: 'dp.st.arthur.y' })\n * // tokens.json => { version: 1, envs: { \u2026existing, dev: 'dp.st.dev.x', arthur: 'dp.st.arthur.y' } }\n */\nexport const setTokens = async (tokens: Record<string, string>): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, ...tokens },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * Throw this (or a subclass) \u2014 never a plain `Error` \u2014 for anything a user must fix before\n * env-load can work: no token minted, a corrupt token store, a foreign token store.\n * `DopplerAuthError extends EnvAuthError` for the subset that is specifically \"Doppler refused the\n * token we sent\".\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\n// WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): every consumer of the auth\n// channel needs to classify a failure by its CLASS, not by re-deriving the answer from a message\n// some other module owns \u2014 and it has to be throwable from EVERY module that can produce the\n// class. `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned\n// base type could not be thrown there without a layering inversion and an import cycle. Hence a\n// neutral base here in `lib/errors`.\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * Deliberately WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only\n * one of the durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store\n * never reaches the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n"],
|
|
5
|
+
"mappings": "oKAOA,IAAMA,EAAoB,IAAM,CAC9B,IAAIC,EAAU,GACVC,EAA2B,CAAC,EAC5BC,EAAgB,GAEpB,MAAO,CAWL,MAAMC,EAAoB,CACxBH,EAAUG,EACVF,EAAU,CAAC,EACXC,EAAgB,EAClB,EAMA,gBAAuB,CACrBA,EAAgB,EAClB,EAQA,UAAUE,EAAcC,EAA0C,CACh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A,IAAMG,EAASd,EAAiB,UAAUU,CAAS,EAEnD,GAAI,CAACI,EAAO,QACV,MAAM,IAAIF,EACR,0BAA0BC,EAAQN,CAAS,CAAC,KAAKN,EAAE,cAAca,EAAO,KAAK,CAAC;AAAA,sFAEhF,EAGF,OAAOA,EAAO,IAChB,EAiBaC,EAAkB,MAAOC,GAAqC,CACzE,IAAMT,EAAY,MAAML,EAAkB,EAEpCe,EAAaZ,EAAK,QAAQE,CAAS,EACnCW,EAAcb,EAAK,QAAQY,CAAU,EACrCE,EAAgBd,EAAK,QAAQa,CAAW,EAE9C,QAAWE,IAAO,CAACD,EAAeD,EAAaD,CAAU,EACvD,MAAMR,EAAG,MAAMW,EAAK,CAAE,UAAW,GAAM,KAAMrB,CAAe,CAAC,EAC7D,MAAMU,EAAG,MAAMW,EAAKrB,CAAc,EAGpCsB,EAAoBd,EAAW,GAAG,KAAK,UAAUS,EAAO,KAAM,CAAC,CAAC;AAAA,EAAMlB,CAAe,EAIrF,MAAMW,EAAG,MAAMF,EAAWT,CAAe,CAC3C,EAsBO,IAAMwB,EAAY,MAAOC,GAAkD,CAChF,IAAMC,EAAW,MAAMC,EAAe,EAEtC,MAAMC,EAAgB,CACpB,QAASC,EACT,KAAM,CAAE,GAAGH,GAAU,KAAM,GAAGD,CAAO,CACvC,CAAC,CACH,EAYaK,EAAc,MAAOC,GAA+B,CAC/D,IAAML,EAAW,MAAMC,EAAe,EAEtC,GAAI,CAACD,GAAY,EAAEK,KAAOL,EAAS,MAAO,OAE1C,IAAMM,EAAO,CAAE,GAAGN,EAAS,IAAK,EAEhC,OAAOM,EAAKD,CAAG,EAEf,MAAMH,EAAgB,CACpB,QAASC,EACT,KAAAG,CACF,CAAC,CACH",
|
|
6
|
+
"names": ["createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "isAbsolute", "resolve", "process", "parsedArgv", "launchCwd", "setParsedArgv", "argv", "YES_FLAGS", "absolutizeChangeDir", "args", "cwd", "out", "index", "token", "rerunArgv", "userArgs", "separator", "optionsEnd", "options", "passThrough", "process", "ESC_BYTE", "headlessExcerpt", "source", "headlessRemediation", "argument", "resolveHeadless", "policy", "agentMode", "StructuredRefusalError", "withEscape", "run", "base", "controller", "whenHeadless", "promptBase", "context", "isHeadless", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "CommandDeclinedError", "message", "isCommandDeclined", "error", "refuseUnconfirmed", "message", "plan", "rerun", "rerunArgv", "source", "agentMode", "StructuredRefusalError", "confirmOrExit", "confirmedCommand", "options", "isHeadless", "answer", "withEscape", "context", "confirm", "commandEcho", "CommandDeclinedError", "logger", "process", "fs", "path", "z", "EnvAuthError", "message", "env", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setTokens", "tokens", "existing", "readTokenStore", "writeTokenStore", "TOKEN_STORE_VERSION", "removeToken", "env", "envs"]
|
|
7
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as x,e as ne,h as S,i as se,j as p}from"./chunk-
|
|
1
|
+
import{a as x,e as ne,h as S,i as se,j as p}from"./chunk-MYUZOXKA.js";import{P as c,S as oe,d,da as b,e as _,f as re,ga as m,h as D,i as te,w as P}from"./chunk-X33OD35Q.js";import{a as Z,c as U,d as T,f as G,g as H,h as B,i as Y,j as Q,o as X,p as K,q as ee}from"./chunk-I23MDR4X.js";import He from"@inquirer/select";import{readRepoIdentity as Be}from"@slip-stream-kit/config/internal";import{Buffer as Ye}from"node:buffer";import Qe from"node:fs";import J from"node:path";import $ from"node:process";import{z as k}from"zod";import{$ as I}from"zx";var _e="Could not find requested project",De="Could not find requested config",ie="Invalid Auth token",ae="does not have access to requested config",A=e=>e.includes(ie)||e.includes(ae)?"auth":e.includes(_e)?"project":e.includes(De)?"config":"unknown",R=e=>e.includes(ae)?"mis-scoped":e.includes(ie)?"revoked":null;var ce=e=>[`Doppler rejected the service token for env "${e}" \u2014 it is invalid, revoked, or scoped to a different config.`,`Fix: run \`infra-kit env-token-set ${e}\` with a token scoped to that config.`,"CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config."].join(`
|
|
2
2
|
`),f=class extends S{authKind;constructor(r,t=null,o){super(o??ce(r),r),this.name="DopplerAuthError",this.authKind=t}};var L=({kind:e,project:r,config:t,available:o})=>{let n=e==="project"?[`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${t}" not found in project "${r}".`];if(o&&o.length>0){let s=e==="project"?"Available projects":`Available configs in "${r}"`;n.push(`${s}: ${o.join(", ")}.`)}return n.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: pass an existing config, or create it in Doppler."),n.join(`
|
|
3
3
|
`)};import{$ as N}from"zx";var be=5e3,xe="DOPPLER_CONFIG",g=async()=>{let{envManagement:e}=await b();return e.config.name},Se=async({childEnv:e,project:r,config:t})=>{let o=N.quiet;N.quiet=!0;try{let s=(await N({env:e})`doppler secrets get ${xe} --plain --project ${r} --config ${t}`.timeout(be)).stdout.trim();return s!==t?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(n){return{outcome:Ne(n)}}finally{N.quiet=o}},Ne=e=>{let r=D(e)??(e instanceof Error?e.message:String(e));return A(r)!=="auth"?"unreachable":R(r)??"unreachable"};import Oe from"node:process";var l="INFRA_KIT_ENV_TOKEN",C=async e=>{let r=Oe.env[l];if(r)return{token:r,source:"env"};let o=(await p())?.envs[e];if(o)return{token:o,source:"store"};throw new S(je(e,await se()),e)},je=(e,r)=>[`No Doppler service token for env "${e}".`,`Mint one at https://dashboard.doppler.com \u2014 this project \u2192 config "${e}" \u2192 Access tab \u2192 "Generate Service Token".`,`Fix: run \`infra-kit env-token-set ${e}\` and paste it.`,`It is stored in ${oe(r)} (mode 0600, never in the repo).`,`CI / agents: set ${l} instead \u2014 it takes precedence and needs no home config.`].join(`
|
|
4
4
|
`);import Ee from"node:process";import{z as ve}from"zod";import ze from"node:process";import{z as u}from"zod";var le=["prod"],v={allowed:!1,reason:"disallow"},h=e=>le.includes(e),Fe=["dev","stage"],Ie=e=>Fe.includes(e)||h(e),$e=(e,r=v)=>r.allowed?e:e.filter(t=>!h(t)),Ke=(e,r,t=v)=>{if(!t.allowed&&h(e))throw t.reason==="agent-blocked"?new m({status:"refused",env:e,agentMode:d.source},2,{operation:r,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e}" is withheld from agents in this project (protectedEnvs: "cli-only")`}):new te(void 0,{operation:r,remediation:`use \`infra-kit release deliver\` \u2014 it merges the release to main, opens the RC PR, deploys from main, and releases the Jira version. To allow ad-hoc deploys to "${e}" in this project, set \`protectedEnvs\` to "allow" or "cli-only" in infra-kit.json`,stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})};var Le=async()=>{let e;try{e=(await b()).protectedEnvs??"disallow"}catch{return v}return e==="disallow"?v:e==="cli-only"&&_()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var Ce=e=>{let{env:r,branch:t}=e;h(r)&&c.warn([`\u26A0\uFE0F "${r}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${t}" ships ${r} from a ref that is not merged to main, and skips:`," \u2022 the squash-merge of the release branch into main"," \u2022 the RC pull request"," \u2022 the Jira fix-version release","Run `infra-kit release deliver` instead if you want those."].join(`
|
|
@@ -9,4 +9,4 @@ import{a as x,e as ne,h as S,i as se,j as p}from"./chunk-R6MPHCEI.js";import{P a
|
|
|
9
9
|
`)}
|
|
10
10
|
`,384),K(W,i,384),{filePath:W,variableCount:o.length,project:r,config:e}},Pe=q(),sr=async e=>{let{config:r}=e;await we({provider:Pe,params:e,operation:"env-load",argument:"config"});let t="";if(r)t=r;else{if(_())throw new m({status:"argument_required",argument:"config",agentMode:d.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let s=await z();x.setInteractive(),t=await ne(i=>He({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:$.stderr,whenHeadless:"refuse"})}x.addOption("--config",t);let o=await nr({config:t});x.print();let n={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config,sessionId:$.env[T]??null};return{content:O(JSON.stringify(n,null,2)),structuredContent:n}},Te=1024*1024,ir=3e4,ar=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],cr=(e,r=$.env)=>{let t={...r};for(let o of ar)delete t[o];return t.DOPPLER_TOKEN=e,t},eo=async e=>new Map(await Ae(await g(),e)),Ae=async(e,r)=>{let{token:t}=await C(r),o=cr(t),n=I.quiet;I.quiet=!0;try{let s;try{s=await I({env:o})`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(ir)}catch(a){throw pr(a,e,r)}ur(s.stdout);let i=mr(s.stdout);return lr(i,r),i}finally{I.quiet=n}},lr=(e,r)=>{let t=e.find(([o])=>o===Xe)?.[1];if(!(t===void 0||t===r))throw new f(r,null,`Doppler returned secrets for config "${t}" but "${r}" was requested \u2014 the service token for env "${r}" is scoped to the wrong config. Refusing to load another environment's secrets.
|
|
11
11
|
Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},pr=(e,r,t)=>{let o=D(e)??(e instanceof Error?e.message:String(e)),n=A(o);return n==="auth"?new f(t,R(o)):n==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(L({kind:n,project:r,config:t,available:null}))},ur=e=>{let r=Ye.byteLength(e,"utf-8");if(r>Te)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Te}) \u2014 refusing to write to disk`)},y=e=>`'${e.replaceAll("'","'\\''")}'`,dr=/^[A-Z_]\w*$/i,mr=e=>{let r;try{r=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let t=[];for(let[o,n]of Object.entries(r)){if(!dr.test(o))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(o.slice(0,80))})`);if(typeof n!="string")throw new TypeError(`doppler returned a non-string value for "${o}" (got ${typeof n})`);t.push([o,n])}if(t.length===0)throw new Error("doppler returned empty output for env-load");return t},ro=j({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit "config" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess.',inputSchema:{config:k.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:Pe,outputSchema:{filePath:k.string().describe("Path to the file that must be sourced to apply variables"),variableCount:k.number().describe("Number of variables loaded"),project:k.string().describe("Doppler project name"),config:k.string().describe("Doppler config name"),sessionId:k.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:sr});export{O as a,j as b,A as c,R as d,g as e,Se as f,l as g,C as h,h as i,Ie as j,$e as k,Ke as l,Le as m,Ce as n,Ve as o,w as p,z as q,ge as r,Je as s,we as t,rr as u,or as v,nr as w,sr as x,Te as y,cr as z,eo as A,lr as B,pr as C,ur as D,y as E,mr as F,ro as G};
|
|
12
|
-
//# sourceMappingURL=chunk-
|
|
12
|
+
//# sourceMappingURL=chunk-QSIWRM6A.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var i={name:"infra-kit",type:"module",version:"0.
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var i={name:"infra-kit",type:"module",version:"0.17.1",repository:{type:"git",url:"git+https://github.com/ArthurSaenz/infra-kit.git",directory:"apps/infra-kit/cli"},files:["dist"],description:"infra-kit",bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js","ik-mcp":"dist/mcp-proxy.js"},engines:{node:">=24.x"},scripts:{build:"pnpm run clean-artifacts && node ./scripts/build.js",prepack:"pnpm run build","infra-kit-check":"pnpm exec infra-kit audit","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only","qa:pty":"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts src/entry/__tests__/post-run-pause-pty.test.ts",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@aws-lambda-powertools/logger":"^2.35.0","@inquirer/checkbox":"^5.2.5","@inquirer/confirm":"^6.3.2","@inquirer/input":"^5.1.6","@inquirer/password":"^5.2.2","@inquirer/select":"^5.2.5","@slip-stream-kit/config":"workspace:^",chalk:"^6.0.0",chokidar:"^5.0.0",commander:"^15.0.0",fastify:"^5.12.5",ink:"^7.1.1",pino:"^10.3.1","pino-pretty":"^13.1.3",portless:"^0.15.6",react:"19.3.0",yaml:"^2.9.1",zod:"^4.6.5",zx:"^8.8.5"},devDependencies:{"@slip-stream-kit/eslint-plugin":"workspace:*","@types/aws-lambda":"catalog:","@types/react":"catalog:","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.2","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};export{i as a};
|
|
2
|
+
//# sourceMappingURL=chunk-SK3GYE2K.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../package.json"],
|
|
4
|
-
"sourcesContent": ["{\n \"name\": \"infra-kit\",\n \"type\": \"module\",\n \"version\": \"0.
|
|
4
|
+
"sourcesContent": ["{\n \"name\": \"infra-kit\",\n \"type\": \"module\",\n \"version\": \"0.17.1\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/ArthurSaenz/infra-kit.git\",\n \"directory\": \"apps/infra-kit/cli\"\n },\n \"files\": [\n \"dist\"\n ],\n \"description\": \"infra-kit\",\n \"bin\": {\n \"infra-kit\": \"dist/cli.js\",\n \"ik\": \"dist/cli.js\",\n \"ik-mcp\": \"dist/mcp-proxy.js\"\n },\n \"engines\": {\n \"node\": \">=24.x\"\n },\n \"scripts\": {\n \"build\": \"pnpm run clean-artifacts && node ./scripts/build.js\",\n \"prepack\": \"pnpm run build\",\n \"infra-kit-check\": \"pnpm exec infra-kit audit\",\n \"clean-artifacts\": \"rm -rf dist\",\n \"clean-cache\": \"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc\",\n \"prettier-fix\": \"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"prettier-check\": \"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"eslint-check\": \"pnpm exec eslint --cache --report-unused-disable-directives ./src\",\n \"eslint-fix\": \"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix\",\n \"ts-check\": \"tsc --noEmit\",\n \"test\": \"pnpm exec vitest run --reporter=minimal\",\n \"test-watch\": \"pnpm exec vitest --watch --silent passed-only\",\n \"test-ui\": \"pnpm exec vitest --ui --silent passed-only\",\n \"test-report\": \"pnpm exec vitest run --coverage --silent passed-only\",\n \"qa:pty\": \"INFRA_KIT_REQUIRE_PTY=1 pnpm exec vitest run --reporter=minimal src/tui/__tests__/stdin-pause-pty.test.ts src/entry/__tests__/quit-keys-pty.test.ts src/entry/__tests__/post-run-pause-pty.test.ts\",\n \"qa\": \"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success\",\n \"fix\": \"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa\"\n },\n \"dependencies\": {\n \"@aws-lambda-powertools/logger\": \"^2.35.0\",\n \"@inquirer/checkbox\": \"^5.2.5\",\n \"@inquirer/confirm\": \"^6.3.2\",\n \"@inquirer/input\": \"^5.1.6\",\n \"@inquirer/password\": \"^5.2.2\",\n \"@inquirer/select\": \"^5.2.5\",\n \"@slip-stream-kit/config\": \"workspace:^\",\n \"chalk\": \"^6.0.0\",\n \"chokidar\": \"^5.0.0\",\n \"commander\": \"^15.0.0\",\n \"fastify\": \"^5.12.5\",\n \"ink\": \"^7.1.1\",\n \"pino\": \"^10.3.1\",\n \"pino-pretty\": \"^13.1.3\",\n \"portless\": \"^0.15.6\",\n \"react\": \"19.3.0\",\n \"yaml\": \"^2.9.1\",\n \"zod\": \"^4.6.5\",\n \"zx\": \"^8.8.5\"\n },\n \"devDependencies\": {\n \"@slip-stream-kit/eslint-plugin\": \"workspace:*\",\n \"@types/aws-lambda\": \"catalog:\",\n \"@types/react\": \"catalog:\",\n \"@wl/eslint-config\": \"workspace:*\",\n \"@wl/vitest-config\": \"workspace:*\",\n \"esbuild\": \"^0.28.2\",\n \"ink-testing-library\": \"^4.0.0\",\n \"typescript\": \"^6.0.3\"\n }\n}\n"],
|
|
5
5
|
"mappings": "AAAA,IAAAA,EAAA,CACE,KAAQ,YACR,KAAQ,SACR,QAAW,SACX,WAAc,CACZ,KAAQ,MACR,IAAO,mDACP,UAAa,oBACf,EACA,MAAS,CACP,MACF,EACA,YAAe,YACf,IAAO,CACL,YAAa,cACb,GAAM,cACN,SAAU,mBACZ,EACA,QAAW,CACT,KAAQ,QACV,EACA,QAAW,CACT,MAAS,sDACT,QAAW,iBACX,kBAAmB,4BACnB,kBAAmB,cACnB,cAAe,2EACf,eAAgB,4HAChB,iBAAkB,4HAClB,eAAgB,oEAChB,aAAc,kFACd,WAAY,eACZ,KAAQ,0CACR,aAAc,gDACd,UAAW,6CACX,cAAe,uDACf,SAAU,qMACV,GAAM,gHACN,IAAO,6DACT,EACA,aAAgB,CACd,gCAAiC,UACjC,qBAAsB,SACtB,oBAAqB,SACrB,kBAAmB,SACnB,qBAAsB,SACtB,mBAAoB,SACpB,0BAA2B,cAC3B,MAAS,SACT,SAAY,SACZ,UAAa,UACb,QAAW,UACX,IAAO,SACP,KAAQ,UACR,cAAe,UACf,SAAY,UACZ,MAAS,SACT,KAAQ,SACR,IAAO,SACP,GAAM,QACR,EACA,gBAAmB,CACjB,iCAAkC,cAClC,oBAAqB,WACrB,eAAgB,WAChB,oBAAqB,cACrB,oBAAqB,cACrB,QAAW,UACX,sBAAuB,SACvB,WAAc,QAChB,CACF",
|
|
6
6
|
"names": ["package_default"]
|
|
7
7
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ie}from"./chunk-MFAFQVTW.js";import{a as ne}from"./chunk-
|
|
1
|
+
import{a as ie}from"./chunk-MFAFQVTW.js";import{a as ne}from"./chunk-SK3GYE2K.js";import{e as N,q as re,s as oe}from"./chunk-I23MDR4X.js";import Fe from"node:process";import De from"node:process";var S={enabled:!1},We=(e,t=r=>{De.stdout.write(r)})=>(S.enabled&&e&&e.structuredContent!=null&&t(`${JSON.stringify(e.structuredContent,null,2)}
|
|
2
2
|
`),e),se=e=>{e.options.some(r=>r.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(se)};var ae={source:null},w=()=>ae.source!==null,qe=()=>w()||S.enabled,_=()=>!!Fe.env.CI,ze=({env:e,stdinIsTTY:t,flag:r})=>{if(r)return"flag";let o=e.INFRA_KIT_AGENT;return o==="1"||e.CLAUDECODE!==void 0&&!t&&o!=="0"?"env":null};var x=e=>{let t=new Set,r=e;for(;r!==null&&typeof r=="object"&&!t.has(r);){t.add(r);let{stderr:o,stderrExcerpt:n}=r;if(typeof o=="string"&&o.length>0)return o;if(typeof n=="string"&&n.length>0)return n;r=r.cause}},Ge=(e,t)=>{let r=t.stderrExcerpt??x(e),o=[`failed to ${t.operation}`];return r&&o.push(`stderr: ${r.slice(0,200).trim()}`),t.remediation&&o.push(`try: ${t.remediation}`),o.join(" \u2014 ")},u=class extends Error{operation;remediation;stderrExcerpt;constructor(t,r){super(Ge(t,r),{cause:t}),this.name="OperationError",this.operation=r.operation,this.remediation=r.remediation,this.stderrExcerpt=r.stderrExcerpt??x(t)}};import k from"node:path";import le from"node:process";import{$ as m}from"zx";var Be=/^v?(\d+)\.(\d+)\.(\d+)$/,Ue=/^(\d+)\.(\d+)\.(\d+)$/,He=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,I="release/",T="release/v",ce="refs/heads/",Ve="next";var ue=new Set(["dev","main","next","hotfix","regular","release"]),g=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},h=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},pe=e=>e.startsWith(ce)?e.slice(ce.length):e,de=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),L=e=>{if(e.length===0)throw new g('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new g(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!He.test(e))throw new g(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(ue.has(e))throw new g(`Release name "${e}" is reserved. Reserved names: ${[...ue].join(", ")}.`)},K=e=>{let t=pe(e.trim());if(!t.startsWith(I))return null;if(t.startsWith(T)){let o=t.slice(T.length),n=Ue.exec(o);if(n)return de(Number(n[1]),Number(n[2]),Number(n[3]))}let r=t.slice(I.length);try{L(r)}catch{return null}return{kind:"name",name:r,raw:r}},Je=e=>{let t=e.trim();if(pe(t).startsWith(I)){let n=K(t);if(!n)throw new h(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return n}let o=Be.exec(t);if(o)return de(Number(o[1]),Number(o[2]),Number(o[3]));if(t.toLowerCase()===Ve)throw new h('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');if(t.includes("@"))throw new h(`Cannot parse "${e}" as a release ref: the \`@date\` suffix belongs to \`release create\`; pass the version alone here and use \`--release-date\` on \`release edit\``);try{L(t)}catch(n){let s=n instanceof Error?n.message:String(n);throw new h(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:t,raw:t}},Xe=e=>e.kind==="version"?`${T}${e.raw}`:`${I}${e.name}`,Ye=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},Ze=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,Qe=e=>e.kind==="version"?`v${e.raw}`:e.name,et=e=>e.raw,D=e=>e==null?!1:K(e)!==null,me=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},tt=(e,t,r)=>{if(e.kind==="version"&&t.kind==="version")return e.semver.major!==t.semver.major?e.semver.major-t.semver.major:e.semver.minor!==t.semver.minor?e.semver.minor-t.semver.minor:e.semver.patch-t.semver.patch;if(e.kind==="version")return-1;if(t.kind==="version")return 1;let o=me(r?.a),n=me(r?.b);return o!==null&&n!==null&&o!==n?o-n:e.name<t.name?-1:e.name>t.name?1:0};var fe=async e=>{let t=await m({cwd:e})`git worktree list --porcelain`,r=[],o=null;for(let n of t.stdout.split(`
|
|
3
3
|
`)){if(n.startsWith("worktree ")){o&&r.push(o),o={path:n.slice(9),branch:null,detached:!1,bare:!1,prunable:!1,locked:!1};continue}o&&(n.startsWith("branch ")?o.branch=n.slice(7).replace(/^refs\/heads\//,""):n==="detached"?o.detached=!0:n==="bare"?o.bare=!0:n==="locked"||n.startsWith("locked ")?o.locked=!0:(n==="prunable"||n.startsWith("prunable "))&&(o.prunable=!0))}return o&&r.push(o),r},rt=async e=>{let t=await fe(le.cwd()),r=o=>e==="release"?D(o):o.startsWith("feature/");return t.map(o=>o.branch).filter(o=>o!==null&&r(o))},ot=e=>{let t=x(e);return t&&/not a git repository/i.test(t)?"not a git repository":void 0},nt=({hasStderr:e})=>{if(w())return"infra-kit resolves its project from the working directory; run it from inside an infra-kit project repo (or one of its git worktrees), or pass `-C <dir>` naming one";let t="run infra-kit from inside an infra-kit project repo (or one of its git worktrees)";return e?`${t}; if you are already in one, the stderr in this message is the real cause`:t},R=async()=>{try{return(await m({quiet:!0})`git rev-parse --show-toplevel`).stdout.trim()}catch(e){let t=ot(e)??x(e);throw new u(e,{operation:`resolve the project root from ${le.cwd()}`,stderrExcerpt:t,remediation:nt({hasStderr:t!==void 0})})}},W=async e=>{let t=e??await R(),r=(await m({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),o=k.resolve(t,r);return o.includes(`${k.sep}.git${k.sep}modules${k.sep}`)?t:k.dirname(o)},ge=async()=>(await m`git rev-parse --abbrev-ref HEAD`).stdout.trim(),he=async()=>(await m`git status --porcelain`).stdout.split(`
|
|
4
4
|
`).map(t=>t.trimEnd()).filter(t=>t.trim().length>0),it=async()=>(await he()).length===0,st=async()=>{let e=await R(),[t,r]=await Promise.all([m({cwd:e})`git rev-parse --absolute-git-dir`,m({cwd:e})`git rev-parse --git-common-dir`]),o=t.stdout.trim(),n=k.resolve(e,r.stdout.trim());return o!==n};var at=async e=>(await m`git branch --list ${e}`).stdout.trim().length>0,ct=async e=>{(await m`git branch --list ${e}`).stdout.trim().length!==0&&await ge()!==e&&await m`git branch -D ${e}`},ut=async e=>{(await m`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await m`git push origin --delete ${e}`};import{$ as P}from"zx";var mt=async(e,t)=>{let r=`${t}^{commit}`;try{return(await P({cwd:e,quiet:!0})`git rev-parse --verify --quiet ${r}`).stdout.trim()||null}catch{return null}},pt=async(e,t,r)=>{try{return await P({cwd:e,quiet:!0})`git merge-base --is-ancestor ${t} ${r}`,!0}catch(o){if(o.exitCode===1)return!1;throw new u(o,{operation:`test whether ${t} is contained in ${r}`,remediation:"both refs must exist \u2014 verify them with rev-parse first"})}},dt=async(e,t)=>{let o=(await P({cwd:e,quiet:!0})`git ls-remote --heads origin ${t}`).stdout.trim().split(`
|
|
@@ -11,4 +11,4 @@ A retired key on this branch \u2014 run \`infra-kit setup --skip-tools\` in this
|
|
|
11
11
|
`),kr=e=>[`"aliasRepo" is not allowed in ${e.label} (${e.path}): the vite and Playwright helpers read it from the project infra-kit.json only, so a per-machine copy would register a dev host they never aim at.`,"Move it to the project infra-kit.json and commit it there."].join(`
|
|
12
12
|
`),vr={aliasRepo:kr,mcp:hr,vendorSource:yr,audit:wr},xr=(e,t)=>{for(let[r,o]of Object.entries(vr))if(r in t)throw new Error(o(e))},Y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rr=e=>[`Refusing to load ${e.label} \u2014 \`envTokens\` is not a config key.`,"A service token in a config file can be committed, backed up by your editor, or shared."," 1. REVOKE the token in Doppler now \u2014 treat it as compromised.",` 2. Remove the \`envTokens\` key from ${e.path}.`," 3. Re-add it privately: `infra-kit env-token-set <env>`"," (it is written to ~/.infra-kit/projects/<repo>/tokens.json, mode 0600, never to the repo)."].join(`
|
|
13
13
|
`);var Ke=class extends u{structuredContent;exitCode;constructor(t,r,o){super(void 0,o),this.name="StructuredRefusalError",this.structuredContent=t,this.exitCode=r}};export{S as a,We as b,se as c,ae as d,w as e,qe as f,ze as g,x as h,u as i,g as j,L as k,K as l,Je as m,Xe as n,Ye as o,Ze as p,Qe as q,et as r,D as s,tt as t,fe as u,rt as v,R as w,W as x,ge as y,he as z,it as A,st as B,at as C,ct as D,ut as E,mt as F,pt as G,dt as H,lt as I,we as J,ft as K,z as L,gt as M,ht as N,yt as O,G as P,B as Q,It as R,H as S,j as T,$ as U,_t as V,je as W,ee as X,ar as Y,$e as Z,Z as _,cr as $,ur as aa,_e as ba,Te as ca,mr as da,pr as ea,dr as fa,Ke as ga};
|
|
14
|
-
//# sourceMappingURL=chunk-
|
|
14
|
+
//# sourceMappingURL=chunk-X33OD35Q.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as Kp,d as Zp,f as $r,g as om,h as St,i as Ps,j as sm,k as im,l as am,m as cm,n as lm,o as dm,p as um,q as pm,t as $a,u as gm,v as Re}from"./chunk-
|
|
2
|
+
import{a as Kp,d as Zp,f as $r,g as om,h as St,i as Ps,j as sm,k as im,l as am,m as cm,n as lm,o as dm,p as um,q as pm,t as $a,u as gm,v as Re}from"./chunk-5NW4ZWKT.js";import{b as Vp,d as Up,k as Jp,n as Gp}from"./chunk-Y3RW74TE.js";import{a as Ae,b as np,c as ya,d as op,e as sp,f as ip,g as ap,h as Tn,i as cp,j as lp,k as dp,l as up,m as pp,n as Cn,o as mp,p as fp,q as gp,r as hp,s as va,t as ms,u as yt,v as yp,w as fs,x as vp}from"./chunk-IT6XJWTW.js";import{a as ue,b as q,c as bt,d as ks,e as Sa,f as bs,g as Pa,h as On,i as Ht,j as Rs,k as Wp,l as In,m as Dn,n as Ea,o as xa,q as Ta}from"./chunk-MH37P7W4.js";import{b as xn,c as us,d as ha,e as Zu,f as ps,g as Qu,i as ep,k as tp,m as he,o as rp}from"./chunk-AWFGP6GY.js";import{a as Xp}from"./chunk-TVG47UHG.js";import{B as Oa,F as Ia,G as Da,a as k,b as S,c as Qp,d as em,e as qt,f as tm,g as Yt,h as nm,i as mm,j as Nn,k as Pt,l as Ar,m as He,n as Es,o as Et,p as fm,q as xs,r as hm,s as ym,t as qe,x as Aa,z as _n}from"./chunk-QSIWRM6A.js";import{a as h,b as at,c as Hp,d as qp,e as O,f as Ss,g as B,i as Rt,j as Ve,k as Ca,l as rm}from"./chunk-MYUZOXKA.js";import{$ as wt,A as Ep,B as xp,C as Tp,D as ys,E as vs,F as Oe,G as $n,H as Cr,I as ws,J as Cp,K as $p,L as Ap,M as ka,N as ba,O as Op,P as u,Q as Ie,R as Z,S as v,T as Ip,U as Dp,V as Np,W as Mp,X as jp,Y as vt,Z as Fp,_ as Ra,a as Kt,aa as Lp,b as A,ba as Bp,c as wp,ca as H,d as N,da as M,e as ye,ea as An,f as J,fa as kt,g as gs,ga as C,h as kp,i as f,j as bp,k as hs,l as G,m as me,n as ve,o as Rp,p as wa,q as re,r as X,s as xr,t as Sp,u as Ke,v as fe,w as T,x as be,y as Tr,z as Pp}from"./chunk-X33OD35Q.js";import{a as _p}from"./chunk-MFAFQVTW.js";import{a as K}from"./chunk-SK3GYE2K.js";import{a as Rr,b as ss,c as is,d as Pn,e as Ku,f as Sr,g as as,h as cs,i as Hu,j as ls,k as ds,l as qu,m as Yu,n as zu,o as Pr,p as En,q as de,r as Xu,s as Er}from"./chunk-I23MDR4X.js";import{a as Yp,b as zp}from"./chunk-QWVLAZ6N.js";import MD,{Separator as iw}from"@inquirer/select";import{existsSync as jD,realpathSync as FD}from"node:fs";import{homedir as LD}from"node:os";import $e from"node:process";import{fileURLToPath as cw}from"node:url";import af from"node:process";import{z as _e}from"zod";import Em from"node:fs";import Dr from"node:path";import{packageConfigSchema as km}from"@slip-stream-kit/config/internal";import bm from"node:fs/promises";import Ts from"node:path";import{pathToFileURL as yw}from"node:url";import{z as Rm}from"zod";import vm from"node:path";var Mn=["frontend","backend","lib","e2e","mobile"],uw={ui:"frontend",api:"backend",tests:"e2e"},pw="mobile-app",mw=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],fw=(e,t)=>{let r=vm.relative(t,e).split(vm.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=uw[o];if(s)return s}return r.at(-1)===pw?"mobile":null},gw=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of mw)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},jn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??fw(e,t)??gw(r)??"lib";var xt={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},wm=2e3,Na={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${wm}} pnpm exec playwright test --ui --headed --workers=1`,"e2e-test-chrome":"pnpm exec playwright test --project=chromium","e2e-test-debug":"pnpm exec playwright test --debug","e2e-test-codegen":"pnpm exec playwright codegen","playwright-install":"pnpm exec playwright install --with-deps"},Fn={requiredScripts:["build","dev","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},Ln=(e,t=xt)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import hw from"node:fs/promises";var Se=async e=>{try{return await hw.access(e),!0}catch{return!1}};var ne="infra-kit.config.ts",zt=async e=>{try{let t=await bm.readFile(Ts.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},_a=async e=>{let t=await bm.stat(e),o=(await import(`${yw(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${ne} at ${e} has no default export`);return typeof o=="function"?await o():o},Xt=async e=>{let t=Ts.join(e,ne);if(await Se(t))try{let n=(await _a(t))?.type;return Mn.find(o=>o===n)}catch{return}},Bn=async(e,t=xt)=>{let r=Ts.join(e,ne);if(!await Se(r))throw new Error(`${ne} not found at ${r}`);let n=await _a(r),o=km.safeParse(n);if(!o.success)throw new Error(`Invalid ${ne} at ${r}: ${Rm.prettifyError(o.error)}`);return Ln(o.data,t)},Or=async e=>{let t=Ts.join(e,ne);if(!await Se(t))return;let r=km.safeParse(await _a(t));if(!r.success)throw new Error(`Invalid ${ne} at ${t}: ${Rm.prettifyError(r.error)}`);return r.data};import Sm from"node:fs/promises";import Cs from"node:path";import vw from"yaml";var ww="pnpm-workspace.yaml",kw=async e=>(await Sm.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Cs.join(e,r.name)),bw=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await kw(n));continue}let o=Cs.join(n,t);await Se(o)&&r.push(o)}return r},Rw=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await bw(r,n);return r},Pe=async e=>{let t=await Sm.readFile(Cs.join(e,ww),"utf-8"),n=((vw.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await Rw(e,s);for(let a of i)await Se(Cs.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Wn from"node:path";var Vn=async e=>{let t=Wn.resolve(e);for(;t!==Wn.dirname(t);){if(await Se(Wn.join(t,"package.json")))return t;t=Wn.dirname(t)}if(await Se(Wn.join(t,"package.json")))return t;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var Ye=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Tt=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);if(n===-1||o===-1||o<n)return null;let s=e.slice(0,n).replace(/\n+$/,""),i=e.slice(o+r.length).replace(/^\n+/,"");return s+(i?`
|
|
3
3
|
${i}`:"")},Ma=(e,t)=>{let r=e.indexOf(t);if(r===-1)return null;let o=e.slice(r+t.length).match(/^([^\s>]+)/);return o?o[1]:null},Pm=(e,t,r)=>`${e}
|
|
4
4
|
${t}
|
|
5
5
|
${r}`,Ir=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Pm(r,t,n),i=Ye(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),d=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(d)}let c=(i?Tt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
package/dist/dev-server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as qe,b as N,c as j,d as Xe,e as W,g as L,h as Qe,l as Ze,n as et,r as tt,s as rt,t as nt,u as ae,v as it}from"./chunk-
|
|
1
|
+
import{a as qe,b as N,c as j,d as Xe,e as W,g as L,h as Qe,l as Ze,n as et,r as tt,s as rt,t as nt,u as ae,v as it}from"./chunk-5NW4ZWKT.js";import{a as O,b as M,c as Be,d as Me,e as H,f as He,g as I,h as je,i as We,j as Ge,k as Ve,l as Ke,m as Je,n as ze}from"./chunk-Y3RW74TE.js";import{c as ne,k as ie,n as Ie,o as Ne,u as Le}from"./chunk-IT6XJWTW.js";import"./chunk-AWFGP6GY.js";import{P as T,Y as Fe,d as _e,da as oe,ga as Ye,i as se,x as Ue}from"./chunk-X33OD35Q.js";import"./chunk-MFAFQVTW.js";import"./chunk-SK3GYE2K.js";import{d as $e,f as Ce,n as Oe}from"./chunk-I23MDR4X.js";import{a as _,b as st}from"./chunk-DVXTZPQ5.js";import{Command as ii}from"commander";import k from"node:process";import{pathToFileURL as si}from"node:url";import le from"node:process";var ue=n=>{try{le.stderr.write(n)}catch{}},U=(n,e,t=!0)=>{let r=e instanceof Error?`${e.message}
|
|
2
2
|
${e.stack??"(no stack)"}`:String(e);return`
|
|
3
3
|
\u26A0\uFE0F ${n}: ${r}
|
|
4
4
|
${t?` dev-server kept alive (likely a bug in a handler's async path); restart if it misbehaves.
|
|
@@ -35,5 +35,5 @@ Received ${t}, closing Orca tab "${e}"...`),await ar(n)}})},lr=async n=>{let e=O
|
|
|
35
35
|
`);let l=r(()=>{e(),t(Ee)},i);a.shutdown().finally(()=>{l(),t(Ee)}).catch(()=>{})}},pi=["SIGINT","SIGTERM"],ci=({forceReap:n=N,exit:e=i=>{k.exit(i)},register:t=(i,s)=>{k.on(i,s)},unregister:r=(i,s)=>{k.off(i,s)}}={})=>{let i=new Map;for(let s of pi){let o=()=>{cr(n,e,Xe(s))};i.set(s,o),t(s,o)}return{remove:()=>{for(let[s,o]of i)r(s,o)}}},xe=async n=>{let e=li(n);if(e.orca){let l=await lr(e);if(l==="ran")return;k.stdout.write(`Orca: ${l.fallback}; falling back to single-terminal dev
|
|
36
36
|
`)}let t=null,r=ui(),i=di({getRunner:()=>t,setTimer:r}),s=Pt({onDeath:(l,u)=>{i(`stdio unwritable: ${l} ${u.code}`)}}),o=ci();try{t=await sr({...e,onExitRequest:l=>{k.exit(l)}})}finally{o.remove()}let a=t;ot({onFault:(l,u)=>{a.reportFault(U(l,u))},isTerminalDead:s.isDead,fileFault:(l,u)=>{a.fileFault(U(l,u,!1))},onFatal:i}),W({onSignal:async l=>{he(`
|
|
37
37
|
Received ${l}, shutting down dev-server...
|
|
38
|
-
`),await a.shutdown()},describeStall:()=>a.shutdownStage,fileReport:l=>{a.fileFault(l)},setTimer:r})},hi=(n,e,t)=>!n.preset&&!n.app&&!n.self&&!n.orca&&n.watch==null&&!n.verbose&&!n.routes&&!n.reuse&&e&&!t,gi=(n,e)=>({watch:n.watch,orca:n.orca,include:n.include??null,preset:n.preset,presetDef:n.presetDef,self:!1,verbose:!1,routes:!1,uiHealth:e.uiHealth??!0}),ho=async(n,e,t)=>{if(hi(n,e,t)){let{runDevWizard:r}=await import("./dev-wizard-run-
|
|
38
|
+
`),await a.shutdown()},describeStall:()=>a.shutdownStage,fileReport:l=>{a.fileFault(l)},setTimer:r})},hi=(n,e,t)=>!n.preset&&!n.app&&!n.self&&!n.orca&&n.watch==null&&!n.verbose&&!n.routes&&!n.reuse&&e&&!t,gi=(n,e)=>({watch:n.watch,orca:n.orca,include:n.include??null,preset:n.preset,presetDef:n.presetDef,self:!1,verbose:!1,routes:!1,uiHealth:e.uiHealth??!0}),ho=async(n,e,t)=>{if(hi(n,e,t)){let{runDevWizard:r}=await import("./dev-wizard-run-4XJYZTCO.js"),i=Promise.all([import("./persistent-ink-dev-ui-ZSOS3CF4.js"),import("./safe-stderr-ECYA6DRR.js")]).catch(()=>{}),s;try{s=await r()}catch(o){if(it(o))return;throw o}if(s==null)return;await i,await xe({...gi(s,n),tty:e,json:t});return}await xe({...dr(n),tty:e,json:t})},fi=async n=>{let e=new ii;e.name("infra-kit-dev-server").description("Run local dev servers for the apps in a named devServersPresets preset (or all apps)").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)"),e.parse(n),await xe(dr({...e.opts(),preset:e.args[0]}))};import.meta.url===si(k.argv[1]??"").href&&fi(k.argv).catch(n=>{console.error(n instanceof Error?n.message:String(n)),k.exit(1)});export{di as createFatalHandler,ui as createSharedDeadlineTimer,ci as installBootSignalGuard,xe as runDevServer,ho as runDevServerCli,hi as shouldRunWizard,dr as toDevServerOptions};
|
|
39
39
|
//# sourceMappingURL=dev-server.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as b,b as k,d as w,n as C}from"./chunk-Y3RW74TE.js";import{a as g,e as h,j as x}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=dev-wizard-run-
|
|
1
|
+
import{a as b,b as k,d as w,n as C}from"./chunk-Y3RW74TE.js";import{a as g,e as h,j as x}from"./chunk-MYUZOXKA.js";import{P as d,da as v}from"./chunk-X33OD35Q.js";import"./chunk-MFAFQVTW.js";import"./chunk-SK3GYE2K.js";import{f as y}from"./chunk-I23MDR4X.js";import"./chunk-QWVLAZ6N.js";import B from"@inquirer/checkbox";import j from"@inquirer/confirm";import _,{Separator as U}from"@inquirer/select";import{loadDev as I,loadPackageConfig as K}from"@slip-stream-kit/config/internal";import R from"node:path";import m from"node:process";var W=e=>e.split("/")[0],D=e=>new Map(e.apps.map(r=>[r.name,r])),$=e=>e.localCapable&&e.cloudCapable,N=(e,r,a)=>$(r)?a[`${e} ${r.path}`]??(r.cloudCapable?"cloud":"local"):r.localCapable?"local":"cloud",O=(e,r,a)=>{let n=new Set,t=new Map;for(let o of e){let s=r.get(W(o));for(let i of s?.backends??[]){t.set(i.packageName,i.ownerApp);for(let l of i.routes)N(o,l,a)==="local"&&n.add(i.packageName)}}return{localPkgs:n,ownerByPkg:t}},E=(e,r)=>{let a={},n=!1;for(let t of e?.backends??[]){let o=r.has(t.packageName);for(let s of t.routes){let i=s.localCapable&&o?"local":"cloud";a[s.path]=i,i==="cloud"&&(n=!0)}}return{overrides:a,anyCloud:n}},M=(e,r)=>{let a=D(r),n=e.targets.filter(c=>c.endsWith("/ui")),t=e.targets.filter(c=>c.endsWith("/api")),{localPkgs:o,ownerByPkg:s}=O(n,a,e.sources),i={},l=!1;for(let c of n){let{overrides:f,anyCloud:p}=E(a.get(W(c)),o);p&&(l=!0),i[c]=Object.keys(f).length>0?{proxy:f}:{}}for(let c of t)i[c]??={};for(let c of o){let f=s.get(c);f!=null&&(i[`${f}/api`]??={})}return{presetDef:{apps:i,orca:e.orca},anyCloudRoute:l,targetKeys:Object.keys(i).sort()}},z=(e,r)=>{let a=[`--target=${e.targetKeys.join(",")}`];return r.watch||a.push("--no-watch"),r.orca&&a.push("--orca"),{flags:a.join(" ")}};var P={output:m.stderr,clearPromptOnDone:!0},V={select:e=>h(r=>_({message:e.message,choices:e.choices,default:e.default},r),{...P,whenHeadless:"refuse"}),checkbox:e=>h(r=>B({message:e.message,choices:e.choices},r),{...P,whenHeadless:"refuse"}),confirm:e=>h(r=>j({message:e.message,default:e.default},r),{...P,whenHeadless:"refuse"})},q=(e,r)=>{let a=new Map;for(let[n,t]of Object.entries(e)){let o={path:n,localCapable:t.from.includes("local"),cloudCapable:t.from.includes("cloud"),default:t.default},s=a.get(t.packageName);s?(s.routes.push(o),s.localCapable=s.localCapable||o.localCapable,s.cloudCapable=s.cloudCapable||o.cloudCapable):a.set(t.packageName,{packageName:t.packageName,routes:[o],localCapable:o.localCapable,cloudCapable:o.cloudCapable,ownerApp:r.get(t.packageName)})}return[...a.values()]},L=async(e,r,a)=>{try{let n=(await I(e))?.proxy?.routes;return n?q(n,a):[]}catch(n){return d.warn(`\u26A0\uFE0F Skipping ${r}: its dev config failed to load \u2014 ${n instanceof Error?n.message:String(n)}`),[]}},T=async e=>{let r=k(e),a=w(e),n=await v(),t=new Map(r.map(p=>[p.packageName,p.name])),o=new Map(r.map(p=>[p.name,p.packageName])),s=new Set(a.map(p=>p.name)),i=new Set(r.map(p=>p.name)),l=[...new Set([...i,...s])].sort(),c=await Promise.all(l.map(async p=>{let u=s.has(p);return{name:p,hasApi:i.has(p),hasUi:u,apiPackage:o.get(p),backends:u?await L(R.join(e,"apps",p,"ui"),p,t):[],deployedUrlEnv:u?(await K(R.join(e,"apps",p,"ui")).catch(()=>{}))?.deployedUrlEnv:void 0}})),f=await x();return{apps:c,presets:Object.keys(n.devServersPresets??{}),environments:Object.keys(f?.envs??{}).sort()}},F=e=>{let r=[];for(let a of e.apps){if(a.hasUi){let n=a.backends.flatMap(o=>o.routes.map(s=>s.path)),t=n.length>0?`frontend \u2014 proxies ${[...n].sort().join(", ")}`:"frontend";r.push({name:`${a.name}/ui`,value:`${a.name}/ui`,description:t})}a.hasApi&&!a.hasUi&&r.push({name:`${a.name}/api`,value:`${a.name}/api`,description:"backend"})}return r},H=e=>{let r={api:e.apps.filter(t=>t.hasApi).map(t=>t.name),ui:e.apps.filter(t=>t.hasUi).map(t=>t.name)},a={},n=new Map;for(let t of e.apps){t.apiPackage!=null&&(a[t.name]=t.apiPackage);for(let o of t.backends)for(let s of o.routes)n.set(`${t.name} ${s.path}`,o.packageName)}return{discovered:r,apiPkgByApp:a,routePkg:(t,o)=>n.get(`${t} ${o}`)}},Z=(e,r)=>C({__wizard__:e},H(r)).map(a=>a.message),G="INFRA_KIT_DEV_WIZARD_ORCA",J=()=>m.env[G]==="1",Q=async(e,r,a)=>{let n=new Map(r.apps.map(o=>[o.name,o])),t={};for(let o of a){let s=n.get(o.split("/")[0]);for(let i of s?.backends??[])for(let l of i.routes){if(!l.localCapable||!l.cloudCapable)continue;let c=await e.select({message:`\u{1F500} ${o} ${l.path} \u2192 local or cloud?`,choices:[{name:"local (this machine)",value:"local"},{name:"cloud",value:"cloud"}],default:l.default??"local"});t[`${o} ${l.path}`]=c}}return t},X=(e,r,a)=>e.apps.find(n=>n.name===r)?.backends.flatMap(n=>n.routes).find(n=>n.path===a),Y=(e,r)=>{let a=[];for(let[n,t]of Object.entries(e.presetDef.apps??{})){if(!n.endsWith("/ui")||!t.proxy)continue;let o=n.split("/")[0];for(let[s,i]of Object.entries(t.proxy)){let l=X(r,o,s),c=l&&l.localCapable&&l.cloudCapable?"":" (only option)";a.push(` ${n} ${s} \u2192 ${i}${c}`)}}if(a.length!==0){d.info("Resolved routes:");for(let n of[...a].sort())d.info(n)}},ee=async(e,r)=>{let{downloadEnvSecrets:a}=await import("./env-load-L3FLJR4O.js"),n=await a(e);return new Map(r.flatMap(t=>{let o=n.get(t);return o===void 0?[]:[[t,o]]}))},re=async(e,r,a,n)=>{let t=r.flatMap(s=>{let i=a.apps.find(l=>`${l.name}/ui`===s);return i?.deployedUrlEnv?[i.deployedUrlEnv]:[]}),o=t.length>0?await n(e,t):new Map;m.env[y]=e;for(let s of t){let i=o.get(s);i?m.env[s]=i:(delete m.env[s],d.warn(`\u2601\uFE0F "${e}" holds no ${s}; routes that go to the deployed app will fail until it does.`))}},S=async(e,r,a)=>{if(r.apps.length===0)return d.warn("No apps discovered to run."),null;let n=await e.checkbox({message:"\u{1F4E6} Which packages?",choices:F(r)});if(n.length===0)return d.warn("No packages selected."),null;let t=n.filter(u=>u.endsWith("/ui")),o=await Q(e,r,t),s=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!0}),i=J()?await e.confirm({message:"\u{1F9E9} Run each app in its own Orca pane?",default:!1}):!1,l={targets:n,sources:o,watch:s,orca:i},c=M(l,r);if(c.anyCloudRoute){if(r.environments.length===0)return d.warn("\u2601\uFE0F This selection routes to a cloud environment, but no environment token is loaded."),d.warn(" Run `infra-kit env-load` to add one, then re-run the wizard."),null;l.env=await e.select({message:"\u2601\uFE0F Point cloud routes at which environment?",choices:r.environments.map(u=>({name:u,value:u}))}),await re(l.env,t,r,a)}let f=Z(c.presetDef,r);if(f.length>0){d.warn("\u26A0\uFE0F Proxy audit found issues with this selection:");for(let u of f)d.warn(` \u2022 ${u}`);return null}Y(c,r),ae(c,l);let p=c.targetKeys.filter(u=>u.endsWith("/api")).map(u=>u.split("/")[0]);return i&&p.length>0?{include:p,presetDef:c.presetDef,watch:s,orca:!0}:(i&&d.info("\u2139\uFE0F Orca needs at least one local backend (panes are backend-only) \u2014 running in-process instead."),{presetDef:c.presetDef,watch:s,orca:!1})},ae=(e,r)=>{g.setInteractive();let a=z(e,r);g.addOption(a.flags,!0),g.print(),d.info("\u2139\uFE0F Prefer a short name? Save this selection as a devPreset and run `infra-kit dev <name>`.")},te=async(e,r)=>{let a=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!0});return g.setInteractive(),g.addOption(r,!0),a||g.addOption("--no-watch",!0),g.print(),{preset:r,watch:a,orca:!1}},A=" manual",ne=async(e,r,a=ee)=>{if(r.presets.length===0)return S(e,r,a);let n=await e.select({message:"\u{1F680} Start from a preset, or configure manually?",choices:[...r.presets.map(t=>({name:t,value:t})),new U(" "),{name:"Manual (custom)\u2026",value:A}]});return n===A?S(e,r,a):te(e,n)},ke=async(e=V,r=b(m.cwd()))=>ne(e,await T(r));export{A as MANUAL_CHOICE,G as WIZARD_ORCA_VAR,Z as auditManualPlan,V as defaultPrompts,T as gatherWizardModel,L as loadBackends,ke as runDevWizard,ne as runWizardFlow};
|
|
2
|
+
//# sourceMappingURL=dev-wizard-run-4XJYZTCO.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as g,B as h,C as i,D as j,E as k,F as l,G as m,u as a,v as b,w as c,x as d,y as e,z as f}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=env-load-
|
|
1
|
+
import{A as g,B as h,C as i,D as j,E as k,F as l,G as m,u as a,v as b,w as c,x as d,y as e,z as f}from"./chunk-QSIWRM6A.js";import"./chunk-MYUZOXKA.js";import"./chunk-X33OD35Q.js";import"./chunk-MFAFQVTW.js";import"./chunk-SK3GYE2K.js";import"./chunk-I23MDR4X.js";import"./chunk-QWVLAZ6N.js";export{e as DOPPLER_MAX_OUTPUT_BYTES,j as assertDopplerOutputSize,h as assertTokenScope,f as buildDopplerChildEnv,a as buildEnvLoadFileLines,g as downloadEnvSecrets,d as envLoad,m as envLoadMcpTool,l as parseDopplerSecretsJson,b as resolveEnvLoadRoots,k as shellSingleQuote,i as translateDopplerDownloadError,c as writeEnvLoadFile};
|
|
2
|
+
//# sourceMappingURL=env-load-L3FLJR4O.js.map
|
package/dist/update-check.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{p as i}from"./chunk-MH37P7W4.js";import"./chunk-AWFGP6GY.js";import{a as t}from"./chunk-
|
|
1
|
+
import{p as i}from"./chunk-MH37P7W4.js";import"./chunk-AWFGP6GY.js";import{a as t}from"./chunk-SK3GYE2K.js";import"./chunk-I23MDR4X.js";import a from"node:fs";import o from"node:process";import{fileURLToPath as s}from"node:url";var m=r=>{let n=r.indexOf("--parent-pid");if(n===-1)return;let e=Number(r[n+1]);return Number.isInteger(e)&&e>0?e:void 0},p=()=>a.realpathSync(s(new URL("./cli.js",import.meta.url))),d=async()=>{await i(t.version,{selfRealPath:p(),parentPid:m(o.argv)})};d().catch(()=>{o.exitCode=0});
|
|
2
2
|
//# sourceMappingURL=update-check.js.map
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "infra-kit",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.17.1",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "git+https://github.com/ArthurSaenz/infra-kit.git",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"@inquirer/input": "^5.1.6",
|
|
27
27
|
"@inquirer/password": "^5.2.2",
|
|
28
28
|
"@inquirer/select": "^5.2.5",
|
|
29
|
-
"@slip-stream-kit/config": "^0.
|
|
29
|
+
"@slip-stream-kit/config": "^0.17.1",
|
|
30
30
|
"chalk": "^6.0.0",
|
|
31
31
|
"chokidar": "^5.0.0",
|
|
32
32
|
"commander": "^15.0.0",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"zx": "^8.8.5"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@slip-stream-kit/eslint-plugin": "0.
|
|
44
|
+
"@slip-stream-kit/eslint-plugin": "0.17.1",
|
|
45
45
|
"@types/aws-lambda": "^8.10.163",
|
|
46
46
|
"@types/react": "19.3.0",
|
|
47
47
|
"@wl/eslint-config": "0.1.0",
|
package/dist/chunk-R6MPHCEI.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{P as p,S as w,ca as C,d as f,f as u,ga as g}from"./chunk-4GXRGHU3.js";import{p as b}from"./chunk-I23MDR4X.js";import{a as A,b as D}from"./chunk-QWVLAZ6N.js";var H=()=>{let e="",t=[],r=!1;return{start(n){e=n,t=[],r=!1},setInteractive(){r=!0},addOption(n,o){t.push({flag:n,value:o})},formatOptions(){return t.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} "${n.value}"`).filter(Boolean).join(" ")},snapshot(){return t.length===0?null:{formattedOptions:this.formatOptions()}},print(){!r||t.length===0||!e||p.info(`\u{1F4DF} Equivalent command:
|
|
2
|
-
pnpm exec infra-kit ${e} ${this.formatOptions()}
|
|
3
|
-
`)},reset(){e="",t=[],r=!1}}},x=H();import{isAbsolute as $,resolve as I}from"node:path";import M from"node:process";var E=null,y=null,K=e=>{E=[...e],y=M.cwd()},q=new Set(["--yes","-y"]),B=(e,t)=>{let r=[...e];for(let[n,o]of r.entries())o==="-C"&&r[n+1]!==void 0&&!$(r[n+1])?r[n+1]=I(t,r[n+1]):o.startsWith("-C")&&o.length>2&&!o.startsWith("--")&&!$(o.slice(2))&&(r[n]=`-C${I(t,o.slice(2))}`);return r},T=()=>{if(E===null||y===null)return["--yes"];let e=B(E.slice(2),y);return e.some(r=>q.has(r))?e:[...e,"--yes"]};import _ from"node:process";var J=27,L=e=>e===null?"an interactive prompt was reached under --json, which never prompts":`an interactive prompt was reached in agent mode (${e==="flag"?"--agent":"INFRA_KIT_AGENT / CLAUDECODE"}), where there is no human to answer it`,W=e=>`${e===void 0?"pass the value explicitly instead of relying on the prompt":`pass --${e}`} on the re-run`,z=e=>{if(typeof e=="object"&&"value"in e)return e.value;let t=typeof e=="object"?e.refuse:void 0,{source:r}=f;throw new g(t===void 0?{status:"refused",agentMode:r}:{status:"argument_required",argument:t,agentMode:r},2,{operation:"interactive prompt",remediation:W(t),stderrExcerpt:L(r)})},j=async(e,t)=>{let r=new AbortController,{whenHeadless:n="refuse",...o}=t??{},i={...o,signal:r.signal};if(u())return z(n);if(!_.stdin.isTTY)return e(i);let m=_.stdin,P=d=>{d.length===1&&d[0]===J&&r.abort()};A();try{let d=e(i);return m.isPaused()&&m.resume(),m.on("data",P),await d}finally{m.removeListener("data",P),D()}};import U from"@inquirer/confirm";import Y from"node:process";var a=class extends Error{constructor(t="Operation cancelled by the operator"){super(t),this.name="CommandDeclinedError"}},fe=e=>e instanceof a;var N=(e,t,r=T())=>{let{source:n}=f;throw new g({status:"confirmation_required",message:e,plan:t,rerun:r,agentMode:n},2,{operation:"confirm before running",remediation:n===null?"pass `--yes` to confirm, or drop `--json` to be prompted":`show the plan to the human, then re-run \`infra-kit ${r.join(" ")}\` to confirm`,stderrExcerpt:"confirmation required and nobody to ask"})},G=async(e,t,r={})=>{!e&&u()&&N(t,r.plan,r.rerun);let n=e?!0:await j(o=>U({message:t},o),{whenHeadless:"refuse"});if(e||x.setInteractive(),!n){if(r.throwOnDecline)throw new a;p.info("Operation cancelled. Exiting..."),Y.exit(0)}};import h from"node:fs/promises";import l from"node:path";import{z as s}from"zod";var c=class extends Error{env;constructor(t,r=null){super(t),this.name="EnvAuthError",this.env=r}};var V="tokens.json",v=1,R=384,F=448,Q=s.object({version:s.literal(v).default(v),envs:s.record(s.string().min(1),s.string().min(1))}).strict(),k=async()=>{let e=await C();return l.join(l.dirname(e.userProject),V)},S=async()=>{let e=await k(),t;try{t=await h.readFile(e,"utf-8")}catch{return null}let r;try{r=JSON.parse(t)}catch(o){throw new c(`Invalid JSON in the token store at ${w(e)}: ${o.message}
|
|
4
|
-
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`)}let n=Q.safeParse(r);if(!n.success)throw new c(`Invalid token store at ${w(e)}: ${s.prettifyError(n.error)}
|
|
5
|
-
Fix or delete the file, then re-add the token with \`infra-kit env-token-set <env>\`.`);return n.data},O=async e=>{let t=await k(),r=l.dirname(t),n=l.dirname(r),o=l.dirname(n);for(let i of[o,n,r])await h.mkdir(i,{recursive:!0,mode:F}),await h.chmod(i,F);b(t,`${JSON.stringify(e,null,2)}
|
|
6
|
-
`,R),await h.chmod(t,R)};var X=async e=>{let t=await S();await O({version:v,envs:{...t?.envs,...e}})},Z=async e=>{let t=await S();if(!t||!(e in t.envs))return;let r={...t.envs};delete r[e],await O({version:v,envs:r})};export{x as a,fe as b,K as c,T as d,j as e,N as f,G as g,c as h,k as i,S as j,X as k,Z as l};
|
|
7
|
-
//# sourceMappingURL=chunk-R6MPHCEI.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/command-echo/command-echo.ts", "../src/lib/parsed-argv/parsed-argv.ts", "../src/lib/prompts/escapable-context.ts", "../src/lib/command-echo/confirm-or-exit.ts", "../src/lib/errors/command-declined-error.ts", "../src/lib/env-tokens/env-tokens.ts", "../src/lib/errors/env-auth-error.ts"],
|
|
4
|
-
"sourcesContent": ["import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let cliPath = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Bind the echo to the command about to run, and clear the previous one's recording.\n *\n * `cliPath` must be the argv Commander actually parsed (`release create`), which is why the ONLY\n * caller is program.ts's `preAction` hook, feeding it `commandPath(actionCommand)`. Commands used to\n * name themselves here, and that is precisely how the printed line rotted: they passed the flat\n * `release-create`, which stopped being a command the day the flat aliases were dropped, so the\n * \"equivalent command\" we told the user to retype no longer parsed. Commander is the only thing that\n * knows the real path, so it is the only thing allowed to say it.\n */\n start(path: string): void {\n cliPath = path\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n *\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input.\n *\n * Silent without a bound `cliPath`: the only caller that binds one is Commander's `preAction`, so an\n * unbound echo means the handler was called off the CLI (a test, an in-process caller), where a\n * `pnpm exec` line would be nonsense. Printing a path-less `pnpm exec infra-kit --yes` would be\n * worse than printing nothing.\n */\n print(): void {\n if (!isInteractive || options.length === 0 || !cliPath) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${cliPath} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n cliPath = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import { isAbsolute, resolve } from 'node:path'\nimport process from 'node:process'\n\n/**\n * The argv Commander actually parsed for this run \u2014 captured by `entry/cli.ts` at the one place it\n * hands an argv to `parseAsync`, the interactive-menu re-entry included. Commands that need to name\n * their own invocation (a `confirmation_required` refusal's `rerun`) read it here instead of\n * `process.argv`, which the menu path never rewrites.\n */\n\nlet parsedArgv: readonly string[] | null = null\nlet launchCwd: string | null = null\n\n/**\n * Record the full node-style argv (`[node, script, ...args]`) handed to `parseAsync`, and the cwd it\n * was typed in \u2014 read NOW because the `-C` chdir in `preAction` runs later, and a relative `-C` only\n * means anything against this directory.\n */\nexport const setParsedArgv = (argv: readonly string[]): void => {\n parsedArgv = [...argv]\n launchCwd = process.cwd()\n}\n\nconst YES_FLAGS = new Set(['--yes', '-y'])\n\n/**\n * Make every `-C <dir>` in `args` absolute against `cwd`, in place. Commander accepts both\n * `-C dir` and `-Cdir`; both are handled so the re-run is cwd-independent whichever way it was typed.\n */\nconst absolutizeChangeDir = (args: string[], cwd: string): string[] => {\n const out = [...args]\n\n for (const [index, token] of out.entries()) {\n if (token === '-C' && out[index + 1] !== undefined && !isAbsolute(out[index + 1] as string)) {\n out[index + 1] = resolve(cwd, out[index + 1] as string)\n } else if (token.startsWith('-C') && token.length > 2 && !token.startsWith('--') && !isAbsolute(token.slice(2))) {\n out[index] = `-C${resolve(cwd, token.slice(2))}`\n }\n }\n\n return out\n}\n\n/**\n * The argv an agent re-runs to confirm what this run refused: the captured user args with `--yes`\n * appended and any relative `-C` made absolute, so the next Bash call may run from any cwd.\n *\n * Appending is safe: no leaf uses `passThroughOptions` or `--`, and the only variadic option\n * (`--project <names...>`) stops at `--yes`. An argv that already carries `--yes`/`-y` is returned\n * as-is \u2014 a second copy would be noise, and a confirm that fired despite it is not this function's\n * problem to hide.\n *\n * @example\n * // captured: ['node', 'infra-kit', '-C', 'app', 'release', 'remove', '1.2.3', '--json'], cwd /w\n * rerunArgv() // ['-C', '/w/app', 'release', 'remove', '1.2.3', '--json', '--yes']\n */\nexport const rerunArgv = (): string[] => {\n if (parsedArgv === null || launchCwd === null) return ['--yes']\n\n const args = absolutizeChangeDir(parsedArgv.slice(2), launchCwd)\n\n const alreadyConfirmed = args.some((token) => {\n return YES_FLAGS.has(token)\n })\n\n return alreadyConfirmed ? args : [...args, '--yes']\n}\n", "import type { Buffer } from 'node:buffer'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport type { AgentModeSource } from 'src/lib/agent-mode'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\n\nimport { acquireStdin, releaseStdin } from './stdin-ref'\n\n/**\n * Structural mirror of `@inquirer/type`'s `Context` \u2014 the second argument every\n * `@inquirer/*` prompt takes. Declared here rather than imported because\n * `@inquirer/core` and `@inquirer/type` are transitive dependencies of this\n * package, not direct ones (only the four prompt packages are).\n */\nexport interface PromptContext {\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n clearPromptOnDone?: boolean\n signal?: AbortSignal\n}\n\n/**\n * What this call site does when there is no human: refuse, refuse NAMING the argument that would have\n * answered the prompt, or answer with a fixed value.\n *\n * - `'refuse'` \u2014 throw `{ status: 'refused' }`: the site has no single argument to name.\n * - `{ refuse: 'version' }` \u2014 throw `{ status: 'argument_required', argument: 'version' }`: the\n * agent is told exactly what to pass on the re-run. The name is the CLI flag / tool field without\n * its dashes; G8 (`headless-policy-guards`) checks it exists on every owning tool's schema.\n * - `{ value: T }` \u2014 answer with `value`, no throw.\n *\n * There is no `'unreachable'` any more: that was a claim about the retired server's schema making a\n * field required, and no schema stands between a Bash-driven agent and this prompt.\n */\nexport type HeadlessPolicy<T> = 'refuse' | { refuse: string } | { value: T }\n\n/** {@link withEscape}'s options: the prompt context, plus this site's headless policy. */\nexport type EscapeOptions<T> = PromptContext & { whenHeadless?: HeadlessPolicy<T> }\n\nconst ESC_BYTE = 0x1b\n\n// Widening the existing options object rather than adding a third parameter: six call sites already\n// pass a `PromptContext` (`entry/cli.ts`, `env-load`, `env-token-set`, and the wizard's shared\n// context used by three prompts), all of them `{ output: process.stderr }` for documented reasons \u2014\n// `env-token-set.ts:64-68` notes that some env commands run inside `$(\u2026)`, where a prompt on stdout\n// would leave the user typing a credential into a captured stream. A third parameter would have\n// forced every one of them to grow a positional `undefined`.\n//\n// Optional, and the default is `'refuse'`. That default is safe for the same reason the guard exists\n// at all: under `isAgentMode()` nobody is at the keyboard, so no prompt at any site can return a\n// usable answer, and refusing removes no\n// capability that exists. It is what CLI-only sites (the palette, the dev wizard, `env-token-set`)\n// keep, because they face a real human.\n//\n// It is NOT what an agent-reachable site may keep. There, omitting `whenHeadless` is indistinguishable\n// from never having considered the question, so G7 (`every-inquirer-site-is-escapable`) requires the\n// answer to be written out \u2014 `'refuse'` included.\n//\n// What the default is NOT is *correct* everywhere \u2014 that distinction is the whole point of the\n// parameter. `worktrees-add` documents a `false` fallback for agents in its own schema, so a refusal\n// there is right-outcome-by-accident at best and a regression at worst. The type cannot tell those\n// apart; G6 (description-to-policy) and G8 (argument-to-schema) are what check the answers,\n// because a wrong answer here compiles and can never fail a test on its own.\nconst headlessExcerpt = (source: AgentModeSource): string => {\n if (source === null) return 'an interactive prompt was reached under --json, which never prompts'\n\n return `an interactive prompt was reached in agent mode (${source === 'flag' ? '--agent' : 'INFRA_KIT_AGENT / CLAUDECODE'}), where there is no human to answer it`\n}\n\nconst headlessRemediation = (argument: string | undefined): string => {\n const passIt =\n argument === undefined ? 'pass the value explicitly instead of relying on the prompt' : `pass --${argument}`\n\n return `${passIt} on the re-run`\n}\n\nconst resolveHeadless = <T>(policy: HeadlessPolicy<T>): T => {\n if (typeof policy === 'object' && 'value' in policy) return policy.value\n\n const argument = typeof policy === 'object' ? policy.refuse : undefined\n const { source } = agentMode\n\n throw new StructuredRefusalError(\n argument === undefined\n ? { status: 'refused', agentMode: source }\n : { status: 'argument_required', argument, agentMode: source },\n 2,\n {\n operation: 'interactive prompt',\n remediation: headlessRemediation(argument),\n stderrExcerpt: headlessExcerpt(source),\n },\n )\n}\n\n/**\n * Run an `@inquirer/*` prompt with Esc bound to cancellation. On Esc the prompt rejects with an\n * `AbortPromptError`, which `entry/cli.ts` already catches at the top level -> \"Operation\n * cancelled.\" -> exit 0.\n *\n * The listener attaches only on a real interactive terminal. `isTTY` alone is NOT a sufficient\n * guard \u2014 see lib/agent-mode for why `stdio: 'inherit'` defeats it.\n */\n// The cancel path is entirely pre-existing plumbing: an `AbortController`'s signal goes into the\n// prompt context, `@inquirer/core` rejects with an `AbortPromptError` when it fires, and that name\n// is already in `CANCELLATION_ERROR_NAMES` (lib/errors/is-prompt-cancellation). All this adds is\n// the thing that calls `abort()`.\n//\n// DETECTION \u2014 a raw `data` listener that aborts iff the chunk is exactly one `0x1b` byte.\n// Deliberately NOT readline `keypress`: that delivers a lone Esc only after its escape-sequence\n// timeout (~523ms measured), and the `escapeCodeTimeout` dial that would shorten it is\n// process-global and first-armer-wins \u2014 a second `emitKeypressEvents` call on `process.stdin` is\n// SILENTLY IGNORED, so the dial degrades to a no-op with no error and no failing test. The raw\n// listener costs ~24ms and touches no global state. Arrow keys (`\\x1b[B`, 3 bytes) and Alt combos\n// (`\\x1bb`, 2 bytes) are ignored because they are LONGER \u2014 no parsed key field is involved. Node\n// `data` listeners broadcast, so this one does not steal bytes from readline: arrows and Enter keep\n// working while it is attached.\n//\n// FALSE POSITIVES are a non-issue: there is no routine source of a lone-`0x1b` chunk. Focus events\n// (`\\x1b[I`/`\\x1b[O`), bracketed paste (`\\x1b[200~`) and mouse reports (`\\x1b[M\u2026`) are all\n// multi-byte, and inquirer enables none of them.\n//\n// FALSE NEGATIVE \u2014 measured and accepted: a COALESCED Esc (`\"\\x1bx\"` arriving in ONE chunk, i.e.\n// Esc immediately followed by another key) is silently dropped and the prompt stays open. The fix\n// would be Ink's 20ms deferred abort \u2014 hold the lone Esc, cancel it if a follow-up chunk lands.\n// That is a logged NON-GOAL; do not pre-build it.\nexport const withEscape = async <T>(\n run: (context: PromptContext) => Promise<T>,\n base?: EscapeOptions<T>,\n): Promise<T> => {\n const controller = new AbortController()\n // `whenHeadless` is ours, not inquirer's \u2014 split it off so it never reaches a prompt's context.\n const { whenHeadless = 'refuse', ...promptBase } = base ?? {}\n const context: PromptContext = { ...promptBase, signal: controller.signal }\n\n // Keyed on `isHeadless()`. `!isTTY` deliberately does NOT ride along: a piped-but-human\n // run (`infra-kit worktrees add > log.txt`) has no TTY and still deserves its prompt, and the two\n // conditions were only ever collapsed here because both merely skipped the Esc listener. Now that\n // this branch decides an ANSWER rather than just a listener, conflating them would refuse prompts\n // no agent is waiting on. `release-picker.ts` keeps its own `!isTTY` clause for its own reason.\n //\n // `--json` joins because a prompt is stdout traffic on a stream a machine is parsing, and because\n // `release-picker`/`source-picker` already treat `--json` as never-prompt \u2014 this makes the 20 sites\n // agree with those two.\n if (isHeadless()) return resolveHeadless(whenHeadless)\n\n if (!process.stdin.isTTY) return run(context)\n\n const input = process.stdin\n\n const onData = (chunk: Buffer) => {\n if (chunk.length === 1 && chunk[0] === ESC_BYTE) controller.abort()\n }\n\n // STDIN OWNERSHIP \u2014 this is the seam that keeps stdin alive for inquirer, which refs\n // nothing itself. It must sit BELOW the early return above: a non-TTY run never reads\n // stdin, so acquiring there would ref a handle nobody reads and hang the process. See\n // lib/prompts/stdin-ref for why an unref'd stdin kills a prompt with exit 13.\n acquireStdin()\n\n try {\n // Attach after the prompt has built its readline interface. Cheap ordering defence\n // only \u2014 there is no race today: readline attaches its own consumer synchronously\n // and `data` events are async.\n //\n // INSIDE the `try`, both of them: `run` is caller-supplied and `@inquirer/core` runs\n // synchronously up to readline construction, so a SYNCHRONOUS throw here would skip a\n // `finally` placed any lower \u2014 leaking the ref and hanging the CLI, which is the exact\n // failure this module exists to prevent.\n const pending = run(context)\n\n // Explicit, because `on('data')` alone is NOT enough to start the flow: `Readable` resumes on a\n // new `data` listener only when `flowing !== false`, and the palette's teardown now pauses stdin\n // (tui/boot.tsx) so a prompt opened after an Ink screen inherits `flowing === false`. Esc would be\n // silently dead. It happens to work anyway today \u2014 `run()` above builds inquirer's readline, whose\n // constructor resumes the stream \u2014 but that is an undocumented side effect of a TRANSITIVE\n // dependency, and the ordering it relies on is the very thing the comment below reserves the right\n // to change. One idempotent call is cheaper than that coupling.\n if (input.isPaused()) input.resume()\n\n input.on('data', onData)\n\n return await pending\n } finally {\n // Non-negotiable: the dev wizard runs ~5 prompts back to back, so a leaked\n // listener would abort the next one.\n input.removeListener('data', onData)\n // Same `finally` as the listener teardown, and for the same reason: every exit path\n // (answer, Esc abort, throw) must give the ref back, or node never exits.\n releaseStdin()\n }\n}\n", "/**\n * @fileoverview\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (`--yes`, the argv a `confirmation_required`\n * refusal hands back) the prompt is skipped and execution proceeds. Otherwise, with no human to ask \u2014 agent mode, or `--json`, whose\n * stdout a machine is parsing \u2014 it throws a `confirmation_required` refusal\n * carrying the argv that confirms (preview-then-execute, no new flag). Otherwise\n * it prompts the user, marks the echo as interactive, and exits cleanly if the\n * user declines.\n *\n * Esc aborts the prompt (via `withEscape`) rather than answering it \u2014 the caller\n * sees an `AbortPromptError`, which every command's boundary already treats as a\n * clean back-out through `isPromptCancellation`. That is deliberately NOT the same\n * as declining: a decline is an answer of \"no\" and takes the `process.exit(0)` path\n * below, whereas Esc means \"I never answered\".\n *\n * Unlike every other prompt in the CLI this one renders to STDOUT, not stderr \u2014\n * left as-is, since changing it would move confirmation text out of the stream\n * callers have always read it from.\n *\n * The `process.exit(0)` only runs on the interactive-decline path: headless\n * callers refuse above it, so a `--json` document is never cut short by it.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nimport confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { agentMode, isHeadless } from 'src/lib/agent-mode'\nimport { CommandDeclinedError } from 'src/lib/errors/command-declined-error'\nimport { StructuredRefusalError } from 'src/lib/errors/structured-refusal-error'\nimport { logger } from 'src/lib/logger'\nimport { rerunArgv } from 'src/lib/parsed-argv'\nimport { withEscape } from 'src/lib/prompts/escapable-context'\n\nimport { commandEcho } from './command-echo'\n\nexport interface ConfirmOrExitOptions {\n /**\n * The structured form of what `message` renders, handed back verbatim in the\n * `confirmation_required` payload so an agent can show the human WHAT it is\n * about to confirm without parsing prose. JSON-safe and secret-free \u2014 it is\n * emitted to stdout. Sites with no structured plan pass nothing.\n */\n plan?: unknown\n /**\n * Throw {@link CommandDeclinedError} on a decline instead of `process.exit(0)`.\n *\n * **Defaults to false, and must stay that way.** Seven commands call this\n * helper; flipping the default would change the exit semantics of all of them\n * at once, inside a change whose tests cover none of them.\n *\n * Opt in when the command has already acquired something that needs releasing\n * by the time it prompts \u2014 `process.exit` skips every `finally`, so for those\n * commands the decline path is precisely where a resource leaks. The caller\n * owns catching it and exiting 0: a decline is a successful outcome.\n */\n throwOnDecline?: boolean\n /**\n * The argv that confirms, when it must carry more than this run's own argv plus `--yes` \u2014 e.g.\n * the content hash the human is approving. Defaults to `rerunArgv()`.\n */\n rerun?: string[]\n}\n\n/**\n * Throw the `confirmation_required` refusal an agent (or a `--json` run) gets in place of a confirm\n * prompt: the message, the site's plan, the argv that confirms, and the source. Exit 2 \u2014 nothing ran.\n *\n * Exported for the one confirm site that is not `confirmOrExit` (`lib/release-deploy/confirm-deploy`),\n * so both speak the same shape.\n */\n// Thrown from HERE, not from `withEscape`'s headless branch, because it needs what only a confirm\n// site has: the message, the plan, and the knowledge that `--yes` is the answer. Callers key it on\n// `isHeadless()`, never on `confirmedCommand`, so their `--yes` short-circuit stays as it was for\n// agent and human alike.\nexport const refuseUnconfirmed = (message: string, plan?: unknown, rerun: string[] = rerunArgv()): never => {\n const { source } = agentMode\n\n throw new StructuredRefusalError({ status: 'confirmation_required', message, plan, rerun, agentMode: source }, 2, {\n operation: 'confirm before running',\n remediation:\n source === null\n ? 'pass `--yes` to confirm, or drop `--json` to be prompted'\n : `show the plan to the human, then re-run \\`infra-kit ${rerun.join(' ')}\\` to confirm`,\n stderrExcerpt: 'confirmation required and nobody to ask',\n })\n}\n\nexport const confirmOrExit = async (\n confirmedCommand: boolean | undefined,\n message: string,\n options: ConfirmOrExitOptions = {},\n): Promise<void> => {\n if (!confirmedCommand && isHeadless()) refuseUnconfirmed(message, options.plan, options.rerun)\n\n const answer = confirmedCommand\n ? true\n : await withEscape(\n (context) => {\n return confirm({ message }, context)\n },\n // Unreachable headless: the guard above already refused every agent / `--json` run that got\n // here without `confirmedCommand`. Written out anyway \u2014 G7 requires every reachable site to\n // answer, and `'refuse'` is the answer that costs nothing if the guard above ever moves.\n { whenHeadless: 'refuse' },\n )\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n if (options.throwOnDecline) {\n throw new CommandDeclinedError()\n }\n\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n", "/**\n * The operator answered \"no\" at a confirmation prompt.\n *\n * Deliberately NOT an {@link OperationError}: nothing failed. It is also not a prompt\n * cancellation \u2014 Esc means \"I never answered\" and has its own handling, while this means\n * \"I answered, and the answer was no.\" Callers that opt in via `throwOnDecline` are\n * responsible for catching it and exiting 0.\n */\n// It exists so a command that acquired a resource before prompting \u2014 a scratch worktree, a temp\n// directory, a lock \u2014 can unwind through its own `finally` blocks and release it, instead of\n// `confirmOrExit` calling `process.exit(0)` and skipping every one of them.\n//\n// That distinction is load-bearing rather than stylistic. In a plan -> confirm -> apply design,\n// declining is a first-class expected outcome, not an edge case, so the most ordinary non-happy\n// path is exactly the one that would leak.\nexport class CommandDeclinedError extends Error {\n constructor(message = 'Operation cancelled by the operator') {\n super(message)\n this.name = 'CommandDeclinedError'\n }\n}\n\n/** Narrow an unknown catch binding to a decline. */\nexport const isCommandDeclined = (error: unknown): error is CommandDeclinedError => {\n return error instanceof CommandDeclinedError\n}\n", "// DEFAULT import, deliberately \u2014 the same reason config-bootstrap.ts documents: the module is used as\n// `fs.readFile(...)` / `fs.mkdir(...)` so every call is a property lookup on the live module object,\n// which is what `vi.spyOn(fs, \u2026)` patches. A named import (`import { readFile }`) is bound at import\n// time and the spy silently does NOT intercept it \u2014 the assertion goes green while the real call\n// still hits disk. Do not \"modernize\" this import.\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\nimport { atomicWriteFileSync } from 'src/lib/constants'\nimport { EnvAuthError } from 'src/lib/errors/env-auth-error'\nimport { getInfraKitConfigPaths } from 'src/lib/infra-kit-config'\nimport { tildify } from 'src/lib/path-display'\n\n/**\n * Basename of the token store. A SIBLING of the layer-3 `infra-kit.json`, never a key inside it:\n * `getInfraKitConfig` only ever globs the three hardcoded `infra-kit.json` paths and its schema is\n * `.strict()`, so an unknown key throws at the LAYER parse and bricks every command on every pinned\n * version. A sibling file is structurally invisible to that loader \u2014 `config-bootstrap.ts` already\n * relies on exactly this for its `.example.jsonc`. That invisibility is the blast-radius guarantee:\n * a corrupt `tokens.json` can only break the readers below, never `worktrees-list`.\n */\nconst TOKEN_STORE_FILE = 'tokens.json'\n\n/** Schema version of the on-disk store. Bump only alongside a migration. */\nconst TOKEN_STORE_VERSION = 1\n\n/** Mode of `tokens.json` itself \u2014 owner read/write only. It holds live credentials. */\nconst TOKEN_FILE_MODE = 0o600\n\n/** Mode of every directory on the way to the store \u2014 owner-only traversal. */\nconst TOKEN_DIR_MODE = 0o700\n\n/**\n * The store's OWN schema: `{ version?: 1, envs: { <env>: <token> } }`. Deliberately NOT derived from\n * `infraKitConfigObject`: this file is not a merge layer, so `.strict()` here is free (a typo is a\n * loud error in three readers, not a bricked CLI).\n */\n// HAND-AUTHORABILITY IS THE CONSTRAINT THIS SHAPE IS CHOSEN FOR, and two earlier fields were\n// dropped for it \u2014 do not re-add either without re-deciding that:\n//\n// - `version` is OPTIONAL (defaulted to 1) because a store typed by a human carries no version\n// key, and a store the CLI refuses to read is a store the human cannot write.\n// - `repoRoot` is GONE, and with it the refusal that compared it against the current checkout.\n// That guard was real: the store directory is keyed on `path.basename(mainRepoRoot)`, so\n// `~/work/api` and `~/oss/api` share ONE token directory and repo B could load (and then\n// overwrite) repo A's credentials. It was removed anyway, knowingly: it also made the CLI refuse\n// every hand-written store, which carries no such field. Hand-authorability wins; the\n// basename-collision risk is ACCEPTED. A weakened version of the guard (warn-and-continue, or\n// \"only check when present\") is NOT the compromise here \u2014 it would re-introduce the same refusal\n// for anyone who did write the field. If you want the guard back, key the store directory on\n// something collision-free instead.\nconst tokenStoreSchema = z\n .object({\n version: z.literal(TOKEN_STORE_VERSION).default(TOKEN_STORE_VERSION),\n envs: z.record(z.string().min(1), z.string().min(1)),\n })\n .strict()\n\n/** The parsed `tokens.json` shape: `{ version, envs }` \u2014 `version` defaulted to 1 when absent on disk. */\nexport type TokenStore = z.infer<typeof tokenStoreSchema>\n\n/**\n * Absolute path to the per-project token store: `~/.infra-kit/projects/<repo>/tokens.json`.\n *\n * Derived from {@link getInfraKitConfigPaths} rather than re-deriving the home/projects/repo chain \u2014\n * that resolver already keys the directory off the MAIN repo root (so every worktree of a repo shares\n * one store) and memoizes the two `git rev-parse` spawns.\n *\n * @example\n * await getTokenStorePath() // => '/Users/arthur/.infra-kit/projects/infra-kit/tokens.json'\n */\nexport const getTokenStorePath = async (): Promise<string> => {\n const paths = await getInfraKitConfigPaths()\n\n return path.join(path.dirname(paths.userProject), TOKEN_STORE_FILE)\n}\n\n/**\n * Read the token store, or `null` when it does not exist.\n *\n * ABSENCE IS NOT AN ERROR \u2014 a fresh machine has no store, and every caller must be able to say \"no\n * tokens yet\" without a try/catch. The two things that DO throw are malformed JSON and a schema\n * mismatch: both are states only a human can fix, so both are loud.\n *\n * @example\n * const store = await readTokenStore()\n * store?.envs.dev // => 'dp.st.dev.xxxx' | undefined\n * // no file on disk => null\n * // garbage on disk => throws 'Invalid token store at ~/.infra-kit/projects/api/tokens.json: \u2026'\n */\nexport const readTokenStore = async (): Promise<TokenStore | null> => {\n const storePath = await getTokenStorePath()\n\n let raw: string\n\n try {\n raw = await fs.readFile(storePath, 'utf-8')\n } catch {\n return null\n }\n\n // Every refusal below is an EnvAuthError, not a plain Error. A broken store is the MOST durable\n // env-auth failure there is \u2014 only a human can fix it \u2014 and downstream callers classify on that\n // CLASS (see EnvAuthError's doc). `env` is null: no ONE environment is at fault.\n let parsedRaw: unknown\n\n try {\n parsedRaw = JSON.parse(raw)\n } catch (err) {\n throw new EnvAuthError(\n `Invalid JSON in the token store at ${tildify(storePath)}: ${(err as Error).message}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n const result = tokenStoreSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new EnvAuthError(\n `Invalid token store at ${tildify(storePath)}: ${z.prettifyError(result.error)}\\n` +\n `Fix or delete the file, then re-add the token with \\`infra-kit env-token-set <env>\\`.`,\n )\n }\n\n return result.data\n}\n\n/**\n * Persist the store atomically at 0600, tightening every directory on the way to it to 0700.\n *\n * The chmods are not belt-and-braces: the config bootstrap already seeds\n * `~/.infra-kit/projects/<repo>/` at the default umask (0755), so an EXISTING directory is\n * world-readable and `mkdir`'s mode argument is a no-op for it. The same holds for the file \u2014 a\n * hand-written `tokens.json` is 0644 \u2014 so the modes of the whole credential path are (re)asserted on\n * EVERY write, not only on the writes that created it. Self-healing by construction: a plain\n * `env-token-set` is enough to fix a store a human typed.\n *\n * @example\n * await writeTokenStore({ version: 1, envs: { dev: 'dp.st.dev.x' } })\n * // ~/.infra-kit/projects/api/tokens.json -rw-------\n * // ~/.infra-kit/projects/api/ drwx------\n */\nexport const writeTokenStore = async (store: TokenStore): Promise<void> => {\n const storePath = await getTokenStorePath()\n\n const projectDir = path.dirname(storePath)\n const projectsDir = path.dirname(projectDir)\n const userConfigDir = path.dirname(projectsDir)\n\n for (const dir of [userConfigDir, projectsDir, projectDir]) {\n await fs.mkdir(dir, { recursive: true, mode: TOKEN_DIR_MODE })\n await fs.chmod(dir, TOKEN_DIR_MODE)\n }\n\n atomicWriteFileSync(storePath, `${JSON.stringify(store, null, 2)}\\n`, TOKEN_FILE_MODE)\n\n // The rename above already lands a fresh 0600 inode, but the mode of a credential file is not a\n // thing to leave to the umask that happened to be in effect \u2014 assert it outright.\n await fs.chmod(storePath, TOKEN_FILE_MODE)\n}\n\n/**\n * Add or replace one environment's token, read-modify-write, stamping the current `version`. Inherits\n * {@link readTokenStore}'s refusals: a corrupt store is never silently overwritten.\n *\n * @example\n * await setToken('dev', 'dp.st.dev.xxxxxxxx')\n * // tokens.json => { version: 1, envs: { dev: 'dp.st.dev.xxxxxxxx' } }\n */\nexport const setToken = async (env: string, token: string): Promise<void> => {\n await setTokens({ [env]: token })\n}\n\n/**\n * Add or replace several environments' tokens in ONE read-modify-write, so a bulk import never leaves\n * the store half-written between two of its entries.\n *\n * @example\n * await setTokens({ dev: 'dp.st.dev.x', arthur: 'dp.st.arthur.y' })\n * // tokens.json => { version: 1, envs: { \u2026existing, dev: 'dp.st.dev.x', arthur: 'dp.st.arthur.y' } }\n */\nexport const setTokens = async (tokens: Record<string, string>): Promise<void> => {\n const existing = await readTokenStore()\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs: { ...existing?.envs, ...tokens },\n })\n}\n\n/**\n * Drop one environment's token. A no-op when the store (or the key) is absent \u2014 removing something\n * that is not there is the state the caller asked for.\n *\n * Removing a token here does NOT revoke it in Doppler; callers say so.\n *\n * @example\n * await removeToken('dev')\n * // tokens.json => { version: 1, envs: {} }\n */\nexport const removeToken = async (env: string): Promise<void> => {\n const existing = await readTokenStore()\n\n if (!existing || !(env in existing.envs)) return\n\n const envs = { ...existing.envs }\n\n delete envs[env]\n\n await writeTokenStore({\n version: TOKEN_STORE_VERSION,\n envs,\n })\n}\n", "/**\n * The DURABLE, USER-FIXABLE env-auth failure \u2014 as a TYPE rather than a string.\n *\n * Throw this (or a subclass) \u2014 never a plain `Error` \u2014 for anything a user must fix before\n * env-load can work: no token minted, a corrupt token store, a foreign token store.\n * `DopplerAuthError extends EnvAuthError` for the subset that is specifically \"Doppler refused the\n * token we sent\".\n *\n * @example\n * // no token minted for this env (integrations/doppler/token-resolver.ts)\n * throw new EnvAuthError(buildMissingTokenMessage('dev', storePath), 'dev')\n * @example\n * // the token store itself is unusable \u2014 no single env is at fault, so `env` stays null\n * throw new EnvAuthError(`Invalid JSON in the token store at ${storePath} \u2026`)\n */\n// WHY THIS EXISTS (and why it is deliberately NOT a Doppler type): every consumer of the auth\n// channel needs to classify a failure by its CLASS, not by re-deriving the answer from a message\n// some other module owns \u2014 and it has to be throwable from EVERY module that can produce the\n// class. `lib/env-tokens` (the store) is a layer BELOW `integrations/doppler`, so a Doppler-owned\n// base type could not be thrown there without a layering inversion and an import cycle. Hence a\n// neutral base here in `lib/errors`.\nexport class EnvAuthError extends Error {\n /**\n * The env (= Doppler config) whose token is at fault, or `null` when the failure is not attributable\n * to ONE env (a corrupt or foreign token store breaks every env at once). `null` is honest: do NOT\n * invent an env to fill it \u2014 the consumer names the env it was TRYING to load, which it already\n * knows.\n */\n readonly env: string | null\n\n constructor(message: string, env: string | null = null) {\n super(message)\n this.name = 'EnvAuthError'\n this.env = env\n }\n}\n\n/**\n * The TYPE GUARD every consumer of the auth channel classifies on \u2014 the single question \"is this a\n * durable, user-fixable env-auth failure?\", answered by the error's CLASS and never by its text.\n *\n * Deliberately WIDER than `isDopplerAuthError`: that one means \"Doppler refused us\", which is only\n * one of the durable failures \u2014 a missing token never reaches Doppler at all, and a corrupt store\n * never reaches the resolver.\n *\n * @example\n * isEnvAuthFailure(new EnvAuthError('No Doppler service token for env \"dev\".', 'dev')) // => true\n * isEnvAuthFailure(new DopplerAuthError('dev', 'revoked')) // => true (subclass)\n * isEnvAuthFailure(new Error('connect ETIMEDOUT')) // => false (transient)\n */\nexport const isEnvAuthFailure = (error: unknown): error is EnvAuthError => {\n return error instanceof EnvAuthError\n}\n"],
|
|
5
|
-
"mappings": "oKAOA,IAAMA,EAAoB,IAAM,CAC9B,IAAIC,EAAU,GACVC,EAA2B,CAAC,EAC5BC,EAAgB,GAEpB,MAAO,CAWL,MAAMC,EAAoB,CACxBH,EAAUG,EACVF,EAAU,CAAC,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C,KAAKN,EAAE,cAAca,EAAO,KAAK,CAAC;AAAA,sFAEhF,EAGF,OAAOA,EAAO,IAChB,EAiBaC,EAAkB,MAAOC,GAAqC,CACzE,IAAMT,EAAY,MAAML,EAAkB,EAEpCe,EAAaZ,EAAK,QAAQE,CAAS,EACnCW,EAAcb,EAAK,QAAQY,CAAU,EACrCE,EAAgBd,EAAK,QAAQa,CAAW,EAE9C,QAAWE,IAAO,CAACD,EAAeD,EAAaD,CAAU,EACvD,MAAMR,EAAG,MAAMW,EAAK,CAAE,UAAW,GAAM,KAAMrB,CAAe,CAAC,EAC7D,MAAMU,EAAG,MAAMW,EAAKrB,CAAc,EAGpCsB,EAAoBd,EAAW,GAAG,KAAK,UAAUS,EAAO,KAAM,CAAC,CAAC;AAAA,EAAMlB,CAAe,EAIrF,MAAMW,EAAG,MAAMF,EAAWT,CAAe,CAC3C,EAsBO,IAAMwB,EAAY,MAAOC,GAAkD,CAChF,IAAMC,EAAW,MAAMC,EAAe,EAEtC,MAAMC,EAAgB,CACpB,QAASC,EACT,KAAM,CAAE,GAAGH,GAAU,KAAM,GAAGD,CAAO,CACvC,CAAC,CACH,EAYaK,EAAc,MAAOC,GAA+B,CAC/D,IAAML,EAAW,MAAMC,EAAe,EAEtC,GAAI,CAACD,GAAY,EAAEK,KAAOL,EAAS,MAAO,OAE1C,IAAMM,EAAO,CAAE,GAAGN,EAAS,IAAK,EAEhC,OAAOM,EAAKD,CAAG,EAEf,MAAMH,EAAgB,CACpB,QAASC,EACT,KAAAG,CACF,CAAC,CACH",
|
|
6
|
-
"names": ["createCommandEcho", "cliPath", "options", "isInteractive", "path", "flag", "value", "opt", "logger", "commandEcho", "isAbsolute", "resolve", "process", "parsedArgv", "launchCwd", "setParsedArgv", "argv", "YES_FLAGS", "absolutizeChangeDir", "args", "cwd", "out", "index", "token", "rerunArgv", "process", "ESC_BYTE", "headlessExcerpt", "source", "headlessRemediation", "argument", "resolveHeadless", "policy", "agentMode", "StructuredRefusalError", "withEscape", "run", "base", "controller", "whenHeadless", "promptBase", "context", "isHeadless", "process", "input", "onData", "chunk", "acquireStdin", "pending", "releaseStdin", "confirm", "process", "CommandDeclinedError", "message", "isCommandDeclined", "error", "refuseUnconfirmed", "message", "plan", "rerun", "rerunArgv", "source", "agentMode", "StructuredRefusalError", "confirmOrExit", "confirmedCommand", "options", "isHeadless", "answer", "withEscape", "context", "confirm", "commandEcho", "CommandDeclinedError", "logger", "process", "fs", "path", "z", "EnvAuthError", "message", "env", "TOKEN_STORE_FILE", "TOKEN_STORE_VERSION", "TOKEN_FILE_MODE", "TOKEN_DIR_MODE", "tokenStoreSchema", "z", "getTokenStorePath", "paths", "getInfraKitConfigPaths", "path", "readTokenStore", "storePath", "raw", "fs", "parsedRaw", "err", "EnvAuthError", "tildify", "result", "writeTokenStore", "store", "projectDir", "projectsDir", "userConfigDir", "dir", "atomicWriteFileSync", "setTokens", "tokens", "existing", "readTokenStore", "writeTokenStore", "TOKEN_STORE_VERSION", "removeToken", "env", "envs"]
|
|
7
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|