infra-kit 0.3.4 → 0.3.6

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.
@@ -0,0 +1,2 @@
1
+ import{b as Z}from"./chunk-TPVXMJ7N.js";import{render as Ie}from"ink";import ue from"node:process";import{Box as J,Text as R,useApp as he,useInput as we,useWindowSize as xe}from"ink";import{useEffect as ee,useState as F}from"react";import{useMemo as de,useState as V}from"react";var D=(e,t)=>{let[r,m]=V(""),[n,a]=V(0),o=de(()=>{let f=r.trim().toLowerCase();return f?e.filter(d=>t(d).toLowerCase().includes(f)):e},[e,r,t]),c=Math.min(n,Math.max(0,o.length-1));return{filtered:o,activeIndex:c,query:r,handleNavigation:(f,d)=>{let b=o.length;return d.upArrow?(b>0&&a((c-1+b)%b),!0):d.downArrow?(b>0&&a((c+1)%b),!0):d.backspace||d.delete?(m(r.slice(0,-1)),a(0),!0):f&&!d.ctrl&&!d.meta?(m(r+f),a(0),!0):!1},clearQuery:()=>r?(m(""),a(0),!0):!1}};var pe=()=>{},q=(e,t=0)=>e<5?{mode:"tiny",chromeRows:0,groups:!1}:e<10?{mode:"compact",chromeRows:4+t,groups:!1}:{mode:"full",chromeRows:6+t,groups:!0},fe=(e,t,r,m)=>{let n=0,a;for(let o=t;o<r;o+=1){let c=e[o];if(!c)break;let w=m(c),T=w!==void 0&&w!==a;n+=1+(T?1:0)+(T&&o>t?1:0),a=w}return n},j=(e,t,r,m)=>{let n=t;for(;n<e.length&&fe(e,t,n+1,m)<=r;)n+=1;return n},$=(e,t,r,m,n)=>{let a=n?.groupOf??pe,o=Math.max(0,m-(n?.chromeRows??6)),c=Math.min(t,r);for(;r>=j(e,c,o,a)&&c<r;)c+=1;let w=j(e,c,o,a);return{visible:e.slice(c,w),start:c,hiddenBefore:c,hiddenAfter:Math.max(0,e.length-w)}};import{jsx as I,jsxs as G}from"react/jsx-runtime";var te=e=>{let{items:t,onSubmit:r,onCancel:m,required:n=!0,allowSelectAll:a=!0}=e,o=Te,c=t.reduce((s,x)=>Math.max(s,x.label.length),0),{exit:w}=he(),{rows:T}=xe(),{filtered:f,activeIndex:d,query:b,handleNavigation:v,clearQuery:M}=D(t,ge),[B,O]=F(()=>new Set),[E,h]=F(!1),[S,p]=F(0),[l,C]=F(!1);ee(()=>{l&&w()},[l,w]);let _=q(T,1),y=$(f,S,d,T,{chromeRows:_.chromeRows});ee(()=>{y.start!==S&&p(y.start)},[y.start,S]);let k=s=>{O(x=>{let g=new Set(x);return g.has(s)?g.delete(s):g.add(s),g})},H=()=>{O(s=>t.every(g=>s.has(g.value))?new Set:new Set(t.map(g=>g.value)))},i=()=>{m(),C(!0)},u=()=>{if(n&&B.size===0){h(!0);return}r([...B]),C(!0)};return we((s,x)=>{if(!l){if(x.ctrl&&s==="c"){i();return}if(x.escape){M()||i();return}if(x.ctrl&&s==="a"){a&&H();return}if(s===" "){let g=f[d];g&&k(g.value);return}if(x.return){u();return}v(s,x)}}),l?null:_.mode==="tiny"?I(R,{dimColor:!0,wrap:"truncate",children:o.tiny}):G(J,{flexDirection:"column",children:[_.mode==="full"?I(R,{dimColor:!0,wrap:"truncate",children:o.hint}):null,G(J,{children:[I(R,{color:"cyan",children:o.prompt}),I(R,{wrap:"truncate-start",children:b})]}),G(J,{flexDirection:"column",marginTop:_.mode==="full"?1:0,children:[f.length===0?I(R,{dimColor:!0,wrap:"truncate",children:o.empty}):null,y.hiddenBefore>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenBefore} above`}):null,y.visible.map((s,x)=>{let g=y.start+x===d,me=B.has(s.value);return G(R,{color:g?"green":void 0,wrap:"truncate",children:[g?"\u203A ":" ",me?"[x] ":"[ ] ",s.label.padEnd(c)," ",I(R,{dimColor:!0,children:s.description??""})]},s.value)}),y.hiddenAfter>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenAfter} below`}):null]}),E?I(R,{dimColor:!0,wrap:"truncate",children:o.requiredHint}):null]})};function ge(e){return`${e.label} ${e.description??""}`}var Te={hint:"filter \xB7 \u2191\u2193 move \xB7 Space toggle \xB7 Ctrl-A all \xB7 Enter submit \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick branches",requiredHint:"select at least one",more:"\u2026"};import{Box as U,Text as W,useApp as be,useInput as Se,useWindowSize as Ce}from"ink";import{useEffect as re,useState as ne}from"react";import{jsx as L,jsxs as z}from"react/jsx-runtime";var oe=e=>{let{items:t,onSelect:r,onCancel:m}=e,n=ve,a=t.reduce((p,l)=>Math.max(p,l.label.length),0),{exit:o}=be(),{rows:c}=Ce(),{filtered:w,activeIndex:T,query:f,handleNavigation:d,clearQuery:b}=D(t,Pe),[v,M]=ne(0),[B,O]=ne(!1);re(()=>{B&&o()},[B,o]);let E=q(c),h=$(w,v,T,c,{chromeRows:E.chromeRows});re(()=>{h.start!==v&&M(h.start)},[h.start,v]);let S=()=>{m(),O(!0)};return Se((p,l)=>{if(!B){if(l.ctrl&&p==="c"){S();return}if(l.escape){b()||S();return}if(l.return){let C=w[T];C&&(r(C.value),O(!0));return}d(p,l)}}),B?null:E.mode==="tiny"?L(W,{dimColor:!0,wrap:"truncate",children:n.tiny}):z(U,{flexDirection:"column",children:[E.mode==="full"?L(W,{dimColor:!0,wrap:"truncate",children:n.hint}):null,z(U,{children:[L(W,{color:"cyan",children:n.prompt}),L(W,{wrap:"truncate-start",children:f})]}),z(U,{flexDirection:"column",marginTop:E.mode==="full"?1:0,children:[w.length===0?L(W,{dimColor:!0,wrap:"truncate",children:n.empty}):null,h.hiddenBefore>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenBefore} above`}):null,h.visible.map((p,l)=>{let C=h.start+l===T;return z(W,{color:ye(p.type,C),wrap:"truncate",children:[C?"\u203A ":" ",p.label.padEnd(a)," ",L(W,{dimColor:!0,children:p.description??""})]},p.value)}),h.hiddenAfter>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenAfter} below`}):null]})]})};function ye(e,t){return e==="hotfix"?"red":t?"green":void 0}function Pe(e){return`${e.label} ${e.description??""}`}var ve={hint:"type to filter \xB7 \u2191\u2193 move \xB7 Enter select \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick a branch",more:"\u2026"};import{Box as Q,Text as P,useApp as Be,useInput as Oe,useWindowSize as Re}from"ink";import{useEffect as ie,useMemo as Ae,useState as K}from"react";import{jsx as A,jsxs as N}from"react/jsx-runtime";var se=e=>{let{items:t,onSelect:r,onCancel:m,onSuspend:n}=e,a={hint:Ee(!!n),prompt:"\u276F ",empty:"No matching commands",tiny:"terminal too short \u2014 resize to pick a command",more:"\u2026"},o=24,{exit:c,suspendTerminal:w}=Be(),{rows:T}=Re(),[f,d]=K(""),[b,v]=K(0),[M,B]=K(0),[O,E]=K(!1);ie(()=>{O&&c()},[O,c]);let h=Ae(()=>{let i=f.trim().toLowerCase();return i?t.filter(u=>`${u.name} ${u.description}`.toLowerCase().includes(i)):t},[t,f]),S=Math.min(b,Math.max(0,h.length-1)),p=q(T),l=$(h,M,S,T,{chromeRows:p.chromeRows,groupOf:p.groups?i=>i.group:void 0});ie(()=>{l.start!==M&&B(l.start)},[l.start,M]);let C=()=>{m(),E(!0)},_=()=>{n&&w(n).catch(()=>{})},y=i=>i==="c"||i==="d"?(C(),!0):i==="z"?(_(),!0):!1,k=i=>{let u=h.length;u>0&&v((S+i+u)%u)};if(Oe((i,u)=>{if(!O&&!(u.ctrl&&y(i))){if(u.escape){d(""),v(0);return}if(u.return){let s=h[S];s&&(r(s.name),E(!0));return}if(u.upArrow){k(-1);return}if(u.downArrow){k(1);return}if(u.backspace||u.delete){d(f.slice(0,-1)),v(0);return}i&&!u.ctrl&&!u.meta&&(d(f+i),v(0))}}),O)return null;if(p.mode==="tiny")return A(P,{dimColor:!0,wrap:"truncate",children:a.tiny});let H="";return N(Q,{flexDirection:"column",children:[p.mode==="full"?A(P,{dimColor:!0,wrap:"truncate",children:a.hint}):null,N(Q,{children:[A(P,{color:"cyan",children:a.prompt}),A(P,{wrap:"truncate-start",children:f})]}),N(Q,{flexDirection:"column",marginTop:p.mode==="full"?1:0,children:[h.length===0?A(P,{dimColor:!0,wrap:"truncate",children:a.empty}):null,l.hiddenBefore>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenBefore} above`}):null,l.visible.map((i,u)=>{let s=l.start+u===S,x=p.groups&&i.group!==H;return H=i.group,N(Q,{flexDirection:"column",children:[x&&u>0?A(P,{children:" "}):null,x?A(P,{color:"yellow",wrap:"truncate",children:`\u2014 ${i.group} \u2014`}):null,N(P,{color:s?"green":void 0,wrap:"truncate",children:[s?"\u203A ":" ",i.name.padEnd(o)," ",A(P,{dimColor:!0,children:i.description})]})]},i.name)}),l.hiddenAfter>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenAfter} below`}):null]})]})},le={suspend:"filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear \xB7 Ctrl-D quit \xB7 Ctrl-Z suspend",plain:"type to filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear \xB7 Ctrl-D quit"},Ee=e=>e?le.suspend:le.plain;import ae from"node:process";var ce=(e={})=>{let t=e.platform??ae.platform,r=e.kill??((m,n)=>{ae.kill(m,n)});if(t!=="win32")try{r(0,"SIGSTOP")}catch{}};import{jsx as X}from"react/jsx-runtime";var Y=async e=>{let t=Z(),{waitUntilExit:r}=Ie(e,{stdout:t,exitOnCtrlC:!1,interactive:!!t.isTTY});try{await r()}catch{}finally{ue.stdin.ref()}},st=async e=>{let t=null;return await Y(X(se,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null},onSuspend:ue.platform==="win32"?void 0:()=>{ce()}})),t},at=async e=>{let t=null;return await Y(X(oe,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null}})),t},ct=async(e,t)=>{let r=null;return await Y(X(te,{items:e,required:t?.required,allowSelectAll:t?.allowSelectAll,onSubmit:m=>{r=m},onCancel:()=>{r=null}})),r};export{ct as runBranchMultiPicker,at as runBranchPicker,st as runCommandPalette};
2
+ //# sourceMappingURL=boot-FHXCA53R.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/tui/boot.tsx", "../src/tui/screens/branch-multi-picker.tsx", "../src/tui/hooks/use-list-filter.ts", "../src/tui/screens/palette-window.ts", "../src/tui/screens/branch-picker.tsx", "../src/tui/screens/command-palette.tsx", "../src/tui/suspend.ts"],
4
- "sourcesContent": ["import { render } from 'ink'\nimport process from 'node:process'\nimport type { ReactElement } from 'react'\n\nimport type { BranchPickerItem } from 'src/lib/prompts/types'\n\nimport { safeStderr } from './safe-stderr'\nimport { BranchMultiPicker } from './screens/branch-multi-picker'\nimport { BranchPicker } from './screens/branch-picker'\nimport { CommandPalette } from './screens/command-palette'\nimport { suspendForeground } from './suspend'\nimport type { PaletteItem } from './types'\n\n/**\n * Entry point for the Ink TUI. This module (and everything under `src/tui/`) is\n * the ONLY place allowed to import `ink`/`react`; it is reached exclusively via a\n * dynamic `await import('src/tui/boot')` from the TTY branch of entry/cli.ts, so\n * React never loads on the MCP / `--json` / non-TTY paths. Build splitting keeps\n * it in a separate lazy chunk (see scripts/build.js).\n */\n\n/**\n * Render an Ink element to stderr and resolve once it tears down. Frames are\n * written to stderr so stdout stays clean for the command that runs afterwards\n * (mirrors the previous Inquirer menu).\n *\n * Ink `unref()`s process.stdin when it tears down raw mode on exit. That ref is\n * process-wide and never restored, so the next consumer of stdin \u2014 the Inquirer\n * prompt the selected command opens (e.g. the worktrees-remove checkbox), or a\n * SECOND Ink render in the same process (the bare-menu palette \u2192 picker hop) \u2014\n * reads from an unref'd handle that no longer keeps the event loop alive. Once\n * the command's git/gh subprocesses settle, the loop drains mid-prompt, Node\n * flags entry/cli.ts's top-level await as unsettled, and the process exits with\n * code 13 (the prompt dies on arrival). Re-ref stdin on BOTH the resolve and the\n * reject path so it holds the loop while the next prompt is reading; an idle\n * ref'd stdin does not block exit, so non-interactive follow-up commands still\n * terminate normally. Every render must go through here so the re-ref is never\n * skipped.\n */\nconst renderToStderr = async (element: ReactElement): Promise<void> => {\n const stdout = safeStderr()\n const { waitUntilExit } = render(element, {\n stdout,\n // Ink's default is `exitOnCtrlC: true`, which intercepts the 0x03 byte in its own App and calls\n // `handleExit()` BEFORE it ever reaches `useInput`. That makes every screen's own ctrl+c branch\n // dead code, and \u2014 worse \u2014 it tears down on the CURRENT frame, so `log.done()` freezes the drawn\n // command list into the scrollback instead of erasing it (Esc, which goes through the screens'\n // own quit path, erases correctly; Ctrl-C left a corpse). Every screen rendered here already\n // handles ctrl+c itself, so hand them the key.\n exitOnCtrlC: false,\n // Ink's default is `!isInCi && stdout.isTTY`. We drop the isInCi term: a developer with CI\n // exported in their shell would otherwise get a NON-interactive Ink on a real terminal, and Ink\n // skips ALL terminal management in that mode \u2014 `beginSuspend` returns before it can drop raw mode\n // or erase the frame, and `endSuspend` never redraws. Ctrl-Z would hand the shell a raw-mode tty\n // with a stranded frame and a hidden cursor, and `fg` would come back to nothing. Whether we own\n // the terminal is a question about the tty, and only about the tty.\n interactive: Boolean(stdout.isTTY),\n })\n\n try {\n await waitUntilExit()\n } catch {\n // Swallow a teardown rejection: the caller reports cancellation via its own\n // captured sentinel (which stays at its initial value), not via a throw.\n } finally {\n process.stdin.ref()\n }\n}\n\n/**\n * Render the command palette and resolve to the chosen command name, or `null`\n * if the user cancels. A Ctrl-Z suspends the job and resolves nothing \u2014 the same\n * palette redraws, filter and all, when the user brings it back with `fg`.\n */\nexport const runCommandPalette = async (items: PaletteItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <CommandPalette\n items={items}\n onSelect={(name) => {\n selected = name\n }}\n onCancel={() => {\n selected = null\n }}\n // This module is the platform authority: `undefined` tells the palette that suspending is\n // impossible here, so it neither binds Ctrl-Z nor advertises it in the footer. (`suspendForeground`\n // guards win32 again on its own \u2014 the palette itself must stay free of `process`.)\n onSuspend={\n process.platform === 'win32'\n ? undefined\n : () => {\n suspendForeground()\n }\n }\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable single-select branch picker and resolve to the chosen\n * value, or `null` if the user cancels.\n */\nexport const runBranchPicker = async (items: BranchPickerItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <BranchPicker\n items={items}\n onSelect={(value) => {\n selected = value\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable multi-select branch picker and resolve to the chosen\n * values, or `null` if the user cancels. The captured variable starts as `null`\n * and is only assigned an array in `onSubmit`, so a cancel is distinguishable\n * from an empty submit.\n */\nexport const runBranchMultiPicker = async (\n items: BranchPickerItem[],\n opts?: { required?: boolean; allowSelectAll?: boolean },\n): Promise<string[] | null> => {\n let selected: string[] | null = null\n\n await renderToStderr(\n <BranchMultiPicker\n items={items}\n required={opts?.required}\n allowSelectAll={opts?.allowSelectAll}\n onSubmit={(values) => {\n selected = values\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchMultiPickerProps {\n items: BranchPickerItem[]\n /** Called with the selected item values; the app then exits. */\n onSubmit: (values: string[]) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n /** When true (default), Enter with an empty selection is ignored. */\n required?: boolean\n /** When true (default), Ctrl-A toggles select-all across all items. */\n allowSelectAll?: boolean\n}\n\n/**\n * Searchable multi-select branch picker rendered with Ink. Same filter/move/cancel\n * behaviour as `BranchPicker`, plus a selection `Set` keyed by item *value* so the\n * selection survives filter changes. Space toggles the active row; Ctrl-A toggles\n * select-all across all items; Enter submits the selected values.\n *\n * The list is WINDOWED to the terminal height for the same safety reason as the\n * palette and the single picker: an overflowing Ink frame corrupts the cursor and\n * welds later output onto the transcript. See `palette-window.ts`.\n */\nexport const BranchMultiPicker = (props: BranchMultiPickerProps) => {\n const { items, onSubmit, onCancel, required = true, allowSelectAll = true } = props\n\n const T = BRANCH_MULTI_PICKER_TEXT\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // Selection keyed by value so it persists across filter changes.\n const [selected, setSelected] = useState<Set<string>>(() => {\n return new Set()\n })\n const [showRequiredHint, setShowRequiredHint] = useState(false)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n // The extra chrome row is this screen's `select at least one` hint: counted unconditionally, because\n // it appears on a keystroke and a budget that shrinks mid-frame is a budget that overflows.\n const layout = listLayout(rows, 1)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const toggleValue = (value: string) => {\n setSelected((prev) => {\n const next = new Set(prev)\n\n if (next.has(value)) {\n next.delete(value)\n } else {\n next.add(value)\n }\n\n return next\n })\n }\n\n const toggleSelectAll = () => {\n setSelected((prev) => {\n // Clear only when every item (all, not just filtered) is already selected.\n const allSelected = items.every((item) => {\n return prev.has(item.value)\n })\n\n if (allSelected) {\n return new Set()\n }\n\n return new Set(\n items.map((item) => {\n return item.value\n }),\n )\n })\n }\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n const submit = () => {\n if (required && selected.size === 0) {\n setShowRequiredHint(true)\n\n return\n }\n\n onSubmit([...selected])\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: the typed filter first, the picker only once\n // there is no filter left to clear. It never touches `selected` \u2014 a filter keystroke is\n // not a selection, so clearing one must not discard the other. Stage 2 discards it, as before.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.ctrl && input === 'a') {\n if (allowSelectAll) {\n toggleSelectAll()\n }\n\n return\n }\n\n if (input === ' ') {\n const active = filtered[activeIndex]\n\n if (active) {\n toggleValue(active.value)\n }\n\n return\n }\n\n if (key.return) {\n submit()\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const isChecked = selected.has(item.value)\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width. Ink reads the wrap style off the\n // OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={isActive ? 'green' : undefined} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {isChecked ? '[x] ' : '[ ] '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n {showRequiredHint ? (\n <Text dimColor wrap=\"truncate\">\n {T.requiredHint}\n </Text>\n ) : null}\n </Box>\n )\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_MULTI_PICKER_TEXT = {\n hint: 'filter \u00B7 \u2191\u2193 move \u00B7 Space toggle \u00B7 Ctrl-A all \u00B7 Enter submit \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick branches',\n requiredHint: 'select at least one',\n more: '\u2026',\n}\n", "import type { Key } from 'ink'\nimport { useMemo, useState } from 'react'\n\ninterface ListFilter<T> {\n /** Items matching the current query (all items when the query is empty). */\n filtered: T[]\n /** Active row index, always clamped into `filtered`'s bounds. */\n activeIndex: number\n /** Current filter query. */\n query: string\n /**\n * Handle the shared navigation/filter keys (\u2191\u2193 wrap-around, backspace/delete,\n * printable chars). Returns true when the key was consumed so the caller can\n * `return` early; false leaves the key for the component's own handlers.\n */\n handleNavigation: (input: string, key: Key) => boolean\n /**\n * Stage 1 of the Esc ladder: clears a non-empty query (back to the first row) and\n * returns true. Returns false when the query is already empty \u2014 the boolean IS the\n * ladder, and a false tells the caller there is nothing left to cancel but the screen.\n *\n * Deliberately NOT folded into `handleNavigation`: the two pickers want different\n * stage-2 actions, so the escape branch belongs to each screen, not to the shared handler.\n */\n clearQuery: () => boolean\n}\n\n/**\n * Shared list-filter state for the branch pickers: substring filtering,\n * wrap-around \u2191\u2193 movement, and query editing. Extracted so each `useInput`\n * handler stays under the sonarjs cognitive-complexity \u226415 gate.\n */\nexport const useListFilter = <T>(items: T[], toText: (item: T) => string): ListFilter<T> => {\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return toText(item).toLowerCase().includes(q)\n })\n }, [items, query, toText])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n const handleNavigation = (input: string, key: Key): boolean => {\n const n = filtered.length\n\n if (key.upArrow) {\n // `+ n` sidesteps JS negative modulo (e.g. -1 % 5 === -1, not 4).\n if (n > 0) {\n setIndex((activeIndex - 1 + n) % n)\n }\n\n return true\n }\n\n if (key.downArrow) {\n if (n > 0) {\n setIndex((activeIndex + 1) % n)\n }\n\n return true\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return true\n }\n\n // Printable character: append to the filter and reset to the first row.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n\n return true\n }\n\n return false\n }\n\n const clearQuery = (): boolean => {\n if (!query) {\n return false\n }\n\n setQuery('')\n setIndex(0)\n\n return true\n }\n\n return { filtered, activeIndex, query, handleNavigation, clearQuery }\n}\n", "/**\n * Pure viewport arithmetic shared by every Ink list screen (the command palette and both branch\n * pickers): which slice of the (already filtered) list fits the terminal, and how much chrome the\n * screen may spend around it.\n *\n * This is a SAFETY guard, not a readability one. Ink's cleanup walks the cursor upward one line at a\n * time (`ESC[2K ESC[1A` per row) and `ESC[1A` SATURATES AT ROW 0. So the moment a frame is taller than\n * the viewport, the terminal scrolls while Ink draws, the upward walk erases the wrong rows, and the\n * cursor is left parked ABOVE live content \u2014 after which every later write (the session's status\n * footer, the next palette frame) is deposited on top of the transcript. That is the \"welded rows\" bug:\n * `\u276F ` printed over the head of `ERROR: \u2026`, leaving `ROR: \u2026` behind.\n *\n * The invariant this module exists to enforce, for every (columns, rows):\n *\n * rendered frame height < terminal rows\n *\n * Hold that, and Ink never takes its overflow path: `clearTerminal` never fires, `eraseLines` never\n * saturates, the cursor stays below the transcript, and a fresh (cold) Ink instance \u2014 which erases\n * NOTHING before its first frame \u2014 simply appends below the transcript like any other CLI. No new\n * escape bytes required.\n *\n * Two things make the row count knowable at all:\n * - Every list row is rendered `wrap=\"truncate\"`, so one item is always exactly one row. Without that\n * a long description wraps to two rows and this arithmetic silently under-counts (Ink wraps text\n * itself and measures the WRAPPED height, so it, not us, would be right).\n * - Chrome is counted unconditionally, even when a given row is not drawn (see `CHROME_ROWS`). Over-\n * counting shrinks the list; under-counting overflows. Only one of those is a bug.\n *\n * `src/tui/safe-stderr.ts` (the `ESC[3J` byte filter) remains the last-resort backstop for the case\n * this cannot cover \u2014 a SIGWINCH that invalidates a frame's height retroactively.\n */\nimport type { PaletteItem } from '../types'\n\n/**\n * Reads an item's group label. Omitted by the branch pickers, whose lists have no headers at all.\n * (Passed as an accessor rather than constrained with a `{ group?: string }` marker interface: a type\n * whose properties are ALL optional is \"weak\", and TypeScript refuses to match a `BranchPickerItem`\n * against it \u2014 inference silently falls back to the constraint and every field access breaks.)\n */\nexport type GroupOf<T> = (item: T) => string | undefined\n\n/** The slice to render, plus how many rows fell off each end (for the `\u2026 n more` affordances). */\nexport interface ListWindow<T> {\n visible: T[]\n /** Index the window starts at \u2014 the component stores it so the list does not jump between frames. */\n start: number\n hiddenBefore: number\n hiddenAfter: number\n}\n\n/** Back-compat alias: the command palette's window is a window of `PaletteItem`s. */\nexport type PaletteWindow = ListWindow<PaletteItem>\n\n/**\n * Rows a screen spends on everything that is not a list row, counted UNCONDITIONALLY (a `\u2026 n above`\n * that is not drawn today may be drawn on the next keystroke, and re-deriving the budget mid-frame is\n * how you get an off-by-one that only bites on a full list):\n * hint, `\u276F` prompt, the list's `marginTop`, `\u2026 n above`, `\u2026 n below`, and one row of headroom.\n *\n * The headroom row is what makes the frame strictly SHORTER than the viewport: Ink treats a frame\n * exactly as tall as the terminal as fullscreen and clears the screen.\n */\nexport const CHROME_ROWS = 6\n\n/** Compact chrome: the hint and the list's `marginTop` are dropped. Prompt + affordances + headroom. */\nexport const COMPACT_CHROME_ROWS = 4\n\n/** Below this many rows a screen drops its hint, its `marginTop`, and its group headers. */\nexport const COMPACT_BELOW_ROWS = 10\n\n/** Below this many rows no usable list fits at all; the screen renders a single-line notice instead. */\nexport const TINY_BELOW_ROWS = 5\n\n/** How a screen must lay itself out to keep its frame shorter than `rows`. */\nexport type ListLayoutMode = 'full' | 'compact' | 'tiny'\n\nexport interface ListLayout {\n mode: ListLayoutMode\n /** Rows reserved for chrome. Pass to `paletteWindow` as `chromeRows`. */\n chromeRows: number\n /** Whether group headers may be drawn (they cost a row each, so a compact frame drops them). */\n groups: boolean\n}\n\n/** A list with no group headers: every item costs exactly one row. */\nconst NO_GROUPS = (): undefined => {\n return undefined\n}\n\n/**\n * The layout a screen must use at this terminal height. `extraChromeRows` is for chrome a screen has\n * that the others do not \u2014 the multi-picker's `select at least one` hint is the only one today.\n *\n * A `tiny` frame is one truncated line, which is strictly shorter than any terminal of 2+ rows. (At\n * `rows === 1` nothing can be shorter than the viewport; Ink will clear. That is a degenerate terminal,\n * and `safe-stderr` keeps even that harmless.)\n *\n * @example\n * listLayout(24) // => { mode: 'full', chromeRows: 6, groups: true }\n * listLayout(8) // => { mode: 'compact', chromeRows: 4, groups: false }\n * listLayout(8, 1) // => { mode: 'compact', chromeRows: 5, groups: false } (multi-picker)\n * listLayout(4) // => { mode: 'tiny', chromeRows: 0, groups: false }\n */\nexport const listLayout = (rows: number, extraChromeRows = 0): ListLayout => {\n if (rows < TINY_BELOW_ROWS) {\n return { mode: 'tiny', chromeRows: 0, groups: false }\n }\n\n if (rows < COMPACT_BELOW_ROWS) {\n return { mode: 'compact', chromeRows: COMPACT_CHROME_ROWS + extraChromeRows, groups: false }\n }\n\n return { mode: 'full', chromeRows: CHROME_ROWS + extraChromeRows, groups: true }\n}\n\n/**\n * How many rows rendering `items[start..end)` costs: one per item (guaranteed by `wrap=\"truncate\"`),\n * plus, when `groups` is on, one for each group header and one for the blank line between groups (the\n * first rendered group gets a header but no blank \u2014 it mirrors the `showGroup && position > 0` rule in\n * the components). A list whose items carry no `group` never spends a header row.\n */\nconst heightOf = <T>(items: T[], start: number, end: number, groupOf: GroupOf<T>): number => {\n let height = 0\n let previousGroup: string | undefined\n\n for (let index = start; index < end; index += 1) {\n const item = items[index]\n\n if (!item) break\n\n const group = groupOf(item)\n const startsGroup = group !== undefined && group !== previousGroup\n\n height += 1 + (startsGroup ? 1 : 0) + (startsGroup && index > start ? 1 : 0)\n previousGroup = group\n }\n\n return height\n}\n\n/** The last index (exclusive) that still fits `budget` rows when rendering from `start`. */\nconst endThatFits = <T>(items: T[], start: number, budget: number, groupOf: GroupOf<T>): number => {\n let end = start\n\n while (end < items.length && heightOf(items, start, end + 1, groupOf) <= budget) {\n end += 1\n }\n\n return end\n}\n\n/**\n * The window of items to render: the largest slice starting at or after `start` that fits the terminal\n * while still containing `activeIndex`. Scrolls by the minimum needed \u2014 the caller keeps `start` in\n * state, so the list only moves when the cursor would otherwise leave the window.\n *\n * An empty `visible` is a legitimate result on a terminal too short to hold even one row. It is NOT\n * clamped up to one item: forcing a row that does not fit is exactly how the frame overflows and the\n * cursor corruption starts. A screen that gets nothing back renders its `tiny` notice instead \u2014 see\n * `listLayout`.\n *\n * @example\n * const window = paletteWindow(items, 0, 12, 24)\n * window.visible.length // => however many commands fit 18 rows\n * window.hiddenAfter // => the rest, surfaced as '\u2026 n below'\n */\nexport const paletteWindow = <T>(\n items: T[],\n start: number,\n activeIndex: number,\n rows: number,\n opts?: { chromeRows?: number; groupOf?: GroupOf<T> },\n): ListWindow<T> => {\n const groupOf = opts?.groupOf ?? NO_GROUPS\n const budget = Math.max(0, rows - (opts?.chromeRows ?? CHROME_ROWS))\n\n // Scroll up only if the cursor moved above the window; otherwise scroll down just far enough.\n let first = Math.min(start, activeIndex)\n\n while (activeIndex >= endThatFits(items, first, budget, groupOf) && first < activeIndex) {\n first += 1\n }\n\n const end = endThatFits(items, first, budget, groupOf)\n\n return {\n visible: items.slice(first, end),\n start: first,\n hiddenBefore: first,\n hiddenAfter: Math.max(0, items.length - end),\n }\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchPickerProps {\n items: BranchPickerItem[]\n /** Called with the chosen item's value; the app then exits. */\n onSelect: (value: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n}\n\n/**\n * Searchable single-select branch picker rendered with Ink. Mirrors\n * `CommandPalette` minus the group headers: type-to-filter over label +\n * description, \u2191\u2193 wrap-around, Enter selects the active item's *value*.\n *\n * Like the palette, the list is WINDOWED to the terminal height. That is a safety\n * requirement, not a nicety: a repo with ~20 open releases produced a frame taller\n * than an 80x24 window, and an overflowing Ink frame corrupts the cursor and welds\n * the next frame onto the command's own output. See `palette-window.ts`.\n */\nexport const BranchPicker = (props: BranchPickerProps) => {\n const { items, onSelect, onCancel } = props\n\n const T = BRANCH_PICKER_TEXT\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const layout = listLayout(rows)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: a typed filter first, the picker only once\n // there is no filter left to clear. `clearQuery` returning false IS that ladder.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.value)\n setSubmitted(true)\n }\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width (a long branch name would\n // otherwise wrap and make the frame taller than this component believes). Ink reads the wrap\n // style off the OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={labelColor(item.type, isActive)} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Colour for a row's label, derived from the release type. Kept a plain lookup so\n * an unknown/absent type simply falls through to the default (green when active).\n */\nfunction labelColor(type: string | undefined, isActive: boolean): string | undefined {\n if (type === 'hotfix') {\n return 'red'\n }\n\n return isActive ? 'green' : undefined\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_PICKER_TEXT = {\n hint: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter select \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick a branch',\n more: '\u2026',\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useMemo, useState } from 'react'\n\nimport type { PaletteItem } from '../types'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface CommandPaletteProps {\n items: PaletteItem[]\n /** Called with the chosen command name; the app then exits. */\n onSelect: (name: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n /**\n * Stop the foreground job (Ctrl-Z). ABSENT means suspend is impossible on this platform \u2014 the\n * palette stays pure presentation and never inspects `process`; boot.tsx is the platform authority.\n */\n onSuspend?: () => void\n}\n\n/**\n * Fuzzy-ish command picker rendered with Ink. Pure presentation: it receives a\n * flat list of commands (already grouped/ordered by the catalog) and returns the\n * selected name. It never executes anything \u2014 the caller runs the command via\n * the existing Commander path.\n *\n * NOTE: this component sits at exactly the sonarjs cognitive-complexity ceiling (15). Any `if` or\n * `?:` added to its BODY breaks `pnpm run qa` \u2014 which is why the hint is picked by the module-scope\n * `hintFor` below and the control keys by `handleCtrlKey`, rather than inline.\n */\nexport const CommandPalette = (props: CommandPaletteProps) => {\n const { items, onSelect, onCancel, onSuspend } = props\n\n const T = {\n hint: hintFor(Boolean(onSuspend)),\n prompt: '\u276F ',\n empty: 'No matching commands',\n tiny: 'terminal too short \u2014 resize to pick a command',\n more: '\u2026',\n }\n const nameWidth = 24\n\n const { exit, suspendTerminal } = useApp()\n const { rows } = useWindowSize()\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n // First command in the visible window. Kept in state so the list scrolls by the minimum needed\n // instead of jumping every time the cursor moves.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame (Ink's `log.done()` would otherwise\n // freeze the last drawn frame \u2014 the command list \u2014 into the scrollback).\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return `${item.name} ${item.description}`.toLowerCase().includes(q)\n })\n }, [items, query])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n // The slice that fits this terminal, and how much chrome we may spend around it. A frame taller than\n // the viewport corrupts the cursor (see palette-window.ts) \u2014 every row here is budgeted, and every\n // row below is `wrap=\"truncate\"` so one command is always exactly one row.\n const layout = listLayout(rows)\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, {\n chromeRows: layout.chromeRows,\n // A compact frame drops group headers, so they must not be budgeted for either.\n groupOf: layout.groups\n ? (item) => {\n return item.group\n }\n : undefined,\n })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n // Back out with nothing picked (Ctrl-C, or Esc on an empty filter).\n const quit = () => {\n onCancel()\n setSubmitted(true)\n }\n\n // Hand the terminal back to the user's shell until they `fg`.\n //\n // Ink does all the terminal work for us, in the right order and synchronously: `beginSuspend`\n // settles pending frames, erases the list, restores the cursor and drops raw mode BEFORE our\n // callback runs, and on resume `endSuspend` re-arms raw mode and force-redraws THIS SAME LIVE\n // COMPONENT \u2014 so the typed filter survives the suspend. That is why we must NOT set `submitted`\n // here: unmounting would throw the query away and give us a blank palette on return.\n //\n // The `.catch` is the PRIMARY guard, not a backstop \u2014 never simplify it to `void`. Two 0x1a bytes\n // in one read chunk (a double-tap) are both already queued in Ink's input loop, and `pauseInput`\n // only detaches the stdin listener, so the second one still fires \u2014 into a `beginSuspend` that is\n // already suspended, which throws. Harmless (it throws before flipping its own state, and the first\n // suspension still unwinds), but the rejection must be caught: `void` would make it an unhandled\n // rejection that kills the process mid terminal-restore.\n const suspend = () => {\n if (!onSuspend) {\n return\n }\n\n suspendTerminal(onSuspend).catch(() => {\n // See above: a double Ctrl-Z is a no-op, not a crash.\n })\n }\n\n /**\n * Ctrl-C / Ctrl-Z, hoisted OUT of the `useInput` body. Mandatory, not tidiness: that handler sits at\n * cognitive complexity 14, and an inline `if (key.ctrl && input === 'z' && onSuspend)` costs +2 \u2014\n * 16, over the sonarjs ceiling of 15, and `pnpm run qa` goes red.\n *\n * The palette's Ctrl-Z is a BYTE (0x1a), not a signal: Ink holds stdin in raw mode, which clears\n * termios ISIG, so the tty never generates SIGTSTP here at all. We therefore stop the process GROUP\n * ourselves (kill(0), see ../suspend.ts). The session shell's SIGTSTP handler does the opposite \u2014\n * it self-stops with raise('SIGSTOP') (lib/session/run-session.ts) \u2014 and that is CORRECT there,\n * because while a child command holds the foreground the tty is cooked and has already TSTP'd the\n * whole group, leaving only us to follow. DO NOT UNIFY THE TWO.\n */\n const handleCtrlKey = (input: string): boolean => {\n if (input === 'c') {\n quit()\n\n return true\n }\n\n // Ctrl-D is the REPL/shell convention for \"end of input\", and it is UNCONDITIONAL: unlike Esc it\n // is not part of the filter ladder, so it quits with a filter typed as readily as without one.\n // It exists because Esc-on-an-empty-filter ending the session is the one binding a shell user does\n // not expect, and this gives them the key their fingers already reach for without changing Esc.\n if (input === 'd') {\n quit()\n\n return true\n }\n\n if (input === 'z') {\n suspend()\n\n return true\n }\n\n return false\n }\n\n // Move the active row by `delta`, wrapping. The `+ n` sidesteps JS negative modulo\n // (e.g. -1 % 5 === -1, not 4). No-op on an empty list.\n const step = (delta: number) => {\n const n = filtered.length\n\n if (n > 0) {\n setIndex((activeIndex + delta + n) % n)\n }\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n // Ctrl-C quits, Ctrl-Z suspends (see handleCtrlKey). Esc clears a non-empty filter first, and\n // only quits on an empty filter \u2014 the standard REPL/palette split, so the session shell keeps\n // running while the user narrows.\n if (key.ctrl && handleCtrlKey(input)) {\n return\n }\n\n if (key.escape && query) {\n setQuery('')\n setIndex(0)\n\n return\n }\n\n if (key.escape) {\n quit()\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.name)\n setSubmitted(true)\n }\n\n return\n }\n\n if (key.upArrow) {\n step(-1)\n\n return\n }\n\n if (key.downArrow) {\n step(1)\n\n return\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return\n }\n\n // Printable character: append to the filter.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n }\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one command row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n let lastGroup = ''\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START on the input: overflow must eat the head of the filter, never the character\n being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const showGroup = layout.groups && item.group !== lastGroup\n\n lastGroup = item.group\n\n return (\n <Box flexDirection=\"column\" key={item.name}>\n {/* Blank line between groups (not before the first row of the window). */}\n {showGroup && position > 0 ? <Text> </Text> : null}\n {showGroup ? <Text color=\"yellow\" wrap=\"truncate\">{`\u2014 ${item.group} \u2014`}</Text> : null}\n {/* `wrap=\"truncate\"` is load-bearing, not cosmetic: it is what makes \"one command = one\n row\" true at any width, which is what keeps the frame shorter than the viewport. Ink\n reads the wrap style off the OUTER <Text> only \u2014 it squashes the nested <Text> into\n this one's string \u2014 so it must live here. */}\n <Text color={isActive ? 'green' : undefined} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.name.padEnd(nameWidth)} <Text dimColor>{item.description}</Text>\n </Text>\n </Box>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Footer copy. Kept out of the component's `T` because picking between the two is a conditional.\n *\n * Exported so the hint-width guard can measure these strings: they render under `wrap=\"truncate\"`,\n * so a hint of \u226580 columns silently loses its TAIL \u2014 and the tail is where the newest keybinding\n * always lands. `Esc clear/quit` (not `Esc cancel`) is the honest description: Esc pops the filter\n * first and only ends the session once there is nothing left to clear.\n */\nexport const HINTS = {\n suspend: 'filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear/quit \u00B7 Ctrl-D quit \u00B7 Ctrl-Z suspend',\n plain: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear/quit \u00B7 Ctrl-D quit',\n}\n\n/**\n * The footer hint, which advertises Ctrl-Z only where suspending is possible.\n *\n * Module scope for two reasons, both load-bearing. It cannot live in the component: a `?:` in\n * `CommandPalette`'s body pushes it from 15 to 16, over the sonarjs cognitive-complexity ceiling. And\n * it cannot sit above the component either: `@wl/component-file-order` pins this file to\n * imports \u2192 props interface \u2192 component with nothing in between. Below is the only legal home.\n *\n * Both strings are SHORTER than the hint they replace, on purpose \u2014 the footer renders with\n * `wrap=\"truncate\"`, so anything longer silently loses its tail on a narrow terminal, and the tail is\n * exactly where a newly-added key would land.\n *\n * @example\n * hintFor(true).includes('Ctrl-Z') // => true\n */\nconst hintFor = (canSuspend: boolean): string => {\n return canSuspend ? HINTS.suspend : HINTS.plain\n}\n", "import process from 'node:process'\n\n/**\n * Ctrl-Z at the palette, from the process side. React-free on purpose: the palette is pure\n * presentation and must not reach for `node:process`, and this half is worth unit-testing with plain\n * vitest (inject `kill`, assert the signal) rather than through an Ink frame.\n *\n * It lives under `src/tui/` rather than `src/lib/session/` because `boot.tsx` is its only caller and\n * the whole `src/tui/**` tree is the lazily-imported Ink chunk \u2014 the session layer never imports it,\n * and parking it there would drag it into the eager CLI chunk for nothing.\n */\n\n/** Seams for the stop. Production passes nothing; tests inject fakes and assert the signal. */\nexport interface SuspendDeps {\n platform?: NodeJS.Platform\n kill?: (pid: number, signal: NodeJS.Signals) => void\n}\n\n/**\n * Stop the foreground PROCESS GROUP so the user's shell reclaims the tty and prints a prompt.\n * Returns when the job is resumed (`fg` \u2192 SIGCONT): the kill halts JS synchronously, and execution\n * continues at the next statement \u2014 so there is no SIGCONT handler and nothing to re-arm.\n *\n * **pid 0 is the whole process group, and that is load-bearing.** Under `pnpm exec infra-kit`, pnpm's\n * node wrapper shares our pgid and the interactive shell only ever waits on PNPM \u2014 we are a\n * grandchild it never reaps. Stopping only ourselves would leave pnpm blocked in `waitpid`, so the\n * job never reads as stopped, the shell never reclaims the tty, and the terminal wedges with no\n * prompt and no way back. Stopping the group suspends the job as a unit, exactly as the tty's own\n * Ctrl-Z would; on direct-bin invocation it degenerates to a self-stop, so this is one code path.\n *\n * Only ever called from inside Ink's `suspendTerminal`, which has already erased the frame, restored\n * the cursor and dropped raw mode by the time we get here.\n *\n * `bg` is NOT supported: on resume Ink re-arms raw mode, and a `tcsetattr` from a background process\n * group raises SIGTTOU, which stops the job again. Same as vim. Use `fg`.\n *\n * @example\n * const stopped: number[] = []\n * suspendForeground({ platform: 'darwin', kill: (pid) => stopped.push(pid) })\n * stopped // => [0] (the process group, not process.pid)\n */\nexport const suspendForeground = (deps: SuspendDeps = {}): void => {\n const platform = deps.platform ?? process.platform\n const kill =\n deps.kill ??\n ((pid: number, signal: NodeJS.Signals) => {\n process.kill(pid, signal)\n })\n\n // SIGSTOP does not exist on Windows: `process.kill` there goes to uv_kill, which fails with ENOSYS\n // and THROWS. That throw would surface inside an Ink input handler \u2192 the ErrorBoundary \u2192\n // `handleExit(error)` \u2192 the session shell would silently QUIT. And Windows really does reach this\n // code: `sessionGateEnabled` (lib/session/run-session.ts) gates on TTYs only, with no platform\n // check, so Windows Terminal enters the palette like any other. Belt to boot.tsx's braces.\n if (platform === 'win32') {\n return\n }\n\n // No cursor/newline work here, deliberately: Ink's `beginSuspend` has already erased its frame and\n // left the cursor at column 0, so the shell's \"suspended\" line lands on a clean row. Writing a\n // newline first only opens a gratuitous blank gap above it (verified on a real pty).\n try {\n kill(0, 'SIGSTOP')\n } catch {\n // A stop we could not perform must degrade to a no-op, never to a crash: we are called mid\n // terminal-restore, and throwing here would take the session down with the tty half-handed-back.\n }\n}\n"],
5
- "mappings": "wCAAA,OAAS,UAAAA,OAAc,MACvB,OAAOC,OAAa,eCDpB,OAAS,OAAAC,EAAK,QAAAC,EAAM,UAAAC,GAAQ,YAAAC,GAAU,iBAAAC,OAAqB,MAC3D,OAAS,aAAAC,GAAW,YAAAC,MAAgB,QCApC,OAAS,WAAAC,GAAS,YAAAC,MAAgB,QA+B3B,IAAMC,EAAgB,CAAIC,EAAYC,IAA+C,CAC1F,GAAM,CAACC,EAAOC,CAAQ,EAAIL,EAAS,EAAE,EAC/B,CAACM,EAAOC,CAAQ,EAAIP,EAAS,CAAC,EAE9BQ,EAAWT,GAAQ,IAAM,CAC7B,IAAMU,EAAIL,EAAM,KAAK,EAAE,YAAY,EAEnC,OAAKK,EAIEP,EAAM,OAAQQ,GACZP,EAAOO,CAAI,EAAE,YAAY,EAAE,SAASD,CAAC,CAC7C,EALQP,CAMX,EAAG,CAACA,EAAOE,EAAOD,CAAM,CAAC,EAEnBQ,EAAc,KAAK,IAAIL,EAAO,KAAK,IAAI,EAAGE,EAAS,OAAS,CAAC,CAAC,EAmDpE,MAAO,CAAE,SAAAA,EAAU,YAAAG,EAAa,MAAAP,EAAO,iBAjDd,CAACQ,EAAeC,IAAsB,CAC7D,IAAMC,EAAIN,EAAS,OAEnB,OAAIK,EAAI,SAEFC,EAAI,GACNP,GAAUI,EAAc,EAAIG,GAAKA,CAAC,EAG7B,IAGLD,EAAI,WACFC,EAAI,GACNP,GAAUI,EAAc,GAAKG,CAAC,EAGzB,IAGLD,EAAI,WAAaA,EAAI,QACvBR,EAASD,EAAM,MAAM,EAAG,EAAE,CAAC,EAC3BG,EAAS,CAAC,EAEH,IAILK,GAAS,CAACC,EAAI,MAAQ,CAACA,EAAI,MAC7BR,EAASD,EAAQQ,CAAK,EACtBL,EAAS,CAAC,EAE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,GAAS,CAClBF,EAAWE,CACb,EACA,SAAU,IAAM,CACdF,EAAW,IACb,EAIA,UACEH,GAAQ,WAAa,QACjB,OACA,IAAM,CACJM,GAAkB,CACpB,EAER,CACF,EAEOH,CACT,EAMaI,GAAkB,MAAOL,GAAsD,CAC1F,IAAIC,EAA0B,KAE9B,aAAMT,EACJD,EAACe,GAAA,CACC,MAAON,EACP,SAAWO,GAAU,CACnBN,EAAWM,CACb,EACA,SAAU,IAAM,CACdN,EAAW,IACb,EACF,CACF,EAEOA,CACT,EAQaO,GAAuB,MAClCR,EACAS,IAC6B,CAC7B,IAAIR,EAA4B,KAEhC,aAAMT,EACJD,EAACmB,GAAA,CACC,MAAOV,EACP,SAAUS,GAAM,SAChB,eAAgBA,GAAM,eACtB,SAAWE,GAAW,CACpBV,EAAWU,CACb,EACA,SAAU,IAAM,CACdV,EAAW,IACb,EACF,CACF,EAEOA,CACT",
4
+ "sourcesContent": ["import { render } from 'ink'\nimport process from 'node:process'\nimport type { ReactElement } from 'react'\n\nimport type { BranchPickerItem } from 'src/lib/prompts/types'\n\nimport { safeStderr } from './safe-stderr'\nimport { BranchMultiPicker } from './screens/branch-multi-picker'\nimport { BranchPicker } from './screens/branch-picker'\nimport { CommandPalette } from './screens/command-palette'\nimport { suspendForeground } from './suspend'\nimport type { PaletteItem } from './types'\n\n/**\n * Entry point for the Ink TUI. This module (and everything under `src/tui/`) is\n * the ONLY place allowed to import `ink`/`react`; it is reached exclusively via a\n * dynamic `await import('src/tui/boot')` from the TTY branch of entry/cli.ts, so\n * React never loads on the MCP / `--json` / non-TTY paths. Build splitting keeps\n * it in a separate lazy chunk (see scripts/build.js).\n */\n\n/**\n * Render an Ink element to stderr and resolve once it tears down. Frames are\n * written to stderr so stdout stays clean for the command that runs afterwards\n * (mirrors the previous Inquirer menu).\n *\n * Ink `unref()`s process.stdin when it tears down raw mode on exit. That ref is\n * process-wide and never restored, so the next consumer of stdin \u2014 the Inquirer\n * prompt the selected command opens (e.g. the worktrees-remove checkbox), or a\n * SECOND Ink render in the same process (the bare-menu palette \u2192 picker hop) \u2014\n * reads from an unref'd handle that no longer keeps the event loop alive. Once\n * the command's git/gh subprocesses settle, the loop drains mid-prompt, Node\n * flags entry/cli.ts's top-level await as unsettled, and the process exits with\n * code 13 (the prompt dies on arrival). Re-ref stdin on BOTH the resolve and the\n * reject path so it holds the loop while the next prompt is reading; an idle\n * ref'd stdin does not block exit, so non-interactive follow-up commands still\n * terminate normally. Every render must go through here so the re-ref is never\n * skipped.\n */\nconst renderToStderr = async (element: ReactElement): Promise<void> => {\n const stdout = safeStderr()\n const { waitUntilExit } = render(element, {\n stdout,\n // Ink's default is `exitOnCtrlC: true`, which intercepts the 0x03 byte in its own App and calls\n // `handleExit()` BEFORE it ever reaches `useInput`. That makes every screen's own ctrl+c branch\n // dead code, and \u2014 worse \u2014 it tears down on the CURRENT frame, so `log.done()` freezes the drawn\n // command list into the scrollback instead of erasing it (Esc, which goes through the screens'\n // own quit path, erases correctly; Ctrl-C left a corpse). Every screen rendered here already\n // handles ctrl+c itself, so hand them the key.\n exitOnCtrlC: false,\n // Ink's default is `!isInCi && stdout.isTTY`. We drop the isInCi term: a developer with CI\n // exported in their shell would otherwise get a NON-interactive Ink on a real terminal, and Ink\n // skips ALL terminal management in that mode \u2014 `beginSuspend` returns before it can drop raw mode\n // or erase the frame, and `endSuspend` never redraws. Ctrl-Z would hand the shell a raw-mode tty\n // with a stranded frame and a hidden cursor, and `fg` would come back to nothing. Whether we own\n // the terminal is a question about the tty, and only about the tty.\n interactive: Boolean(stdout.isTTY),\n })\n\n try {\n await waitUntilExit()\n } catch {\n // Swallow a teardown rejection: the caller reports cancellation via its own\n // captured sentinel (which stays at its initial value), not via a throw.\n } finally {\n process.stdin.ref()\n }\n}\n\n/**\n * Render the command palette and resolve to the chosen command name, or `null`\n * if the user cancels. A Ctrl-Z suspends the job and resolves nothing \u2014 the same\n * palette redraws, filter and all, when the user brings it back with `fg`.\n */\nexport const runCommandPalette = async (items: PaletteItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <CommandPalette\n items={items}\n onSelect={(name) => {\n selected = name\n }}\n onCancel={() => {\n selected = null\n }}\n // This module is the platform authority: `undefined` tells the palette that suspending is\n // impossible here, so it neither binds Ctrl-Z nor advertises it in the footer. (`suspendForeground`\n // guards win32 again on its own \u2014 the palette itself must stay free of `process`.)\n onSuspend={\n process.platform === 'win32'\n ? undefined\n : () => {\n suspendForeground()\n }\n }\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable single-select branch picker and resolve to the chosen\n * value, or `null` if the user cancels.\n */\nexport const runBranchPicker = async (items: BranchPickerItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <BranchPicker\n items={items}\n onSelect={(value) => {\n selected = value\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable multi-select branch picker and resolve to the chosen\n * values, or `null` if the user cancels. The captured variable starts as `null`\n * and is only assigned an array in `onSubmit`, so a cancel is distinguishable\n * from an empty submit.\n */\nexport const runBranchMultiPicker = async (\n items: BranchPickerItem[],\n opts?: { required?: boolean; allowSelectAll?: boolean },\n): Promise<string[] | null> => {\n let selected: string[] | null = null\n\n await renderToStderr(\n <BranchMultiPicker\n items={items}\n required={opts?.required}\n allowSelectAll={opts?.allowSelectAll}\n onSubmit={(values) => {\n selected = values\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchMultiPickerProps {\n items: BranchPickerItem[]\n /** Called with the selected item values; the app then exits. */\n onSubmit: (values: string[]) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n /** When true (default), Enter with an empty selection is ignored. */\n required?: boolean\n /** When true (default), Ctrl-A toggles select-all across all items. */\n allowSelectAll?: boolean\n}\n\n/**\n * Searchable multi-select branch picker rendered with Ink. Same filter/move/cancel\n * behaviour as `BranchPicker`, plus a selection `Set` keyed by item *value* so the\n * selection survives filter changes. Space toggles the active row; Ctrl-A toggles\n * select-all across all items; Enter submits the selected values.\n *\n * The list is WINDOWED to the terminal height for the same safety reason as the\n * palette and the single picker: an overflowing Ink frame corrupts the cursor and\n * welds later output onto the transcript. See `palette-window.ts`.\n */\nexport const BranchMultiPicker = (props: BranchMultiPickerProps) => {\n const { items, onSubmit, onCancel, required = true, allowSelectAll = true } = props\n\n const T = BRANCH_MULTI_PICKER_TEXT\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // Selection keyed by value so it persists across filter changes.\n const [selected, setSelected] = useState<Set<string>>(() => {\n return new Set()\n })\n const [showRequiredHint, setShowRequiredHint] = useState(false)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n // The extra chrome row is this screen's `select at least one` hint: counted unconditionally, because\n // it appears on a keystroke and a budget that shrinks mid-frame is a budget that overflows.\n const layout = listLayout(rows, 1)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const toggleValue = (value: string) => {\n setSelected((prev) => {\n const next = new Set(prev)\n\n if (next.has(value)) {\n next.delete(value)\n } else {\n next.add(value)\n }\n\n return next\n })\n }\n\n const toggleSelectAll = () => {\n setSelected((prev) => {\n // Clear only when every item (all, not just filtered) is already selected.\n const allSelected = items.every((item) => {\n return prev.has(item.value)\n })\n\n if (allSelected) {\n return new Set()\n }\n\n return new Set(\n items.map((item) => {\n return item.value\n }),\n )\n })\n }\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n const submit = () => {\n if (required && selected.size === 0) {\n setShowRequiredHint(true)\n\n return\n }\n\n onSubmit([...selected])\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: the typed filter first, the picker only once\n // there is no filter left to clear. It never touches `selected` \u2014 a filter keystroke is\n // not a selection, so clearing one must not discard the other. Stage 2 discards it, as before.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.ctrl && input === 'a') {\n if (allowSelectAll) {\n toggleSelectAll()\n }\n\n return\n }\n\n if (input === ' ') {\n const active = filtered[activeIndex]\n\n if (active) {\n toggleValue(active.value)\n }\n\n return\n }\n\n if (key.return) {\n submit()\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const isChecked = selected.has(item.value)\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width. Ink reads the wrap style off the\n // OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={isActive ? 'green' : undefined} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {isChecked ? '[x] ' : '[ ] '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n {showRequiredHint ? (\n <Text dimColor wrap=\"truncate\">\n {T.requiredHint}\n </Text>\n ) : null}\n </Box>\n )\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_MULTI_PICKER_TEXT = {\n hint: 'filter \u00B7 \u2191\u2193 move \u00B7 Space toggle \u00B7 Ctrl-A all \u00B7 Enter submit \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick branches',\n requiredHint: 'select at least one',\n more: '\u2026',\n}\n", "import type { Key } from 'ink'\nimport { useMemo, useState } from 'react'\n\ninterface ListFilter<T> {\n /** Items matching the current query (all items when the query is empty). */\n filtered: T[]\n /** Active row index, always clamped into `filtered`'s bounds. */\n activeIndex: number\n /** Current filter query. */\n query: string\n /**\n * Handle the shared navigation/filter keys (\u2191\u2193 wrap-around, backspace/delete,\n * printable chars). Returns true when the key was consumed so the caller can\n * `return` early; false leaves the key for the component's own handlers.\n */\n handleNavigation: (input: string, key: Key) => boolean\n /**\n * Stage 1 of the Esc ladder: clears a non-empty query (back to the first row) and\n * returns true. Returns false when the query is already empty \u2014 the boolean IS the\n * ladder, and a false tells the caller there is nothing left to cancel but the screen.\n *\n * Deliberately NOT folded into `handleNavigation`: the two pickers want different\n * stage-2 actions, so the escape branch belongs to each screen, not to the shared handler.\n */\n clearQuery: () => boolean\n}\n\n/**\n * Shared list-filter state for the branch pickers: substring filtering,\n * wrap-around \u2191\u2193 movement, and query editing. Extracted so each `useInput`\n * handler stays under the sonarjs cognitive-complexity \u226415 gate.\n */\nexport const useListFilter = <T>(items: T[], toText: (item: T) => string): ListFilter<T> => {\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return toText(item).toLowerCase().includes(q)\n })\n }, [items, query, toText])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n const handleNavigation = (input: string, key: Key): boolean => {\n const n = filtered.length\n\n if (key.upArrow) {\n // `+ n` sidesteps JS negative modulo (e.g. -1 % 5 === -1, not 4).\n if (n > 0) {\n setIndex((activeIndex - 1 + n) % n)\n }\n\n return true\n }\n\n if (key.downArrow) {\n if (n > 0) {\n setIndex((activeIndex + 1) % n)\n }\n\n return true\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return true\n }\n\n // Printable character: append to the filter and reset to the first row.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n\n return true\n }\n\n return false\n }\n\n const clearQuery = (): boolean => {\n if (!query) {\n return false\n }\n\n setQuery('')\n setIndex(0)\n\n return true\n }\n\n return { filtered, activeIndex, query, handleNavigation, clearQuery }\n}\n", "/**\n * Pure viewport arithmetic shared by every Ink list screen (the command palette and both branch\n * pickers): which slice of the (already filtered) list fits the terminal, and how much chrome the\n * screen may spend around it.\n *\n * This is a SAFETY guard, not a readability one. Ink's cleanup walks the cursor upward one line at a\n * time (`ESC[2K ESC[1A` per row) and `ESC[1A` SATURATES AT ROW 0. So the moment a frame is taller than\n * the viewport, the terminal scrolls while Ink draws, the upward walk erases the wrong rows, and the\n * cursor is left parked ABOVE live content \u2014 after which every later write (the session's status\n * footer, the next palette frame) is deposited on top of the transcript. That is the \"welded rows\" bug:\n * `\u276F ` printed over the head of `ERROR: \u2026`, leaving `ROR: \u2026` behind.\n *\n * The invariant this module exists to enforce, for every (columns, rows):\n *\n * rendered frame height < terminal rows\n *\n * Hold that, and Ink never takes its overflow path: `clearTerminal` never fires, `eraseLines` never\n * saturates, the cursor stays below the transcript, and a fresh (cold) Ink instance \u2014 which erases\n * NOTHING before its first frame \u2014 simply appends below the transcript like any other CLI. No new\n * escape bytes required.\n *\n * Two things make the row count knowable at all:\n * - Every list row is rendered `wrap=\"truncate\"`, so one item is always exactly one row. Without that\n * a long description wraps to two rows and this arithmetic silently under-counts (Ink wraps text\n * itself and measures the WRAPPED height, so it, not us, would be right).\n * - Chrome is counted unconditionally, even when a given row is not drawn (see `CHROME_ROWS`). Over-\n * counting shrinks the list; under-counting overflows. Only one of those is a bug.\n *\n * `src/tui/safe-stderr.ts` (the `ESC[3J` byte filter) remains the last-resort backstop for the case\n * this cannot cover \u2014 a SIGWINCH that invalidates a frame's height retroactively.\n */\nimport type { PaletteItem } from '../types'\n\n/**\n * Reads an item's group label. Omitted by the branch pickers, whose lists have no headers at all.\n * (Passed as an accessor rather than constrained with a `{ group?: string }` marker interface: a type\n * whose properties are ALL optional is \"weak\", and TypeScript refuses to match a `BranchPickerItem`\n * against it \u2014 inference silently falls back to the constraint and every field access breaks.)\n */\nexport type GroupOf<T> = (item: T) => string | undefined\n\n/** The slice to render, plus how many rows fell off each end (for the `\u2026 n more` affordances). */\nexport interface ListWindow<T> {\n visible: T[]\n /** Index the window starts at \u2014 the component stores it so the list does not jump between frames. */\n start: number\n hiddenBefore: number\n hiddenAfter: number\n}\n\n/** Back-compat alias: the command palette's window is a window of `PaletteItem`s. */\nexport type PaletteWindow = ListWindow<PaletteItem>\n\n/**\n * Rows a screen spends on everything that is not a list row, counted UNCONDITIONALLY (a `\u2026 n above`\n * that is not drawn today may be drawn on the next keystroke, and re-deriving the budget mid-frame is\n * how you get an off-by-one that only bites on a full list):\n * hint, `\u276F` prompt, the list's `marginTop`, `\u2026 n above`, `\u2026 n below`, and one row of headroom.\n *\n * The headroom row is what makes the frame strictly SHORTER than the viewport: Ink treats a frame\n * exactly as tall as the terminal as fullscreen and clears the screen.\n */\nexport const CHROME_ROWS = 6\n\n/** Compact chrome: the hint and the list's `marginTop` are dropped. Prompt + affordances + headroom. */\nexport const COMPACT_CHROME_ROWS = 4\n\n/** Below this many rows a screen drops its hint, its `marginTop`, and its group headers. */\nexport const COMPACT_BELOW_ROWS = 10\n\n/** Below this many rows no usable list fits at all; the screen renders a single-line notice instead. */\nexport const TINY_BELOW_ROWS = 5\n\n/** How a screen must lay itself out to keep its frame shorter than `rows`. */\nexport type ListLayoutMode = 'full' | 'compact' | 'tiny'\n\nexport interface ListLayout {\n mode: ListLayoutMode\n /** Rows reserved for chrome. Pass to `paletteWindow` as `chromeRows`. */\n chromeRows: number\n /** Whether group headers may be drawn (they cost a row each, so a compact frame drops them). */\n groups: boolean\n}\n\n/** A list with no group headers: every item costs exactly one row. */\nconst NO_GROUPS = (): undefined => {\n return undefined\n}\n\n/**\n * The layout a screen must use at this terminal height. `extraChromeRows` is for chrome a screen has\n * that the others do not \u2014 the multi-picker's `select at least one` hint is the only one today.\n *\n * A `tiny` frame is one truncated line, which is strictly shorter than any terminal of 2+ rows. (At\n * `rows === 1` nothing can be shorter than the viewport; Ink will clear. That is a degenerate terminal,\n * and `safe-stderr` keeps even that harmless.)\n *\n * @example\n * listLayout(24) // => { mode: 'full', chromeRows: 6, groups: true }\n * listLayout(8) // => { mode: 'compact', chromeRows: 4, groups: false }\n * listLayout(8, 1) // => { mode: 'compact', chromeRows: 5, groups: false } (multi-picker)\n * listLayout(4) // => { mode: 'tiny', chromeRows: 0, groups: false }\n */\nexport const listLayout = (rows: number, extraChromeRows = 0): ListLayout => {\n if (rows < TINY_BELOW_ROWS) {\n return { mode: 'tiny', chromeRows: 0, groups: false }\n }\n\n if (rows < COMPACT_BELOW_ROWS) {\n return { mode: 'compact', chromeRows: COMPACT_CHROME_ROWS + extraChromeRows, groups: false }\n }\n\n return { mode: 'full', chromeRows: CHROME_ROWS + extraChromeRows, groups: true }\n}\n\n/**\n * How many rows rendering `items[start..end)` costs: one per item (guaranteed by `wrap=\"truncate\"`),\n * plus, when `groups` is on, one for each group header and one for the blank line between groups (the\n * first rendered group gets a header but no blank \u2014 it mirrors the `showGroup && position > 0` rule in\n * the components). A list whose items carry no `group` never spends a header row.\n */\nconst heightOf = <T>(items: T[], start: number, end: number, groupOf: GroupOf<T>): number => {\n let height = 0\n let previousGroup: string | undefined\n\n for (let index = start; index < end; index += 1) {\n const item = items[index]\n\n if (!item) break\n\n const group = groupOf(item)\n const startsGroup = group !== undefined && group !== previousGroup\n\n height += 1 + (startsGroup ? 1 : 0) + (startsGroup && index > start ? 1 : 0)\n previousGroup = group\n }\n\n return height\n}\n\n/** The last index (exclusive) that still fits `budget` rows when rendering from `start`. */\nconst endThatFits = <T>(items: T[], start: number, budget: number, groupOf: GroupOf<T>): number => {\n let end = start\n\n while (end < items.length && heightOf(items, start, end + 1, groupOf) <= budget) {\n end += 1\n }\n\n return end\n}\n\n/**\n * The window of items to render: the largest slice starting at or after `start` that fits the terminal\n * while still containing `activeIndex`. Scrolls by the minimum needed \u2014 the caller keeps `start` in\n * state, so the list only moves when the cursor would otherwise leave the window.\n *\n * An empty `visible` is a legitimate result on a terminal too short to hold even one row. It is NOT\n * clamped up to one item: forcing a row that does not fit is exactly how the frame overflows and the\n * cursor corruption starts. A screen that gets nothing back renders its `tiny` notice instead \u2014 see\n * `listLayout`.\n *\n * @example\n * const window = paletteWindow(items, 0, 12, 24)\n * window.visible.length // => however many commands fit 18 rows\n * window.hiddenAfter // => the rest, surfaced as '\u2026 n below'\n */\nexport const paletteWindow = <T>(\n items: T[],\n start: number,\n activeIndex: number,\n rows: number,\n opts?: { chromeRows?: number; groupOf?: GroupOf<T> },\n): ListWindow<T> => {\n const groupOf = opts?.groupOf ?? NO_GROUPS\n const budget = Math.max(0, rows - (opts?.chromeRows ?? CHROME_ROWS))\n\n // Scroll up only if the cursor moved above the window; otherwise scroll down just far enough.\n let first = Math.min(start, activeIndex)\n\n while (activeIndex >= endThatFits(items, first, budget, groupOf) && first < activeIndex) {\n first += 1\n }\n\n const end = endThatFits(items, first, budget, groupOf)\n\n return {\n visible: items.slice(first, end),\n start: first,\n hiddenBefore: first,\n hiddenAfter: Math.max(0, items.length - end),\n }\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface BranchPickerProps {\n items: BranchPickerItem[]\n /** Called with the chosen item's value; the app then exits. */\n onSelect: (value: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n}\n\n/**\n * Searchable single-select branch picker rendered with Ink. Mirrors\n * `CommandPalette` minus the group headers: type-to-filter over label +\n * description, \u2191\u2193 wrap-around, Enter selects the active item's *value*.\n *\n * Like the palette, the list is WINDOWED to the terminal height. That is a safety\n * requirement, not a nicety: a repo with ~20 open releases produced a frame taller\n * than an 80x24 window, and an overflowing Ink frame corrupts the cursor and welds\n * the next frame onto the command's own output. See `palette-window.ts`.\n */\nexport const BranchPicker = (props: BranchPickerProps) => {\n const { items, onSelect, onCancel } = props\n\n const T = BRANCH_PICKER_TEXT\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { rows } = useWindowSize()\n const { filtered, activeIndex, query, handleNavigation, clearQuery } = useListFilter(items, filterText)\n // First branch in the visible window; kept in state so the list scrolls by the minimum needed.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const layout = listLayout(rows)\n // No `groupOf`: a branch list has no headers, so every branch costs exactly one row.\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, { chromeRows: layout.chromeRows })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n const cancel = () => {\n onCancel()\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.ctrl && input === 'c') {\n cancel()\n\n return\n }\n\n // Esc pops the innermost stateful thing: a typed filter first, the picker only once\n // there is no filter left to clear. `clearQuery` returning false IS that ladder.\n if (key.escape) {\n if (!clearQuery()) {\n cancel()\n }\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.value)\n setSubmitted(true)\n }\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one branch row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START: overflow must eat the head of the filter, never the character being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n\n // `wrap=\"truncate\"` keeps one branch = one row at any width (a long branch name would\n // otherwise wrap and make the frame taller than this component believes). Ink reads the wrap\n // style off the OUTER <Text> only, so it must live here, not on the nested description.\n return (\n <Text color={labelColor(item.type, isActive)} key={item.value} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Colour for a row's label, derived from the release type. Kept a plain lookup so\n * an unknown/absent type simply falls through to the default (green when active).\n */\nfunction labelColor(type: string | undefined, isActive: boolean): string | undefined {\n if (type === 'hotfix') {\n return 'red'\n }\n\n return isActive ? 'green' : undefined\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n\n/**\n * Static screen copy. Module-scoped and exported so the hint-width guard can measure it:\n * these strings render under `wrap=\"truncate\"`, so a hint of \u226580 columns silently loses\n * its tail at the common terminal width \u2014 and the tail is where the Esc hint lives.\n */\nexport const BRANCH_PICKER_TEXT = {\n hint: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter select \u00B7 Esc clear/cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n tiny: 'terminal too short \u2014 resize to pick a branch',\n more: '\u2026',\n}\n", "import { Box, Text, useApp, useInput, useWindowSize } from 'ink'\nimport { useEffect, useMemo, useState } from 'react'\n\nimport type { PaletteItem } from '../types'\nimport { listLayout, paletteWindow } from './palette-window'\n\ninterface CommandPaletteProps {\n items: PaletteItem[]\n /** Called with the chosen command name; the app then exits. */\n onSelect: (name: string) => void\n /** Called when the user cancels (Ctrl-C / Ctrl-D); the app then exits. Esc never reaches this. */\n onCancel: () => void\n /**\n * Stop the foreground job (Ctrl-Z). ABSENT means suspend is impossible on this platform \u2014 the\n * palette stays pure presentation and never inspects `process`; boot.tsx is the platform authority.\n */\n onSuspend?: () => void\n}\n\n/**\n * Fuzzy-ish command picker rendered with Ink. Pure presentation: it receives a\n * flat list of commands (already grouped/ordered by the catalog) and returns the\n * selected name. It never executes anything \u2014 the caller runs the command via\n * the existing Commander path.\n *\n * NOTE: this component sits at exactly the sonarjs cognitive-complexity ceiling (15). Any `if` or\n * `?:` added to its BODY breaks `pnpm run qa` \u2014 which is why the hint is picked by the module-scope\n * `hintFor` below and the control keys by `handleCtrlKey`, rather than inline.\n */\nexport const CommandPalette = (props: CommandPaletteProps) => {\n const { items, onSelect, onCancel, onSuspend } = props\n\n const T = {\n hint: hintFor(Boolean(onSuspend)),\n prompt: '\u276F ',\n empty: 'No matching commands',\n tiny: 'terminal too short \u2014 resize to pick a command',\n more: '\u2026',\n }\n const nameWidth = 24\n\n const { exit, suspendTerminal } = useApp()\n const { rows } = useWindowSize()\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n // First command in the visible window. Kept in state so the list scrolls by the minimum needed\n // instead of jumping every time the cursor moves.\n const [windowStart, setWindowStart] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame (Ink's `log.done()` would otherwise\n // freeze the last drawn frame \u2014 the command list \u2014 into the scrollback).\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return `${item.name} ${item.description}`.toLowerCase().includes(q)\n })\n }, [items, query])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n // The slice that fits this terminal, and how much chrome we may spend around it. A frame taller than\n // the viewport corrupts the cursor (see palette-window.ts) \u2014 every row here is budgeted, and every\n // row below is `wrap=\"truncate\"` so one command is always exactly one row.\n const layout = listLayout(rows)\n const view = paletteWindow(filtered, windowStart, activeIndex, rows, {\n chromeRows: layout.chromeRows,\n // A compact frame drops group headers, so they must not be budgeted for either.\n groupOf: layout.groups\n ? (item) => {\n return item.group\n }\n : undefined,\n })\n\n // Commit the scroll position once the frame that used it has rendered.\n useEffect(() => {\n if (view.start !== windowStart) {\n setWindowStart(view.start)\n }\n }, [view.start, windowStart])\n\n // Back out with nothing picked (Ctrl-C / Ctrl-D). Esc is NOT a caller: it pops the filter only.\n const quit = () => {\n onCancel()\n setSubmitted(true)\n }\n\n // Hand the terminal back to the user's shell until they `fg`.\n //\n // Ink does all the terminal work for us, in the right order and synchronously: `beginSuspend`\n // settles pending frames, erases the list, restores the cursor and drops raw mode BEFORE our\n // callback runs, and on resume `endSuspend` re-arms raw mode and force-redraws THIS SAME LIVE\n // COMPONENT \u2014 so the typed filter survives the suspend. That is why we must NOT set `submitted`\n // here: unmounting would throw the query away and give us a blank palette on return.\n //\n // The `.catch` is the PRIMARY guard, not a backstop \u2014 never simplify it to `void`. Two 0x1a bytes\n // in one read chunk (a double-tap) are both already queued in Ink's input loop, and `pauseInput`\n // only detaches the stdin listener, so the second one still fires \u2014 into a `beginSuspend` that is\n // already suspended, which throws. Harmless (it throws before flipping its own state, and the first\n // suspension still unwinds), but the rejection must be caught: `void` would make it an unhandled\n // rejection that kills the process mid terminal-restore.\n const suspend = () => {\n if (!onSuspend) {\n return\n }\n\n suspendTerminal(onSuspend).catch(() => {\n // See above: a double Ctrl-Z is a no-op, not a crash.\n })\n }\n\n /**\n * Ctrl-C / Ctrl-Z, hoisted OUT of the `useInput` body. Mandatory, not tidiness: that handler sits at\n * cognitive complexity 14, and an inline `if (key.ctrl && input === 'z' && onSuspend)` costs +2 \u2014\n * 16, over the sonarjs ceiling of 15, and `pnpm run qa` goes red.\n *\n * The palette's Ctrl-Z is a BYTE (0x1a), not a signal: Ink holds stdin in raw mode, which clears\n * termios ISIG, so the tty never generates SIGTSTP here at all. We therefore stop the process GROUP\n * ourselves (kill(0), see ../suspend.ts). The session shell's SIGTSTP handler does the opposite \u2014\n * it self-stops with raise('SIGSTOP') (lib/session/run-session.ts) \u2014 and that is CORRECT there,\n * because while a child command holds the foreground the tty is cooked and has already TSTP'd the\n * whole group, leaving only us to follow. DO NOT UNIFY THE TWO.\n */\n const handleCtrlKey = (input: string): boolean => {\n if (input === 'c') {\n quit()\n\n return true\n }\n\n // Ctrl-D is the REPL/shell convention for \"end of input\", and it is the PRIMARY quit \u2014 the one the\n // footer advertises. UNCONDITIONAL, unlike anything Esc does: it ends the session with a filter\n // typed as readily as without one. It landed here as a companion to an Esc that also quit; that Esc\n // is gone, and this is now the binding a shell user's fingers already reach for.\n if (input === 'd') {\n quit()\n\n return true\n }\n\n if (input === 'z') {\n suspend()\n\n return true\n }\n\n return false\n }\n\n // Move the active row by `delta`, wrapping. The `+ n` sidesteps JS negative modulo\n // (e.g. -1 % 5 === -1, not 4). No-op on an empty list.\n const step = (delta: number) => {\n const n = filtered.length\n\n if (n > 0) {\n setIndex((activeIndex + delta + n) % n)\n }\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n // Ctrl-C quits, Ctrl-Z suspends (see handleCtrlKey). Esc pops one level and this palette has\n // exactly one \u2014 the filter \u2014 so an empty filter makes it a no-op, NOT a quit. Popping the root\n // would leave nowhere to land: the session shell has no screen behind the palette, so an Esc that\n // quit would be a quit wearing a back-out's clothes. Quitting is Ctrl-C / Ctrl-D, and only those.\n // No emptiness check: clearing an already-empty query is a React no-op.\n if (key.ctrl && handleCtrlKey(input)) {\n return\n }\n\n if (key.escape) {\n setQuery('')\n setIndex(0)\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.name)\n setSubmitted(true)\n }\n\n return\n }\n\n if (key.upArrow) {\n step(-1)\n\n return\n }\n\n if (key.downArrow) {\n step(1)\n\n return\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return\n }\n\n // Printable character: append to the filter.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n }\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n // Too short for even one command row plus a prompt. One truncated line always fits.\n if (layout.mode === 'tiny') {\n return (\n <Text dimColor wrap=\"truncate\">\n {T.tiny}\n </Text>\n )\n }\n\n let lastGroup = ''\n\n return (\n <Box flexDirection=\"column\">\n {layout.mode === 'full' ? (\n <Text dimColor wrap=\"truncate\">\n {T.hint}\n </Text>\n ) : null}\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n {/* truncate-START on the input: overflow must eat the head of the filter, never the character\n being typed. */}\n <Text wrap=\"truncate-start\">{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={layout.mode === 'full' ? 1 : 0}>\n {filtered.length === 0 ? (\n <Text dimColor wrap=\"truncate\">\n {T.empty}\n </Text>\n ) : null}\n {view.hiddenBefore > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenBefore} above`}</Text> : null}\n {view.visible.map((item, position) => {\n const isActive = view.start + position === activeIndex\n const showGroup = layout.groups && item.group !== lastGroup\n\n lastGroup = item.group\n\n return (\n <Box flexDirection=\"column\" key={item.name}>\n {/* Blank line between groups (not before the first row of the window). */}\n {showGroup && position > 0 ? <Text> </Text> : null}\n {showGroup ? <Text color=\"yellow\" wrap=\"truncate\">{`\u2014 ${item.group} \u2014`}</Text> : null}\n {/* `wrap=\"truncate\"` is load-bearing, not cosmetic: it is what makes \"one command = one\n row\" true at any width, which is what keeps the frame shorter than the viewport. Ink\n reads the wrap style off the OUTER <Text> only \u2014 it squashes the nested <Text> into\n this one's string \u2014 so it must live here. */}\n <Text color={isActive ? 'green' : undefined} wrap=\"truncate\">\n {isActive ? '\u203A ' : ' '}\n {item.name.padEnd(nameWidth)} <Text dimColor>{item.description}</Text>\n </Text>\n </Box>\n )\n })}\n {view.hiddenAfter > 0 ? <Text dimColor wrap=\"truncate\">{`${T.more} ${view.hiddenAfter} below`}</Text> : null}\n </Box>\n </Box>\n )\n}\n\n/**\n * Footer copy. Kept out of the component's `T` because picking between the two is a conditional.\n *\n * Exported so the hint-width guard can measure these strings: they render under `wrap=\"truncate\"`,\n * so a hint of \u226580 columns silently loses its TAIL \u2014 and the tail is where the newest keybinding\n * always lands. `Esc clear` is the whole truth, not an abbreviation of one: Esc pops the filter and\n * never quits, so `Ctrl-D quit` beside it is the only advertised way out.\n *\n * The slack this leaves is NOT spendable: restoring `type to filter` to the suspend variant measures\n * 79 against the guard's `toBeLessThan(80)`, i.e. one column from silently truncating again.\n */\nexport const HINTS = {\n suspend: 'filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear \u00B7 Ctrl-D quit \u00B7 Ctrl-Z suspend',\n plain: 'type to filter \u00B7 \u2191\u2193 move \u00B7 Enter run \u00B7 Esc clear \u00B7 Ctrl-D quit',\n}\n\n/**\n * The footer hint, which advertises Ctrl-Z only where suspending is possible.\n *\n * Module scope for two reasons, both load-bearing. It cannot live in the component: a `?:` in\n * `CommandPalette`'s body pushes it from 15 to 16, over the sonarjs cognitive-complexity ceiling. And\n * it cannot sit above the component either: `@wl/component-file-order` pins this file to\n * imports \u2192 props interface \u2192 component with nothing in between. Below is the only legal home.\n *\n * Both strings are SHORTER than the hint they replace, on purpose \u2014 the footer renders with\n * `wrap=\"truncate\"`, so anything longer silently loses its tail on a narrow terminal, and the tail is\n * exactly where a newly-added key would land.\n *\n * @example\n * hintFor(true).includes('Ctrl-Z') // => true\n */\nconst hintFor = (canSuspend: boolean): string => {\n return canSuspend ? HINTS.suspend : HINTS.plain\n}\n", "import process from 'node:process'\n\n/**\n * Ctrl-Z at the palette, from the process side. React-free on purpose: the palette is pure\n * presentation and must not reach for `node:process`, and this half is worth unit-testing with plain\n * vitest (inject `kill`, assert the signal) rather than through an Ink frame.\n *\n * It lives under `src/tui/` rather than `src/lib/session/` because `boot.tsx` is its only caller and\n * the whole `src/tui/**` tree is the lazily-imported Ink chunk \u2014 the session layer never imports it,\n * and parking it there would drag it into the eager CLI chunk for nothing.\n */\n\n/** Seams for the stop. Production passes nothing; tests inject fakes and assert the signal. */\nexport interface SuspendDeps {\n platform?: NodeJS.Platform\n kill?: (pid: number, signal: NodeJS.Signals) => void\n}\n\n/**\n * Stop the foreground PROCESS GROUP so the user's shell reclaims the tty and prints a prompt.\n * Returns when the job is resumed (`fg` \u2192 SIGCONT): the kill halts JS synchronously, and execution\n * continues at the next statement \u2014 so there is no SIGCONT handler and nothing to re-arm.\n *\n * **pid 0 is the whole process group, and that is load-bearing.** Under `pnpm exec infra-kit`, pnpm's\n * node wrapper shares our pgid and the interactive shell only ever waits on PNPM \u2014 we are a\n * grandchild it never reaps. Stopping only ourselves would leave pnpm blocked in `waitpid`, so the\n * job never reads as stopped, the shell never reclaims the tty, and the terminal wedges with no\n * prompt and no way back. Stopping the group suspends the job as a unit, exactly as the tty's own\n * Ctrl-Z would; on direct-bin invocation it degenerates to a self-stop, so this is one code path.\n *\n * Only ever called from inside Ink's `suspendTerminal`, which has already erased the frame, restored\n * the cursor and dropped raw mode by the time we get here.\n *\n * `bg` is NOT supported: on resume Ink re-arms raw mode, and a `tcsetattr` from a background process\n * group raises SIGTTOU, which stops the job again. Same as vim. Use `fg`.\n *\n * @example\n * const stopped: number[] = []\n * suspendForeground({ platform: 'darwin', kill: (pid) => stopped.push(pid) })\n * stopped // => [0] (the process group, not process.pid)\n */\nexport const suspendForeground = (deps: SuspendDeps = {}): void => {\n const platform = deps.platform ?? process.platform\n const kill =\n deps.kill ??\n ((pid: number, signal: NodeJS.Signals) => {\n process.kill(pid, signal)\n })\n\n // SIGSTOP does not exist on Windows: `process.kill` there goes to uv_kill, which fails with ENOSYS\n // and THROWS. That throw would surface inside an Ink input handler \u2192 the ErrorBoundary \u2192\n // `handleExit(error)` \u2192 the session shell would silently QUIT. And Windows really does reach this\n // code: `sessionGateEnabled` (lib/session/run-session.ts) gates on TTYs only, with no platform\n // check, so Windows Terminal enters the palette like any other. Belt to boot.tsx's braces.\n if (platform === 'win32') {\n return\n }\n\n // No cursor/newline work here, deliberately: Ink's `beginSuspend` has already erased its frame and\n // left the cursor at column 0, so the shell's \"suspended\" line lands on a clean row. Writing a\n // newline first only opens a gratuitous blank gap above it (verified on a real pty).\n try {\n kill(0, 'SIGSTOP')\n } catch {\n // A stop we could not perform must degrade to a no-op, never to a crash: we are called mid\n // terminal-restore, and throwing here would take the session down with the tty half-handed-back.\n }\n}\n"],
5
+ "mappings": "wCAAA,OAAS,UAAAA,OAAc,MACvB,OAAOC,OAAa,eCDpB,OAAS,OAAAC,EAAK,QAAAC,EAAM,UAAAC,GAAQ,YAAAC,GAAU,iBAAAC,OAAqB,MAC3D,OAAS,aAAAC,GAAW,YAAAC,MAAgB,QCApC,OAAS,WAAAC,GAAS,YAAAC,MAAgB,QA+B3B,IAAMC,EAAgB,CAAIC,EAAYC,IAA+C,CAC1F,GAAM,CAACC,EAAOC,CAAQ,EAAIL,EAAS,EAAE,EAC/B,CAACM,EAAOC,CAAQ,EAAIP,EAAS,CAAC,EAE9BQ,EAAWT,GAAQ,IAAM,CAC7B,IAAMU,EAAIL,EAAM,KAAK,EAAE,YAAY,EAEnC,OAAKK,EAIEP,EAAM,OAAQQ,GACZP,EAAOO,CAAI,EAAE,YAAY,EAAE,SAASD,CAAC,CAC7C,EALQP,CAMX,EAAG,CAACA,EAAOE,EAAOD,CAAM,CAAC,EAEnBQ,EAAc,KAAK,IAAIL,EAAO,KAAK,IAAI,EAAGE,EAAS,OAAS,CAAC,CAAC,EAmDpE,MAAO,CAAE,SAAAA,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oBAvCJ,IAAMC,EAAiB,MAAOC,GAAyC,CACrE,IAAMC,EAASC,EAAW,EACpB,CAAE,cAAAC,CAAc,EAAIC,GAAOJ,EAAS,CACxC,OAAAC,EAOA,YAAa,GAOb,YAAa,EAAQA,EAAO,KAC9B,CAAC,EAED,GAAI,CACF,MAAME,EAAc,CACtB,MAAQ,CAGR,QAAE,CACAE,GAAQ,MAAM,IAAI,CACpB,CACF,EAOaC,GAAoB,MAAOC,GAAiD,CACvF,IAAIC,EAA0B,KAE9B,aAAMT,EACJD,EAACW,GAAA,CACC,MAAOF,EACP,SAAWG,GAAS,CAClBF,EAAWE,CACb,EACA,SAAU,IAAM,CACdF,EAAW,IACb,EAIA,UACEH,GAAQ,WAAa,QACjB,OACA,IAAM,CACJM,GAAkB,CACpB,EAER,CACF,EAEOH,CACT,EAMaI,GAAkB,MAAOL,GAAsD,CAC1F,IAAIC,EAA0B,KAE9B,aAAMT,EACJD,EAACe,GAAA,CACC,MAAON,EACP,SAAWO,GAAU,CACnBN,EAAWM,CACb,EACA,SAAU,IAAM,CACdN,EAAW,IACb,EACF,CACF,EAEOA,CACT,EAQaO,GAAuB,MAClCR,EACAS,IAC6B,CAC7B,IAAIR,EAA4B,KAEhC,aAAMT,EACJD,EAACmB,GAAA,CACC,MAAOV,EACP,SAAUS,GAAM,SAChB,eAAgBA,GAAM,eACtB,SAAWE,GAAW,CACpBV,EAAWU,CACb,EACA,SAAU,IAAM,CACdV,EAAW,IACb,EACF,CACF,EAEOA,CACT",
6
6
  "names": ["render", "process", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useState", "useMemo", "useState", "useListFilter", "items", "toText", "query", "setQuery", "index", "setIndex", "filtered", "q", "item", "activeIndex", "input", "key", "n", "NO_GROUPS", "listLayout", "rows", "extraChromeRows", "heightOf", "items", "start", "end", "groupOf", "height", "previousGroup", "index", "item", "group", "startsGroup", "endThatFits", "budget", "paletteWindow", "activeIndex", "opts", "first", "jsx", "jsxs", "BranchMultiPicker", "props", "items", "onSubmit", "onCancel", "required", "allowSelectAll", "T", "BRANCH_MULTI_PICKER_TEXT", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "clearQuery", "useListFilter", "filterText", "selected", "setSelected", "useState", "showRequiredHint", "setShowRequiredHint", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "toggleValue", "value", "prev", "next", "toggleSelectAll", "cancel", "submit", "useInput", "input", "key", "active", "Text", "Box", "position", "isActive", "isChecked", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useState", "jsx", "jsxs", "BranchPicker", "props", "items", "onSelect", "onCancel", "T", "BRANCH_PICKER_TEXT", "labelWidth", "max", "item", "exit", "useApp", "rows", "useWindowSize", "filtered", "activeIndex", "query", "handleNavigation", "clearQuery", "useListFilter", "filterText", "windowStart", "setWindowStart", "useState", "submitted", "setSubmitted", "useEffect", "layout", "listLayout", "view", "paletteWindow", "cancel", "useInput", "input", "key", "selected", "Text", "Box", "position", "isActive", "labelColor", "type", "Box", "Text", "useApp", "useInput", "useWindowSize", "useEffect", "useMemo", "useState", "jsx", "jsxs", "CommandPalette", "props", "items", "onSelect", "onCancel", "onSuspend", "T", "hintFor", "nameWidth", "exit", "suspendTerminal", "useApp", "rows", "useWindowSize", "query", "setQuery", "useState", "index", "setIndex", "windowStart", "setWindowStart", "submitted", "setSubmitted", "useEffect", "filtered", "useMemo", "q", "item", "activeIndex", "layout", "listLayout", "view", "paletteWindow", "quit", "suspend", "handleCtrlKey", "input", "step", "delta", "n", "useInput", "key", "selected", "Text", "lastGroup", "Box", "position", "isActive", "showGroup", "HINTS", "canSuspend", "process", "suspendForeground", "deps", "platform", "kill", "pid", "signal", "jsx", "renderToStderr", "element", "stdout", "safeStderr", "waitUntilExit", "render", "process", "runCommandPalette", "items", "selected", "CommandPalette", "name", "suspendForeground", "runBranchPicker", "BranchPicker", "value", "runBranchMultiPicker", "opts", "BranchMultiPicker", "values"]
7
7
  }
@@ -1,4 +1,4 @@
1
- import{a as rs,b as lt,c as Yt,d as ts,e as os,f as ns,g as ss,h as Xt,i as is,j as pt,k as er,l as dt,p as mt,q as de,r as rr}from"./chunk-S45AAYXO.js";import{a as ct}from"./chunk-Y72C523R.js";import{a as rt,c as q,d as k,e as it,f as H,i as u,k as at,l as $,m as D}from"./chunk-GZNE5CBQ.js";import{E as zn,F as qn,H as Hn,I as Zn,J as ze,K as Yn,L as Zt,M as re,O as N,P as O,Q as Xn,R as qe,a as Mn,b as Qr,c as _,d as pe,e as ye,f as Ln,g as Ht,h as z,i as S,j as et,k as Wn,l as V,m as w,n as Vn,o as Jn,p as ee,q as Bn,r as Kn,u as l,w as Un,x as Gn}from"./chunk-IVWPZEMC.js";import{a as J,b as tt,c as yr,d as Qn,e as ot,f as He,g as Ze,h as nt,i as Ye,j as Ie,k as Xe,l as st,n as Qe,o as es,p as Ne,q as Oe,r as te}from"./chunk-CHETBZ6M.js";import br from"node:path";import Sa from"node:process";import{z as B}from"zod";var we={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Qt={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"]},eo=(e,r=we)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import la from"node:fs/promises";var me=async e=>{try{return await la.access(e),!0}catch{return!1}};import ba from"node:path";import{packageConfigSchema as pa}from"@slip-stream-kit/config/internal";import as from"node:fs/promises";import cs from"node:path";import{pathToFileURL as da}from"node:url";import{z as ma}from"zod";var Re="infra-kit.config.ts",ro=async e=>{try{let r=await as.readFile(cs.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},wr=async(e,r=we)=>{let t=cs.join(e,Re);if(!await me(t))throw new Error(`${Re} not found at ${t}`);let o=await as.stat(t),i=(await import(`${da(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${Re} at ${t} has no default export`);let a=typeof i=="function"?await i():i,c=pa.safeParse(a);if(!c.success)throw new Error(`Invalid ${Re} at ${t}: ${ma.prettifyError(c.error)}`);return eo(c.data,r)};import ls from"node:fs/promises";import ut from"node:path";import ua from"yaml";var fa="pnpm-workspace.yaml",ga=async e=>(await ls.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>ut.join(e,t.name)),ha=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await ga(o));continue}let s=ut.join(o,r);await me(s)&&t.push(s)}return t},va=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await ha(t,o);return t},Rr=async e=>{let r=await ls.readFile(ut.join(e,fa),"utf-8"),o=((ua.parse(r)??{}).packages??[]).filter(n=>!n.startsWith("!")&&!n.startsWith("vendor")),s=new Set;for(let n of o){let i=await va(e,n);for(let a of i)await me(ut.join(a,"package.json"))&&s.add(a)}return[...s].sort()};var to=async(e,r=we)=>{try{let t=await wr(e,r);return{check:{name:Re,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:Re,status:"fail",message:t.message},rules:null}}};import ka from"node:fs/promises";import ya from"node:path";var oo=async(e,r)=>Promise.all(r.map(async t=>{let o=await ka.stat(ya.join(e,t)).catch(()=>null);return o?o.isFile()?{name:`file:${t}`,status:"pass",message:"exists"}:{name:`file:${t}`,status:"fail",message:`not a file: ${t} (found a directory)`}:{name:`file:${t}`,status:"fail",message:`missing file: ${t}`}}));var no=(e,r)=>r.map(t=>{let o=e[t];return typeof o!="string"?{name:`script:${t}`,status:"fail",message:`missing "${t}" in package.json scripts`}:o.trim().length===0?{name:`script:${t}`,status:"fail",message:`"${t}" is empty in package.json scripts`}:{name:`script:${t}`,status:"pass",message:"defined"}});import wa from"node:fs/promises";import Ra from"node:path";var tr="turbo.json",so=async(e,r)=>{if(r.length===0)return[];let t;try{let s=await wa.readFile(Ra.join(e,tr),"utf-8");t=JSON.parse(s)}catch(s){return[{name:tr,status:"fail",message:`cannot read/parse ${tr}: ${s.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:tr,status:"fail",message:`no "tasks" object defined in ${tr}`}]:r.map(s=>{let n=s in o||`//#${s}`in o;return{name:`turbo:${s}`,status:n?"pass":"fail",message:n?"defined":`missing turbo task "${s}" in ${tr}`}})};var io=async(e,r=we)=>{let t=await ro(e),o=t.name??ba.basename(e),{check:s,rules:n}=await to(e,r),i=[s];n&&(i.push(...no(t.scripts??{},n.requiredScripts)),i.push(...await oo(e,n.requiredFiles)),i.push(...await so(e,n.turboTasks)));let a=i.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:a}};var g=e=>[{type:"text",text:e}],v=e=>e;import{loadDev as Ea}from"@slip-stream-kit/config/internal";import xa from"node:path";var Pa=(e,r)=>{let t=new Set;for(let o of Object.values(e))for(let s of Object.keys(qn(o,r).proxy))t.add(s);return[...t]},Ta=async(e,r)=>{let t={},o=[];return await Promise.all(r.map(async s=>{try{let i=(await Ea(xa.join(e,"apps",s,"ui")))?.proxy?.routes;if(!i)return;t[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,c.packageName]))}catch(n){o.push({app:s,message:n instanceof Error?n.message:String(n)})}})),{routePkg:(s,n)=>t[s]?.[n],loadErrors:o}},Ca=(e,r)=>[...r.map(t=>({name:`devServersPresets:config:${t.app}`,status:"fail",message:`could not load apps/${t.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${t.message}`})),...e.map(t=>({name:`devServersPresets:${t.preset}`,status:"fail",message:t.message}))],ps=async e=>{let r=(await O()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=zn(r);if(t.length>0){let m=t.map(h=>({name:`devServersPresets:${h.preset}`,status:"fail",message:h.message}));return{packageDir:e,packageName:"devServersPresets",checks:m,passed:!1}}let o=Un(e),s=Gn(e),n={api:o.map(m=>m.name),ui:s.map(m=>m.name)},{routePkg:i,loadErrors:a}=await Ta(e,Pa(r,n)),c={discovered:n,apiPkgByApp:Object.fromEntries(o.map(m=>[m.name,m.packageName])),routePkg:i},p=Ca(Hn(r,c),a),d=p.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:p;return{packageDir:e,packageName:"devServersPresets",checks:d,passed:p.length===0}};var $a=async e=>{let r=br.resolve(e);for(;r!==br.dirname(r);){if(await me(br.join(r,"package.json")))return r;r=br.dirname(r)}if(await me(br.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},_a=async e=>e.root?[{dir:await w(),baseline:Qt}]:e.all?(await Rr(await w())).map(t=>({dir:t})):[{dir:await $a(e.cwd??Sa.cwd())}],Aa=e=>{let r=e.passed?"PASS":"FAIL";l.info(`
1
+ import{a as rs,b as lt,c as Yt,d as ts,e as os,f as ns,g as ss,h as Xt,i as is,j as pt,k as er,l as dt,p as mt,q as de,r as rr}from"./chunk-S45AAYXO.js";import{a as ct}from"./chunk-T74NOBEP.js";import{a as rt,c as q,d as k,e as it,f as H,i as u,k as at,l as $,m as D}from"./chunk-GZNE5CBQ.js";import{E as zn,F as qn,H as Hn,I as Zn,J as ze,K as Yn,L as Zt,M as re,O as N,P as O,Q as Xn,R as qe,a as Mn,b as Qr,c as _,d as pe,e as ye,f as Ln,g as Ht,h as z,i as S,j as et,k as Wn,l as V,m as w,n as Vn,o as Jn,p as ee,q as Bn,r as Kn,u as l,w as Un,x as Gn}from"./chunk-IVWPZEMC.js";import{a as J,b as tt,c as yr,d as Qn,e as ot,f as He,g as Ze,h as nt,i as Ye,j as Ie,k as Xe,l as st,n as Qe,o as es,p as Ne,q as Oe,r as te}from"./chunk-CHETBZ6M.js";import br from"node:path";import Sa from"node:process";import{z as B}from"zod";var we={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Qt={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"]},eo=(e,r=we)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import la from"node:fs/promises";var me=async e=>{try{return await la.access(e),!0}catch{return!1}};import ba from"node:path";import{packageConfigSchema as pa}from"@slip-stream-kit/config/internal";import as from"node:fs/promises";import cs from"node:path";import{pathToFileURL as da}from"node:url";import{z as ma}from"zod";var Re="infra-kit.config.ts",ro=async e=>{try{let r=await as.readFile(cs.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},wr=async(e,r=we)=>{let t=cs.join(e,Re);if(!await me(t))throw new Error(`${Re} not found at ${t}`);let o=await as.stat(t),i=(await import(`${da(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${Re} at ${t} has no default export`);let a=typeof i=="function"?await i():i,c=pa.safeParse(a);if(!c.success)throw new Error(`Invalid ${Re} at ${t}: ${ma.prettifyError(c.error)}`);return eo(c.data,r)};import ls from"node:fs/promises";import ut from"node:path";import ua from"yaml";var fa="pnpm-workspace.yaml",ga=async e=>(await ls.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>ut.join(e,t.name)),ha=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await ga(o));continue}let s=ut.join(o,r);await me(s)&&t.push(s)}return t},va=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await ha(t,o);return t},Rr=async e=>{let r=await ls.readFile(ut.join(e,fa),"utf-8"),o=((ua.parse(r)??{}).packages??[]).filter(n=>!n.startsWith("!")&&!n.startsWith("vendor")),s=new Set;for(let n of o){let i=await va(e,n);for(let a of i)await me(ut.join(a,"package.json"))&&s.add(a)}return[...s].sort()};var to=async(e,r=we)=>{try{let t=await wr(e,r);return{check:{name:Re,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:Re,status:"fail",message:t.message},rules:null}}};import ka from"node:fs/promises";import ya from"node:path";var oo=async(e,r)=>Promise.all(r.map(async t=>{let o=await ka.stat(ya.join(e,t)).catch(()=>null);return o?o.isFile()?{name:`file:${t}`,status:"pass",message:"exists"}:{name:`file:${t}`,status:"fail",message:`not a file: ${t} (found a directory)`}:{name:`file:${t}`,status:"fail",message:`missing file: ${t}`}}));var no=(e,r)=>r.map(t=>{let o=e[t];return typeof o!="string"?{name:`script:${t}`,status:"fail",message:`missing "${t}" in package.json scripts`}:o.trim().length===0?{name:`script:${t}`,status:"fail",message:`"${t}" is empty in package.json scripts`}:{name:`script:${t}`,status:"pass",message:"defined"}});import wa from"node:fs/promises";import Ra from"node:path";var tr="turbo.json",so=async(e,r)=>{if(r.length===0)return[];let t;try{let s=await wa.readFile(Ra.join(e,tr),"utf-8");t=JSON.parse(s)}catch(s){return[{name:tr,status:"fail",message:`cannot read/parse ${tr}: ${s.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:tr,status:"fail",message:`no "tasks" object defined in ${tr}`}]:r.map(s=>{let n=s in o||`//#${s}`in o;return{name:`turbo:${s}`,status:n?"pass":"fail",message:n?"defined":`missing turbo task "${s}" in ${tr}`}})};var io=async(e,r=we)=>{let t=await ro(e),o=t.name??ba.basename(e),{check:s,rules:n}=await to(e,r),i=[s];n&&(i.push(...no(t.scripts??{},n.requiredScripts)),i.push(...await oo(e,n.requiredFiles)),i.push(...await so(e,n.turboTasks)));let a=i.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:a}};var g=e=>[{type:"text",text:e}],v=e=>e;import{loadDev as Ea}from"@slip-stream-kit/config/internal";import xa from"node:path";var Pa=(e,r)=>{let t=new Set;for(let o of Object.values(e))for(let s of Object.keys(qn(o,r).proxy))t.add(s);return[...t]},Ta=async(e,r)=>{let t={},o=[];return await Promise.all(r.map(async s=>{try{let i=(await Ea(xa.join(e,"apps",s,"ui")))?.proxy?.routes;if(!i)return;t[s]=Object.fromEntries(Object.entries(i).map(([a,c])=>[a,c.packageName]))}catch(n){o.push({app:s,message:n instanceof Error?n.message:String(n)})}})),{routePkg:(s,n)=>t[s]?.[n],loadErrors:o}},Ca=(e,r)=>[...r.map(t=>({name:`devServersPresets:config:${t.app}`,status:"fail",message:`could not load apps/${t.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${t.message}`})),...e.map(t=>({name:`devServersPresets:${t.preset}`,status:"fail",message:t.message}))],ps=async e=>{let r=(await O()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=zn(r);if(t.length>0){let m=t.map(h=>({name:`devServersPresets:${h.preset}`,status:"fail",message:h.message}));return{packageDir:e,packageName:"devServersPresets",checks:m,passed:!1}}let o=Un(e),s=Gn(e),n={api:o.map(m=>m.name),ui:s.map(m=>m.name)},{routePkg:i,loadErrors:a}=await Ta(e,Pa(r,n)),c={discovered:n,apiPkgByApp:Object.fromEntries(o.map(m=>[m.name,m.packageName])),routePkg:i},p=Ca(Hn(r,c),a),d=p.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:p;return{packageDir:e,packageName:"devServersPresets",checks:d,passed:p.length===0}};var $a=async e=>{let r=br.resolve(e);for(;r!==br.dirname(r);){if(await me(br.join(r,"package.json")))return r;r=br.dirname(r)}if(await me(br.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},_a=async e=>e.root?[{dir:await w(),baseline:Qt}]:e.all?(await Rr(await w())).map(t=>({dir:t})):[{dir:await $a(e.cwd??Sa.cwd())}],Aa=e=>{let r=e.passed?"PASS":"FAIL";l.info(`
2
2
  ${e.packageName} \u2014 ${r}`);for(let t of e.checks){let o=t.status==="pass"?"[PASS]":"[FAIL]";l.info(` ${o} ${t.name}: ${t.message}`)}},ds=async(e={})=>{let r=await _a(e),t=[];for(let n of r)t.push(await io(n.dir,n.baseline));if(e.root){let n=await ps(r[0].dir);n&&t.push(n)}for(let n of t)Aa(n);let o=t.every(n=>n.passed);l.info(`
3
3
  ${o?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let s={allPassed:o,packages:t.map(n=>({name:n.packageName,passed:n.passed,checks:n.checks}))};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},Ia={all:B.boolean().optional().describe("Audit every non-vendor workspace package"),root:B.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Na={allPassed:B.boolean().describe("Whether every audited package passed all checks"),packages:B.array(B.object({name:B.string(),passed:B.boolean(),checks:B.array(B.object({name:B.string(),status:B.enum(["pass","fail"]),message:B.string()}))})).describe("Per-package check results")},ao=v({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:Ia,outputSchema:Na,handler:e=>ds({all:e.all,root:e.root})});import j from"node:fs";import Fc from"node:os";import ne from"node:path";import{z as pr}from"zod";import{$ as Co}from"zx";import{execFileSync as Oa}from"node:child_process";var ms=(e,r)=>{let t=e.filter(o=>!o.live).map(o=>o.name);return r?{prunable:[],withheld:t}:{prunable:t,withheld:[]}},Da=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],Fa=e=>Da.some(r=>r.test(e)),ja="/bin/ps",Ma=()=>Oa(ja,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
4
4
  `),us=(e=Ma)=>{try{return e().some(Fa)}catch{return!0}};import Ha from"@inquirer/select";import{Buffer as Za}from"node:buffer";import Ya from"node:fs";import Xa from"node:path";import ho from"node:process";import{z as $r}from"zod";import{$ as ht}from"zx";var La="Could not find requested project",Wa="Could not find requested config",fs="Invalid Auth token",gs="does not have access to requested config",Er=e=>e.includes(fs)||e.includes(gs)?"auth":e.includes(La)?"project":e.includes(Wa)?"config":"unknown",xr=e=>e.includes(gs)?"mis-scoped":e.includes(fs)?"revoked":null;var hs=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(`
@@ -183,7 +183,7 @@ No token for: ${n.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-
183
183
 
184
184
  ${s}`:`${t}
185
185
  `;try{I.quiet=!0,await I`git switch ${i}`,await I`git pull origin ${i}`,await I`git checkout -b ${a}`,await I`git push -u origin ${a}`,await I`git commit --allow-empty-message --allow-empty --message ''`,await I`git push origin ${a}`;let d=(await I`gh pr create --title ${n} --body ${c} --base ${i} --head ${a}`).stdout.trim();return await I`git switch ${i}`,I.quiet=!1,{branchName:a,prUrl:d}}catch(p){throw l.error({error:p,branchName:a},`Error creating release branch ${a}`),p}};var M=async e=>{let{operation:r}=e;if(await Jn())throw new f(void 0,{operation:r,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});if(!await Vn())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};import Tl from"node:process";var Jr=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};import xl from"node:process";var $t={enabled:!1},Pl=(e,r=t=>{xl.stdout.write(t)})=>($t.enabled&&e&&e.structuredContent!=null&&r(`${JSON.stringify(e.structuredContent,null,2)}
186
- `),e),fi=e=>{e.options.some(t=>t.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(fi)};var gi=()=>{if(at()||!Tl.stdin.isTTY||$t.enabled)throw new f(void 0,{operation:"interactive branch selection",remediation:"pass the branch selection explicitly (CLI: `--version`/`--versions`/`--all`; MCP: the `version`/`versions`/`all` fields) for non-interactive, --json, or MCP runs"})},Te=async e=>{gi();let{runBranchPicker:r}=await import("./boot-EEEVHAMO.js"),t=await r(e);if(t===null)throw new Jr;return t},ur=async(e,r)=>{gi();let{runBranchMultiPicker:t}=await import("./boot-EEEVHAMO.js"),o=await t(e,r);if(o===null)throw new Jr;return o};var hi=async e=>{let{all:r,confirmedCommand:t}=e;await M({operation:"merge dev into release branches"});let s=(await x()).filter(p=>E(p.title)==="regular").map(p=>p.branch);if(s.length===0)return l.info("\u2139\uFE0F No open release branches found"),u.print(),{content:g(JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)),structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let n=[];if(r)n=s;else{u.setInteractive();let p=await C();n=await ur(A({branches:s,descriptions:p}),{required:!0})}n.length===s.length?u.addOption("--all",!0):u.addOption("--versions",Je(n)),await D(t,`Are you sure you want to merge dev into these branches: ${n.join(", ")}?`),t||u.addOption("--yes",!0),U.quiet=!0;try{await U`git fetch origin`,await U`git switch dev`,await U`git pull origin dev`}catch(p){throw U.quiet=!1,new f(p,{operation:"switch to dev before merging",remediation:"dev may be checked out in another worktree \u2014 check `git worktree list`"})}let a=[];for(let p of n)await Cl(p)||a.push(p);if(U.quiet=!1,a.length>0){l.info(`
186
+ `),e),fi=e=>{e.options.some(t=>t.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(fi)};var gi=()=>{if(at()||!Tl.stdin.isTTY||$t.enabled)throw new f(void 0,{operation:"interactive branch selection",remediation:"pass the branch selection explicitly (CLI: `--version`/`--versions`/`--all`; MCP: the `version`/`versions`/`all` fields) for non-interactive, --json, or MCP runs"})},Te=async e=>{gi();let{runBranchPicker:r}=await import("./boot-FHXCA53R.js"),t=await r(e);if(t===null)throw new Jr;return t},ur=async(e,r)=>{gi();let{runBranchMultiPicker:t}=await import("./boot-FHXCA53R.js"),o=await t(e,r);if(o===null)throw new Jr;return o};var hi=async e=>{let{all:r,confirmedCommand:t}=e;await M({operation:"merge dev into release branches"});let s=(await x()).filter(p=>E(p.title)==="regular").map(p=>p.branch);if(s.length===0)return l.info("\u2139\uFE0F No open release branches found"),u.print(),{content:g(JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)),structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let n=[];if(r)n=s;else{u.setInteractive();let p=await C();n=await ur(A({branches:s,descriptions:p}),{required:!0})}n.length===s.length?u.addOption("--all",!0):u.addOption("--versions",Je(n)),await D(t,`Are you sure you want to merge dev into these branches: ${n.join(", ")}?`),t||u.addOption("--yes",!0),U.quiet=!0;try{await U`git fetch origin`,await U`git switch dev`,await U`git pull origin dev`}catch(p){throw U.quiet=!1,new f(p,{operation:"switch to dev before merging",remediation:"dev may be checked out in another worktree \u2014 check `git worktree list`"})}let a=[];for(let p of n)await Cl(p)||a.push(p);if(U.quiet=!1,a.length>0){l.info(`
187
187
  \u26A0\uFE0F ${a.length} branch(es) failed to merge automatically.
188
188
  `),l.info("\u{1F4CB} Manual merge script for failed branches:");for(let p of a)l.info(`# Merge dev into ${p} and resolve conflicts if any
189
189
 
@@ -228,4 +228,4 @@ See \`.sync-manifest.json\` for the source commit and per-file checksums.
228
228
 
229
229
  ${i.join(`
230
230
  `)}`);let a={worktrees:s,count:s.length};return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},An=v({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:kr.array(kr.object({version:kr.string().describe("Release version"),type:kr.enum(["regular","hotfix"]).describe("Release type"),description:kr.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:kr.number().describe("Number of worktrees")},handler:na});import{z as Ae}from"zod";var sa=async()=>{try{let e=await w(),r=`${e}${te}`,t=await V("release"),o=await ee(),s=await dd({currentBranches:t,repoName:o}),[n,{opened:i}]=await Promise.all([Sn({projectRoot:e,worktreeDir:r,currentBranches:t}),md({worktreeDir:r,currentBranches:t,repoName:o})]),a={closedCmux:s,openedCmux:i,ideProviders:n.filter(c=>c.ran).map(c=>c.provider),ideFoldersAdded:n.reduce((c,p)=>c+p.added,0),ideFoldersRemoved:n.reduce((c,p)=>c+p.removed,0)};return ud(a,{ideRan:n.some(c=>c.ran)}),u.print(),{content:g(JSON.stringify(a,null,2)),structuredContent:{...a}}}catch(e){throw l.error({error:e},"\u274C Error reloading worktrees"),new f(e,{operation:"reload worktrees",remediation:"run `infra-kit worktrees list` to confirm the branches exist"})}},dd=async e=>{let{currentBranches:r,repoName:t}=e;if(r.length===0)return[];let o=await dt(),s=[];for(let n of r){let i=de({repoName:t,branch:n});o.has(pt(i))&&(await er(i),s.push(i))}return s},md=async e=>{let{worktreeDir:r,currentBranches:t,repoName:o}=e,s=[];for(let n of t){let i=de({repoName:o,branch:n});try{await mt({cwd:`${r}/${n}`,title:i}),s.push(i)}catch(a){l.warn({error:a,title:i},`\u26A0\uFE0F Failed to reopen cmux workspace for ${n}`)}}return{opened:s}},ud=(e,r)=>{if(e.closedCmux.length>0&&l.info(`\u{1F9F9} Closed ${e.closedCmux.length} cmux workspace(s)`),r.ideRan){let t=e.ideProviders.map(o=>$n(o)).join(", ");e.ideFoldersAdded>0&&l.info(`\u2705 Added ${e.ideFoldersAdded} folder(s) to ${t} workspace(s)`),e.ideFoldersRemoved>0&&l.info(`\u{1F9F9} Removed ${e.ideFoldersRemoved} dangling folder(s) from ${t} workspace(s)`)}if(e.openedCmux.length>0){l.info("\u2705 Reopened cmux workspaces:");for(let t of e.openedCmux)l.info(t)}!r.ideRan&&e.closedCmux.length===0&&e.openedCmux.length===0&&e.ideFoldersAdded===0&&e.ideFoldersRemoved===0&&l.info("\u2139\uFE0F Nothing to reload")},In=v({name:"worktrees-reload",description:"Close all open cmux workspaces for the current release worktrees, then reopen the full set \u2014 the single window-restore command. Every configured editor (Cursor and/or Zed) is reconciled + relaunched (no per-window close). Disruptive: closes live cmux windows first. Safe to run from any branch. Use to refresh stale windows or to restore everything after a cold start (editor + cmux closed).",inputSchema:{},outputSchema:{closedCmux:Ae.array(Ae.string()).describe("Titles of cmux workspaces a close was attempted for (best-effort)"),openedCmux:Ae.array(Ae.string()).describe("Titles of cmux workspaces reopened during this run"),ideProviders:Ae.array(Ae.string()).describe("Configured IDE providers that were reloaded (cursor | zed); empty if none configured"),ideFoldersAdded:Ae.number().describe("Total worktree folders added across all configured editor workspaces"),ideFoldersRemoved:Ae.number().describe("Total dangling worktree folders removed across all configured editor workspaces")},handler:sa});import{z as zt}from"zod";var fd=e=>{if(at()){if(e.all)throw new f(void 0,{operation:"remove worktrees",remediation:'name targets explicitly via "versions"; bulk all=true removal is disabled over MCP',stderrExcerpt:"all=true is not permitted for worktrees-remove over MCP"});if(!e.versions)throw new f(void 0,{operation:"remove worktrees",remediation:'pass "versions" (comma-separated release versions/names); the interactive picker needs a TTY',stderrExcerpt:'worktrees-remove over MCP requires "versions"'})}},gd=(e,r)=>{let t=e.filter(o=>!r.includes(o));if(t.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${t.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${t.join(", ")}`})},ia=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;await M({operation:"remove worktrees"}),fd({all:t,versions:o});try{let s=await V("release");if(s.length===0)return l.info("\u2139\uFE0F No active worktrees to remove"),u.print(),{content:g(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let n=await w(),i=`${n}${te}`,a=[];if(t)a=s;else if(o)a=o.split(",").map(h=>ye(pe(h.trim())));else{u.setInteractive();let[h,y]=await Promise.all([C(),x()]),b=new Map(y.map(R=>[R.branch,E(R.title)]));a=await ur(A({branches:s,descriptions:h,types:b}),{required:!0})}gd(a,s);let c=a.length===s.length;c?u.addOption("--all",!0):u.addOption("--versions",Je(a)),await D(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let p=await ee(),d=await Kr({branches:a,worktreeDir:i,repoName:p,pruneFolder:c});await Zr({projectRoot:n,worktreeDir:i,currentWorktrees:s,removedWorktrees:d,allowEditorRelaunch:!r}),hd(d),u.print();let m={removedWorktrees:d,count:d.length};return{content:g(JSON.stringify(m,null,2)),structuredContent:m}}catch(s){throw rr(s)||s instanceof f?s:(l.error({error:s},"\u274C Error managing worktrees"),new f(s,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},hd=e=>{if(e.length>0){l.info("\u274C Removed worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No unused worktrees to remove")},Nn=v({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches. Over MCP you MUST pass "versions" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named version must be an active worktree, or the call errors without removing anything. What survives: the release branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune".',inputSchema:{versions:zt.string().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Required: each must name an active worktree, or the call errors before removing anything.')},outputSchema:{removedWorktrees:zt.array(zt.string()).describe("List of removed git worktree branches"),count:zt.number().describe("Number of git worktrees removed")},handler:ia});import{z as On}from"zod";import{$ as vd}from"zx";var aa=async e=>{let{confirmedCommand:r}=e;await M({operation:"sync worktrees"});try{let t=await V("release"),o=await w(),s=`${o}${te}`,n=await Ct();await D(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let{branchesToRemove:i}=kd({releasePRsList:n,currentWorktrees:t}),a=await ee(),c=await yd({branches:i,worktreeDir:s,repoName:a});await Zr({projectRoot:o,worktreeDir:s,currentWorktrees:t,removedWorktrees:c,allowEditorRelaunch:!1}),wd(c),u.print();let p={removedWorktrees:c,count:c.length};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}}catch(t){throw rr(t)?t:(l.error({error:t},"\u274C Error managing worktrees"),new f(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},kd=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>et(n)).filter(n=>!r.includes(n))}},yd=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,s=[];for(let n of r)try{let i=`${t}/${n}`,a=de({repoName:o,branch:n});await er(a),await vd`git worktree remove ${i}`,s.push(n)}catch(i){let a=new f(i,{operation:`remove stale worktree for ${n}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});l.error({error:i,branch:n,msg:a.message})}return s},wd=e=>{if(e.length>0){l.info("\u274C Removed worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No unused worktrees to remove")},Dn=v({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.",inputSchema:{},outputSchema:{removedWorktrees:On.array(On.string()).describe("List of removed worktree branches"),count:On.number().describe("Number of worktrees removed during sync")},handler:aa});var Rd=[{key:"develop",label:"Develop"},{key:"release",label:"Release Management"},{key:"worktrees",label:"Worktrees"},{key:"environment",label:"Environment"},{key:"configuration",label:"Configuration"},{key:"vendor",label:"Vendor"},{key:"setup",label:"Setup & Diagnostics"}],qt=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,groupPath:["dev"],longRunning:!0},{cliName:"merge-dev",menuGroup:"release",mcpTool:Wo,mcpExposed:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Go,mcpExposed:!0,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:sn,mcpExposed:!0,groupPath:["release","create"]},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:an,mcpExposed:!0,groupPath:["release","desc-edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Bo,mcpExposed:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Uo,mcpExposed:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Vo,mcpExposed:!1,groupPath:["release","deliver"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:_n,mcpExposed:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:An,mcpExposed:!0,groupPath:["worktrees","list"]},{cliName:"worktrees-reload",menuGroup:"worktrees",mcpTool:In,mcpExposed:!0,groupPath:["worktrees","reload"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Nn,mcpExposed:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Dn,mcpExposed:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Io,mcpExposed:!0,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Ao,mcpExposed:!0,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:vo,mcpExposed:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:_o,mcpExposed:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Oo,mcpExposed:!0,groupPath:["env-token-list"]},{cliName:"config-path",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,groupPath:["config","path"]},{cliName:"config-edit",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,groupPath:["config","edit"],entersAltScreen:!0},{cliName:"vendor-check",menuGroup:"vendor",mcpTool:gn,mcpExposed:!0,groupPath:["vendor","check"]},{cliName:"vendor-diff",menuGroup:"vendor",mcpTool:kn,mcpExposed:!0,groupPath:["vendor","diff"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,groupPath:["vendor","config"]},{cliName:"init",menuGroup:"setup",mcpTool:null,mcpExposed:!1,groupPath:["init"]},{cliName:"doctor",menuGroup:"setup",mcpTool:So,mcpExposed:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:ao,mcpExposed:!0,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Rn,mcpExposed:!0,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["config"]},{cliName:"env-autoload",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["env-autoload"]},{cliName:"env-token-set",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["env-token-remove"]},{cliName:"self-update",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["self-update"]},{cliName:"mcp",menuGroup:null,mcpTool:null,mcpExposed:!1,groupPath:["mcp"]},{cliName:"vendor-manifest",menuGroup:null,mcpTool:yn,mcpExposed:!1,groupPath:["vendor","manifest"]},{cliName:"vendor-sync",menuGroup:null,mcpTool:wn,mcpExposed:!1,groupPath:["vendor","sync"]}],bd=()=>qt.flatMap(e=>e.mcpExposed&&e.mcpTool?[e.mcpTool]:[]),Ed=e=>qt.filter(r=>r.menuGroup===e),xd=e=>qt.some(r=>r.longRunning===!0&&r.groupPath.join(" ")===e);import Fn from"node:process";var Pd="MODULE_TYPELESS_PACKAGE_JSON",Td=(e,r)=>typeof e=="object"&&e!==null?e.code:r,ca=!1,Cd=()=>{if(ca)return;ca=!0;let e=Fn.emitWarning.bind(Fn);Fn.emitWarning=((r,...t)=>{Td(t[0],t[1])!==Pd&&e(r,...t)})};export{g as a,ds as b,Er as c,xr as d,Pr as e,De as f,Xm as g,qa as h,Cs as i,Ss as j,ir as k,$s as l,_s as m,yt as n,wt as o,Ec as p,Eo as q,Ls as r,cr as s,eg as t,xo as u,Po as v,ei as w,ti as x,si as y,ii as z,No as A,pi as B,$t as C,Pl as D,fi as E,hi as F,Ri as G,Ei as H,xi as I,Pi as J,rp as K,Ai as L,Ni as M,Li as N,Gi as O,zi as P,Zi as Q,Yi as R,Gt as S,oa as T,na as U,sa as V,ia as W,aa as X,Rd as Y,qt as Z,bd as _,Ed as $,xd as aa,Cd as ba};
231
- //# sourceMappingURL=chunk-LM7IE2UD.js.map
231
+ //# sourceMappingURL=chunk-3G6O7MCC.js.map
@@ -0,0 +1,2 @@
1
+ import{b as I}from"./chunk-A7FAXZGI.js";import{m as f,q as x}from"./chunk-CHETBZ6M.js";import u from"node:path";var m="infra-kit",g=`${m}@latest`,w=(e,t,n)=>{let r=u.relative(n(u.resolve(e)),u.resolve(t));return r!==""&&!r.startsWith("..")&&!u.isAbsolute(r)},l=(e,t)=>u.resolve(e).split(u.sep).includes(t),z=(e,t)=>{let n=u.resolve(e).split(u.sep),r=n.indexOf("Cellar");return r!==-1&&n[r+1]===t},C=(e,t,n,r)=>{let o=e[t];return o!=null&&o!==""&&w(o,n,r)},H=[{manager:"volta",test:({selfRealPath:e,env:t,realpath:n})=>C(t,"VOLTA_HOME",e,n)||l(e,".volta")||l(e,"volta"),updateCommand:["volta","install",m],canSelfSpawn:!0},{manager:"homebrew",test:({selfRealPath:e})=>z(e,m),updateCommand:["brew","upgrade",m],canSelfSpawn:!1},{manager:"pnpm",test:({selfRealPath:e,env:t,realpath:n})=>C(t,"PNPM_HOME",e,n)||l(e,"pnpm")&&l(e,"global"),updateCommand:["pnpm","add","-g",g],canSelfSpawn:!0},{manager:"bun",test:({selfRealPath:e,env:t,realpath:n})=>C(t,"BUN_INSTALL",e,n)||l(e,".bun"),updateCommand:["bun","add","-g",g],canSelfSpawn:!0},{manager:"yarn",test:({selfRealPath:e})=>l(e,".yarn")||l(e,"yarn")&&l(e,"global"),updateCommand:["yarn","global","add",g],canSelfSpawn:!0},{manager:"npm",test:({selfRealPath:e,env:t,realpath:n})=>C(t,"npm_config_prefix",e,n),updateCommand:["npm","install","-g",g],canSelfSpawn:!0}],N=["npm","install","-g",g],M=e=>{let{selfRealPath:t,env:n,realpath:r,lazyNpmRoot:o}=e,s=H.find(({test:i})=>i({selfRealPath:t,env:n,realpath:r}));if(s)return{manager:s.manager,updateCommand:s.updateCommand,canSelfSpawn:s.canSelfSpawn};let a=o?.();return a!=null&&a!==""&&w(a,t,r)?{manager:"npm",updateCommand:N,canSelfSpawn:!0}:{manager:"unknown",updateCommand:N,canSelfSpawn:!1}},K=(e,t,n)=>l(e,"node_modules")&&w(t,e,n);import{realpathSync as G}from"node:fs";import $ from"node:path";var b=e=>{try{return G(e)}catch{return $.resolve(e)}};import{execFileSync as W}from"node:child_process";import B from"node:process";var Y=3e3,k=()=>{try{let t=W("npm",["root","-g"],{encoding:"utf-8",timeout:Y,stdio:["ignore","pipe","ignore"],shell:B.platform==="win32"}).trim();return t===""?void 0:t}catch{return}};import{spawnSync as ge}from"node:child_process";import{homedir as he}from"node:os";import E from"node:process";import d from"node:fs";import P from"node:path";import Q from"node:process";var X="update-check.lock",Z=1800*1e3,ee=()=>P.join(f(),X),te=(e,t)=>{try{t-d.statSync(e).mtimeMs>Z&&d.rmSync(e,{force:!0})}catch{}},R=(e={})=>{let t=e.nowMs??Date.now(),n=e.lockPath??ee();try{d.mkdirSync(P.dirname(n),{recursive:!0})}catch{return null}let r=()=>{try{return d.openSync(n,"wx",384)}catch{return null}},o=r();if(o===null&&(te(n,t),o=r()),o===null)return null;try{d.writeFileSync(o,String(Q.pid))}catch{}return()=>{try{d.closeSync(o)}catch{}try{d.rmSync(n,{force:!0})}catch{}}};var ne="https://registry.npmjs.org",re=5e3,oe=e=>Object.entries(e).find(([n,r])=>/^npm_config_registry$/i.test(n)&&r!=null&&r!=="")?.[1],ae=e=>{let t=oe(e),n=t!=null&&t!==""?t:ne;for(;n.endsWith("/");)n=n.slice(0,-1);return n},A=async(e,t=fetch)=>{let n=new AbortController,r=setTimeout(()=>{n.abort()},re);try{let o=await t(`${ae(e)}/${m}/latest`,{signal:n.signal,headers:{accept:"application/json"}});if(!o.ok)return null;let a=(await o.json())?.version;return typeof a=="string"&&a!==""?a:null}catch{return null}finally{clearTimeout(r)}};var se=/^(\d+)\.(\d+)\.(\d+)$/,_=e=>{let[t=""]=e.trim().split("+"),[n="",...r]=t.split("-"),o=se.exec(n);if(!o)return null;let[s,a,i]=[o[1],o[2],o[3]].map(Number);return{release:[s,a,i],prerelease:r.length>0?r.join("-").split("."):[]}},L=/^\d+$/,le=(e,t)=>{let n=L.test(e),r=L.test(t);return n&&r?Number(e)-Number(t):n!==r?n?-1:1:e<t?-1:1},ie=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n+=1){let r=e[n],o=t[n];if(r===void 0)return-1;if(o===void 0)return 1;if(r!==o)return le(r,o)}return 0},U=(e,t)=>{let n=_(e),r=_(t);if(!n||!r)return!1;for(let a=0;a<3;a+=1){let i=n.release[a],h=r.release[a];if(i!==h)return i>h}let o=n.prerelease.length===0,s=r.prerelease.length===0;return o!==s?o:ie(n.prerelease,r.prerelease)>0};import T from"node:fs";import O from"node:path";var F="update-check.json",ce=1440*60*1e3,ue=3600*1e3,pe=new Set(["fetch-failed","install-failed","parent-still-running","parent-unknown","installing"]),me=()=>O.join(f(),F),de=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),fe=e=>{if(typeof e!="object"||e===null)return!1;let{lastCheckMs:t,latestVersion:n,updateCommand:r,outcome:o}=e;return typeof t=="number"&&Number.isFinite(t)&&(n===null||typeof n=="string")&&(r===null||de(r))&&(o==null||typeof o=="string")},$e=(e=t=>T.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(me()));return fe(t)?t:null}catch{return null}},D=e=>{let t=f();T.mkdirSync(t,{recursive:!0}),x(O.join(t,F),JSON.stringify(e),384)},We=(e,t)=>{if(!e)return!0;let n=t-e.lastCheckMs;if(n<0)return!0;let r=e.outcome!=null&&pe.has(e.outcome)?ue:ce;return n>=r};var ye=200,Ce=300*1e3,Se=e=>{try{return E.kill(e,0),!0}catch{return!1}},we=e=>new Promise(t=>{setTimeout(t,e)}),Me=async(e,t)=>{let n=t.clock()+Ce;for(;t.clock()<n;){if(!t.isProcessAlive(e))return!0;await t.sleep(ye)}return!t.isProcessAlive(e)},at=async(e,t)=>{let r=(t.acquireLock??R)();if(!r)return"already-running";try{return await be(e,t)}finally{r()}},be=async(e,t)=>{let n=t.env??E.env,r=t.nowMs??Date.now(),o=t.fetchLatest??A,s=t.writeCache??D,a=t.isProcessAlive??Se,i=t.sleep??we,h=t.clock??Date.now,V=t.lazyNpmRoot??k,j=t.spawnSync??ge,c=await o(n),p=(v,q)=>(s({lastCheckMs:r,...q,outcome:v}),v);if(c===null)return p("fetch-failed",{latestVersion:null,updateCommand:null});if(!U(c,e))return p("up-to-date",{latestVersion:c,updateCommand:null});let{canSelfSpawn:J,updateCommand:y}=M({selfRealPath:t.selfRealPath,env:n,realpath:b,lazyNpmRoot:V});if(!J)return p("cannot-self-spawn",{latestVersion:c,updateCommand:y});if(t.parentPid==null)return p("parent-unknown",{latestVersion:c,updateCommand:null});if(s({lastCheckMs:r,latestVersion:c,updateCommand:null,outcome:"installing"}),!await Me(t.parentPid,{isProcessAlive:a,sleep:i,clock:h}))return p("parent-still-running",{latestVersion:c,updateCommand:null});let S=j(y[0],y.slice(1),{stdio:"ignore",shell:E.platform==="win32",cwd:he(),env:I(n),windowsHide:!0});return S.error||S.signal||S.status!==0?p("install-failed",{latestVersion:c,updateCommand:y}):p("installed",{latestVersion:null,updateCommand:null})};export{M as a,K as b,k as c,b as d,U as e,$e as f,We as g,at as h};
2
+ //# sourceMappingURL=chunk-EX66ZFV5.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/install-manager/install-manager.ts", "../src/lib/install-manager/safe-realpath.ts", "../src/lib/install-manager/npm-root.ts", "../src/lib/update-check/run-update-check.ts", "../src/lib/update-check/lock.ts", "../src/lib/update-check/registry.ts", "../src/lib/update-check/semver.ts", "../src/lib/update-check/update-cache.ts"],
4
+ "sourcesContent": ["/**\n * Pure detection of *how* this CLI was installed, so a self-update advisory can name the one command\n * that will actually work. No fs, no spawn, no `process.env` read \u2014 every input is injected, which is\n * what lets the whole matrix be table-tested.\n *\n * Detection is env-first and LAZY: the only signal that costs a subprocess (`npm root -g`) is passed in\n * as `lazyNpmRoot` and consulted solely when every cheaper matcher has missed.\n */\nimport path from 'node:path'\n\n/** The published package this CLI updates itself to. Single source for every suggested argv. */\nexport const PACKAGE_NAME = 'infra-kit'\n\nconst LATEST = `${PACKAGE_NAME}@latest`\n\nexport type InstallManager = 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | 'homebrew' | 'unknown'\n\nexport interface InstallManagerInfo {\n manager: InstallManager\n /** The command to run. Only safe to spawn ourselves when `canSelfSpawn`; otherwise print it. */\n updateCommand: string[]\n /** False when we must not run the command for the user \u2014 either it needs sudo/a tap, or we guessed. */\n canSelfSpawn: boolean\n}\n\n/**\n * Canonicalises a candidate *root* directory. Required, not optional: `selfRealPath` has already had its\n * symlinks followed, so comparing it against a raw `PNPM_HOME`/`npm root -g`/`cwd` compares a resolved\n * path to an unresolved one and silently never matches. macOS is the everyday proof \u2014 `/var` is a symlink\n * to `/private/var`, so a global install under `/var/...` reports `unknown` unless both sides are resolved.\n * Callers inject the real thing; tests inject a stub.\n */\nexport type RealpathFn = (dir: string) => string\n\nexport interface DetectInstallManagerInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises each candidate root before comparison. See {@link RealpathFn}. */\n realpath: RealpathFn\n /** `npm root -g`, deferred: invoked at most once, and only when no cheaper matcher hit. */\n lazyNpmRoot?: () => string | undefined\n}\n\n/**\n * Is `child` inside the `parent` subtree? Boundary-aware: a naive `startsWith` would call\n * `/Users/x/pnpm-ish` a child of `/Users/x/pnpm`. `parent` is canonicalised first because it arrives raw\n * from the environment while `child` is already a realpath.\n */\nconst isWithin = (parent: string, child: string, realpath: RealpathFn): boolean => {\n const rel = path.relative(realpath(path.resolve(parent)), path.resolve(child))\n\n return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)\n}\n\n/** Does `p` contain `name` as a whole path SEGMENT? `/a/node_modules_backup/b` must not match `node_modules`. */\nconst hasSegment = (p: string, name: string): boolean => {\n return path.resolve(p).split(path.sep).includes(name)\n}\n\n/**\n * Is `p` inside a Homebrew keg belonging to the `name` FORMULA \u2014 i.e. `.../Cellar/<name>/<version>/...`?\n *\n * The formula name is what makes this sound. A bare `Cellar` segment says only \"somewhere under a keg\",\n * and the keg it lands in is routinely someone else's: when npm's global prefix is a node keg\n * (`npm config set prefix \"$(brew --prefix node)\"`, or any keg-only `node@X`), an `npm i -g` package\n * installs to `Cellar/node/<v>/lib/node_modules/<pkg>/...` \u2014 brew has never heard of it, yet the segment\n * is right there. Requiring `<name>` to sit directly after `Cellar` is what separates \"brew installed\n * THIS\" from \"brew installed the runtime that installed this\".\n *\n * Works for both keg layouts, since each is rooted at the formula: a plain formula\n * (`Cellar/infra-kit/1.2.3/bin/infra-kit`) and brew's node-CLI layout\n * (`Cellar/infra-kit/1.2.3/libexec/lib/node_modules/infra-kit/dist/cli.js`). Do NOT try to tell them\n * apart by excluding `node_modules` \u2014 the second one contains it.\n */\nconst isBrewKegOf = (p: string, name: string): boolean => {\n const segments = path.resolve(p).split(path.sep)\n const cellar = segments.indexOf('Cellar')\n\n return cellar !== -1 && segments[cellar + 1] === name\n}\n\n/** `env[key]` names a directory that contains `selfRealPath`. Absent/empty env var \u2192 no match. */\nconst underEnvDir = (env: NodeJS.ProcessEnv, key: string, selfRealPath: string, realpath: RealpathFn): boolean => {\n const dir = env[key]\n\n return dir != null && dir !== '' && isWithin(dir, selfRealPath, realpath)\n}\n\ninterface Matcher extends Omit<InstallManagerInfo, 'manager'> {\n manager: InstallManager\n test: (input: Required<Pick<DetectInstallManagerInput, 'selfRealPath' | 'env' | 'realpath'>>) => boolean\n}\n\n/**\n * Ordered, first-hit-wins. Order matters: volta and homebrew wrap an npm-shaped layout, so they must be\n * consulted before the generic npm prefix matcher would claim them.\n */\nconst MATCHERS: Matcher[] = [\n {\n manager: 'volta',\n // volta owns the shim; `volta install` is the correct tool, not a workaround \u2014 so we may run it.\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'VOLTA_HOME', selfRealPath, realpath) ||\n hasSegment(selfRealPath, '.volta') ||\n hasSegment(selfRealPath, 'volta')\n )\n },\n updateCommand: ['volta', 'install', PACKAGE_NAME],\n canSelfSpawn: true,\n },\n {\n manager: 'homebrew',\n // `brew upgrade` can touch the prefix, relink, and prompt \u2014 never ours to run unattended.\n //\n // Our own keg is the ONLY sound signal \u2014 see {@link isBrewKegOf}. Two broader tests look plausible\n // and are both wrong, because each answers \"did brew put something here?\" when the question is \"does\n // brew own THIS package?\":\n // - `HOMEBREW_PREFIX` containment: when node comes from brew, npm's global prefix IS\n // $HOMEBREW_PREFIX, so EVERY `npm i -g` package lands under it, unknown to brew.\n // - a bare `Cellar` segment: an npm prefix pointed at a node keg puts packages inside that keg.\n // Either misfire tells macOS users to run `brew upgrade infra-kit` \u2014 a formula that does not exist \u2014\n // and, far worse, makes the background auto-updater bail with `cannot-self-spawn` forever, so the\n // very fix for it can never reach them. Detection runs on the realpath, and a linked brew bin always\n // resolves into its own keg, so the narrow test has no false negatives to trade for this.\n test: ({ selfRealPath }) => {\n return isBrewKegOf(selfRealPath, PACKAGE_NAME)\n },\n updateCommand: ['brew', 'upgrade', PACKAGE_NAME],\n canSelfSpawn: false,\n },\n {\n manager: 'pnpm',\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'PNPM_HOME', selfRealPath, realpath) ||\n (hasSegment(selfRealPath, 'pnpm') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['pnpm', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'bun',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'BUN_INSTALL', selfRealPath, realpath) || hasSegment(selfRealPath, '.bun')\n },\n updateCommand: ['bun', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'yarn',\n test: ({ selfRealPath }) => {\n return (\n hasSegment(selfRealPath, '.yarn') || (hasSegment(selfRealPath, 'yarn') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['yarn', 'global', 'add', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'npm',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'npm_config_prefix', selfRealPath, realpath)\n },\n updateCommand: ['npm', 'install', '-g', LATEST],\n canSelfSpawn: true,\n },\n]\n\nconst NPM_UPDATE_COMMAND = ['npm', 'install', '-g', LATEST]\n\n/**\n * Identify the package manager that owns `selfRealPath`.\n *\n * `lazyNpmRoot` is the fallback probe and is invoked at most once, only after every env/path matcher has\n * missed \u2014 a global `npm root -g` subprocess is never paid for a pnpm or volta install. When nothing\n * matches we report `unknown` with an npm command that is a *suggestion only* (`canSelfSpawn: false`):\n * running a guessed global install is worse than printing one.\n *\n * @example\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {} })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@latest'], canSelfSpawn: true }\n */\nexport const detectInstallManager = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot } = input\n const hit = MATCHERS.find(({ test }) => {\n return test({ selfRealPath, env, realpath })\n })\n\n if (hit) return { manager: hit.manager, updateCommand: hit.updateCommand, canSelfSpawn: hit.canSelfSpawn }\n\n const npmRoot = lazyNpmRoot?.()\n\n if (npmRoot != null && npmRoot !== '' && isWithin(npmRoot, selfRealPath, realpath)) {\n return { manager: 'npm', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: true }\n }\n\n return { manager: 'unknown', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: false }\n}\n\n/**\n * Is this CLI running from a *project-local* `node_modules` (as opposed to a global root)?\n *\n * The cwd clause is what does the distinguishing \u2014 BOTH a project install and a global root contain a\n * `/node_modules/` segment (`pnpm root -g` is `~/Library/pnpm/global/5/node_modules`). Without it we\n * would nag every global pnpm user to stop using a local install they do not have.\n *\n * Accepted false-negative: invoked from a subdirectory (cwd `project/apps/x`, deps at\n * `project/node_modules`) this returns false and the advisory stays silent. Under-warning is the safe\n * direction for a best-effort, never-throwing advisory \u2014 do not \"fix\" it by dropping the cwd clause.\n *\n * `cwd` is canonicalised before comparison for the same reason `detectInstallManager` canonicalises its\n * roots: `selfRealPath` is a realpath, and comparing it to an unresolved cwd never matches.\n *\n * @example\n * isLocalNodeModulesInstall('/repo/node_modules/infra-kit/dist/cli.js', '/repo', (p) => p) // => true\n */\nexport const isLocalNodeModulesInstall = (selfRealPath: string, cwd: string, realpath: RealpathFn): boolean => {\n return hasSegment(selfRealPath, 'node_modules') && isWithin(cwd, selfRealPath, realpath)\n}\n", "import { realpathSync } from 'node:fs'\nimport path from 'node:path'\n\n/**\n * The impure companion to the pure detection module: canonicalise a directory that may not exist.\n *\n * `realpathSync` throws on a missing path, and candidate roots routinely miss \u2014 `PNPM_HOME` can point at a\n * directory the user never created, `npm root -g` can name a prefix that was removed. A throw there would\n * turn \"we could not identify your install\" into a crash, so an unresolvable path falls back to\n * `path.resolve`, which still normalises `.`/`..` and yields a usable, non-matching absolute path.\n */\nexport const safeRealpath = (dir: string): string => {\n try {\n return realpathSync(dir)\n } catch {\n return path.resolve(dir)\n }\n}\n", "/* eslint-disable sonarjs/no-os-command-from-path */\n/**\n * `npm root -g`, the LAZY fallback for {@link detectInstallManager}.\n *\n * Why it is indispensable: the `npm` matcher keys off `npm_config_prefix`, which npm sets only while npm\n * itself is running. A user who ran `npm i -g infra-kit` months ago and now types `ik` has no such var,\n * so every cheap matcher misses and detection reports `unknown` / `canSelfSpawn: false`. Without this\n * probe the single most common install method can never update itself.\n *\n * Shared by `self-update` (interactive) and the background update worker so the two can never disagree\n * about who owns the install.\n */\nimport { execFileSync } from 'node:child_process'\nimport process from 'node:process'\n\nconst NPM_ROOT_TIMEOUT_MS = 3_000\n\n/**\n * The global npm root, or undefined when npm is absent, slow, or errors. Costs a subprocess, so\n * `detectInstallManager` invokes it at most once and only after every env/path matcher has missed \u2014 a\n * pnpm or volta install never pays for it.\n *\n * Resolving the user's `npm` from PATH is inherent here: we must ask the very package manager that owns\n * this install where its global root is. Pinning an absolute path would defeat the detection.\n *\n * @example\n * defaultLazyNpmRoot() // => '/usr/local/lib/node_modules' | undefined\n */\nexport const defaultLazyNpmRoot = (): string | undefined => {\n try {\n const out = execFileSync('npm', ['root', '-g'], {\n encoding: 'utf-8',\n timeout: NPM_ROOT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n shell: process.platform === 'win32',\n })\n const trimmed = out.trim()\n\n return trimmed === '' ? undefined : trimmed\n } catch {\n return undefined\n }\n}\n", "/**\n * The CHILD half of the auto-update, spawned detached by `maybeAutoUpdate`. It outlives the CLI\n * invocation that started it, so it may take its time and it may replace the binary.\n *\n * WHY IT WAITS FOR THE PARENT TO EXIT \u2014 the load-bearing invariant of this whole feature:\n * `scripts/build.js` sets esbuild `splitting: true`, so `dist/cli.js` lazily imports sibling\n * `chunk-*.js` files at runtime (that is how the Ink TUI stays off the fast path). A package manager\n * installing over `dist/` mid-command deletes chunks the parent has not imported yet, and the parent\n * dies on a dynamic import of a file that no longer exists. Waiting for the parent to exit is what\n * makes a silent background install safe rather than a random crash under `infra-kit dev`.\n */\nimport { spawnSync } from 'node:child_process'\nimport { homedir } from 'node:os'\nimport process from 'node:process'\n\nimport { defaultLazyNpmRoot, detectInstallManager, safeRealpath } from 'src/lib/install-manager'\nimport { packageManagerInstallEnv } from 'src/lib/pm-env'\n\nimport { acquireUpdateLock } from './lock'\nimport { fetchLatestVersion } from './registry'\nimport { isNewerVersion } from './semver'\nimport { writeUpdateCache } from './update-cache'\nimport type { UpdateCache } from './update-cache'\n\n/** How often to re-check whether the parent is gone. */\nexport const PARENT_POLL_INTERVAL_MS = 200\n\n/**\n * Give up waiting after this long. A long-lived parent (`infra-kit dev` runs for hours) must not leave\n * an immortal child pinned to a stale version: we simply skip this cycle. `lastCheckMs` is already\n * persisted by then, so the next short-lived command re-checks after the normal 24h window.\n */\nexport const PARENT_WAIT_TIMEOUT_MS = 5 * 60 * 1000\n\nexport interface RunUpdateCheckDeps {\n env?: NodeJS.ProcessEnv\n nowMs?: number\n fetchLatest?: (env: NodeJS.ProcessEnv) => Promise<string | null>\n writeCache?: typeof writeUpdateCache\n isProcessAlive?: (pid: number) => boolean\n sleep?: (ms: number) => Promise<void>\n /** Monotonic-ish source for the parent-wait deadline. Injected so the timeout is testable without real time. */\n clock?: () => number\n /** `npm root -g` probe. Defaults to the real subprocess; this child is detached, so it can afford one. */\n lazyNpmRoot?: () => string | undefined\n /** Single-flight guard. Returns a release fn, or null when another worker already holds the lock. */\n acquireLock?: () => (() => void) | null\n spawnSync?: typeof spawnSync\n /** Realpath of the installed `dist/cli.js`, used to identify the owning package manager. */\n selfRealPath: string\n parentPid?: number\n}\n\n/** Signal 0 performs the permission/existence check without delivering anything. */\nconst defaultIsProcessAlive = (pid: number): boolean => {\n try {\n process.kill(pid, 0)\n\n return true\n } catch {\n return false\n }\n}\n\nconst defaultSleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\n/**\n * Block until `parentPid` exits or {@link PARENT_WAIT_TIMEOUT_MS} elapses. Returns whether the parent\n * is actually gone \u2014 the caller must not install on a timeout.\n */\nconst waitForParentExit = async (\n parentPid: number,\n deps: Required<Pick<RunUpdateCheckDeps, 'isProcessAlive' | 'sleep' | 'clock'>>,\n): Promise<boolean> => {\n const deadline = deps.clock() + PARENT_WAIT_TIMEOUT_MS\n\n while (deps.clock() < deadline) {\n if (!deps.isProcessAlive(parentPid)) return true\n\n await deps.sleep(PARENT_POLL_INTERVAL_MS)\n }\n\n return !deps.isProcessAlive(parentPid)\n}\n\nexport type UpdateCheckOutcome =\n | 'installed'\n | 'install-failed'\n | 'up-to-date'\n | 'fetch-failed'\n | 'cannot-self-spawn'\n | 'parent-still-running'\n | 'parent-unknown'\n | 'already-running'\n\n/**\n * Fetch, decide, and (when safe) install \u2014 returning WHY it did what it did so tests can distinguish\n * \"no update\" from \"could not install\". Never throws.\n *\n * `lastCheckMs` is written from the ATTEMPT, before any early return. If it were written only on\n * success, an offline user would re-spawn a doomed child on every single command.\n *\n * @example\n * await runUpdateCheck('0.1.130', { selfRealPath: '/usr/local/lib/node_modules/infra-kit/dist/cli.js' })\n * // => 'installed'\n */\nexport const runUpdateCheck = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const acquireLock = deps.acquireLock ?? acquireUpdateLock\n\n // Single-flight. N shells launched at once all read the same stale cache and each spawns a worker;\n // the cache throttle cannot stop them because it is only written after the fetch returns. Without\n // this, a pending update means N concurrent `npm install -g` over one global directory.\n const release = acquireLock()\n\n if (!release) return 'already-running'\n\n try {\n return await runUpdateCheckLocked(currentVersion, deps)\n } finally {\n release()\n }\n}\n\nconst runUpdateCheckLocked = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const env = deps.env ?? process.env\n const nowMs = deps.nowMs ?? Date.now()\n const fetchLatest = deps.fetchLatest ?? fetchLatestVersion\n const writeCache = deps.writeCache ?? writeUpdateCache\n const isProcessAlive = deps.isProcessAlive ?? defaultIsProcessAlive\n const sleep = deps.sleep ?? defaultSleep\n const clock = deps.clock ?? Date.now\n const lazyNpmRoot = deps.lazyNpmRoot ?? defaultLazyNpmRoot\n const spawn = deps.spawnSync ?? spawnSync\n\n const latestVersion = await fetchLatest(env)\n\n // Every path below writes the cache EXACTLY once, and always with `lastCheckMs: nowMs` \u2014 the throttle\n // burns on the ATTEMPT, never on success. If it burned only on success, an offline user would respawn\n // a doomed child on every command.\n const finish = (\n outcome: UpdateCheckOutcome,\n cache: Omit<UpdateCache, 'lastCheckMs' | 'outcome'>,\n ): UpdateCheckOutcome => {\n // `outcome` is recorded on EVERY write: it is what lets a reader (human or `isStale`) tell a settled\n // `installed`/`up-to-date` from a transient `fetch-failed`, all of which otherwise write an identical\n // `{latestVersion:null}`. See `UpdateCache.outcome`.\n writeCache({ lastCheckMs: nowMs, ...cache, outcome })\n\n return outcome\n }\n\n if (latestVersion === null) return finish('fetch-failed', { latestVersion: null, updateCommand: null })\n if (!isNewerVersion(latestVersion, currentVersion))\n return finish('up-to-date', { latestVersion, updateCommand: null })\n\n // `lazyNpmRoot` is what makes the COMMON case work: a plain `npm i -g infra-kit` leaves no\n // `npm_config_prefix` in the user's shell, so every cheap matcher misses and detection would report\n // `unknown` / `canSelfSpawn: false`. Without this probe the auto-update would silently degrade to a\n // notice for the majority of installs. The subprocess is affordable here and nowhere else.\n const { canSelfSpawn, updateCommand } = detectInstallManager({\n selfRealPath: deps.selfRealPath,\n env,\n realpath: safeRealpath,\n lazyNpmRoot,\n })\n\n // Homebrew relinks its prefix and may prompt; an unknown location means the command is a guess.\n // Both stay the user's call, so record the command for `maybeAutoUpdate` to print next invocation.\n if (!canSelfSpawn) return finish('cannot-self-spawn', { latestVersion, updateCommand })\n\n // Fail SAFE. Without a parent to outlive we cannot know whether a live CLI is still lazily importing\n // `chunk-*.js` out of the `dist/` we are about to replace, so we skip the cycle rather than install\n // blind. The real spawn always passes `--parent-pid`; only a hand-run worker lands here.\n if (deps.parentPid == null) return finish('parent-unknown', { latestVersion, updateCommand: null })\n\n // Burn the throttle NOW, before the two unbounded-ish operations below (a 5-minute parent wait, then an\n // install of no fixed duration). Everything after this point can take many minutes, and until the cache\n // is written it still reads as STALE \u2014 so every new shell in that window spawns its own worker, and the\n // single-flight lock becomes the only thing standing between them and concurrent `npm install -g` runs\n // over one global directory. The lock is reaped by mtime (LOCK_STALE_MS), so a slow enough install has\n // its live lock stolen and we get exactly the pile-up the lock exists to prevent.\n //\n // Writing the stamp here makes the throttle \u2014 not the lock \u2014 the primary guard, which is what the cache\n // was always for. `finish()` overwrites this with the real outcome; this is the only path that writes\n // the cache twice, and deliberately so.\n //\n // `outcome: 'installing'` is a RETRYABLE checkpoint (see `RETRYABLE_OUTCOMES`): if the worker is killed\n // mid-install (machine sleeps, SIGKILL) and never reaches `finish()`, this stamp is what the next run\n // reads \u2014 and the short retry window lets it try again in an hour rather than a full day.\n writeCache({ lastCheckMs: nowMs, latestVersion, updateCommand: null, outcome: 'installing' })\n\n const parentGone = await waitForParentExit(deps.parentPid, { isProcessAlive, sleep, clock })\n\n // A long-lived parent (`infra-kit dev`) outlasted the wait. Stay silent and retry next window.\n if (!parentGone) return finish('parent-still-running', { latestVersion, updateCommand: null })\n\n // `shell` on win32 so the `.cmd` shims npm/pnpm/yarn ship as global bins resolve.\n //\n // `packageManagerInstallEnv` strips the inherited npx/dlx markers \u2014 which otherwise make\n // pnpm/portless-style tools believe they were invoked via `npx`/`dlx` and refuse to run \u2014 while KEEPING\n // `npm_config_prefix` and `npm_config_registry`. Using the blunt `withoutPackageManagerEnv` here was a\n // bug: it also erased the prefix that `detectInstallManager` had just matched on, so we would detect a\n // global install at prefix P and then install into the default prefix instead \u2014 silently, forever. See\n // the module doc on `packageManagerInstallEnv`.\n //\n // `cwd` is pinned to the home directory, and this is a SECURITY control, not tidiness: npm resolves\n // `registry=` from an `.npmrc` on disk relative to the cwd. Inheriting the caller's cwd would let any\n // repo containing a hostile `.npmrc` silently redirect this unattended `install -g` to an attacker's\n // registry, executing its lifecycle scripts. Stripping `npm_config_registry` from the env does NOT\n // close that hole, because the redirect lives in a file, not the environment.\n const result = spawn(updateCommand[0] as string, updateCommand.slice(1), {\n stdio: 'ignore',\n shell: process.platform === 'win32',\n cwd: homedir(),\n env: packageManagerInstallEnv(env),\n windowsHide: true,\n })\n\n // Record the manual command so a persistently failing silent install (EACCES on a root-owned global\n // dir, say) still surfaces ONE actionable line, instead of failing invisibly forever.\n if (result.error || result.signal || result.status !== 0) {\n return finish('install-failed', { latestVersion, updateCommand })\n }\n\n // The installed version is now `latestVersion`; clear it so the next run does not re-notify.\n return finish('installed', { latestVersion: null, updateCommand: null })\n}\n", "/**\n * Single-flight lock for the background update worker.\n *\n * Without it, N shells starting at once all read the same stale cache and each spawns a worker \u2014 and\n * once a newer version exists, each of those runs `npm install -g` concurrently, over the same global\n * directory. (Measured: five concurrent `ik` invocations spawn five workers.) The throttle in the cache\n * cannot prevent this: it is only written AFTER the fetch returns, long after the other workers launched.\n *\n * `openSync(path, 'wx')` is the primitive \u2014 an atomic create-if-absent, so exactly one worker wins even\n * if all of them call it in the same millisecond.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { getCacheRoot } from 'src/lib/constants'\n\nexport const LOCK_FILE_NAME = 'update-check.lock'\n\n/**\n * A lock older than this is assumed to belong to a worker that was killed before it could clean up.\n *\n * Must exceed the worker's ENTIRE critical section, and the install is part of it: the lock is held across\n * `fetch` (\u22642.5s) + the parent wait (\u22645min) + `npm install -g`, which has no bound at all \u2014 a cold cache on\n * a slow link can run for many minutes. The previous 10 minutes was budgeted from the wait and the fetch\n * alone, silently omitting the very operation the lock exists to serialise. A slow enough install therefore\n * had its own LIVE lock reaped as stale by the next worker, which then ran a second concurrent\n * `npm install -g` over the same global directory \u2014 precisely the pile-up described above.\n *\n * The throttle, not this timeout, is now the primary guard: `runUpdateCheck` stamps `lastCheckMs` BEFORE\n * the wait and the install, so concurrent shells stop spawning workers at all. This value only has to\n * outlive a plausible install, and is deliberately generous \u2014 the cost of being too large is that a worker\n * killed mid-install delays the next attempt, which the 24h throttle would delay anyway.\n */\nexport const LOCK_STALE_MS = 30 * 60 * 1000\n\nexport const lockFilePath = (): string => {\n return path.join(getCacheRoot(), LOCK_FILE_NAME)\n}\n\nexport interface LockDeps {\n nowMs?: number\n lockPath?: string\n}\n\n/** Delete a lock whose mtime predates the staleness window. Best-effort: losing the race is harmless. */\nconst reapIfStale = (lockPath: string, nowMs: number): void => {\n try {\n if (nowMs - fs.statSync(lockPath).mtimeMs > LOCK_STALE_MS) fs.rmSync(lockPath, { force: true })\n } catch {\n // Vanished under us \u2014 another worker reaped it. Nothing to do.\n }\n}\n\n/**\n * Take the lock, or return null when another worker already holds it.\n *\n * Returns a release function rather than a boolean so the caller cannot forget which path releases:\n * there is exactly one handle, and it is the only thing that can unlink the file.\n *\n * @example\n * const release = acquireUpdateLock()\n * if (!release) return 'already-running'\n * try { ... } finally { release() }\n */\nexport const acquireUpdateLock = (deps: LockDeps = {}): (() => void) | null => {\n const nowMs = deps.nowMs ?? Date.now()\n const lockPath = deps.lockPath ?? lockFilePath()\n\n try {\n fs.mkdirSync(path.dirname(lockPath), { recursive: true })\n } catch {\n return null\n }\n\n const open = (): number | null => {\n try {\n // 'wx' fails with EEXIST if the file is already there: an atomic test-and-set.\n return fs.openSync(lockPath, 'wx', 0o600)\n } catch {\n return null\n }\n }\n\n let fd = open()\n\n if (fd === null) {\n reapIfStale(lockPath, nowMs)\n // One retry only. If a live worker holds the lock, we are the loser and must simply stand down.\n fd = open()\n }\n\n if (fd === null) return null\n\n try {\n fs.writeFileSync(fd, String(process.pid))\n } catch {\n // The pid is a debugging aid, not part of the protocol; the lock is held either way.\n }\n\n return () => {\n try {\n fs.closeSync(fd)\n } catch {\n // Already closed.\n }\n\n try {\n fs.rmSync(lockPath, { force: true })\n } catch {\n // Already gone; a later worker will reap it via LOCK_STALE_MS regardless.\n }\n }\n}\n", "/**\n * Ask the npm registry for the `latest` dist-tag. Node >= 24 (see `engines`), so global `fetch` is\n * available and this needs no dependency.\n */\nimport { PACKAGE_NAME } from 'src/lib/install-manager'\n\nexport const DEFAULT_REGISTRY = 'https://registry.npmjs.org'\n\n/**\n * Bounded so a hanging registry can never keep a detached child alive indefinitely. 5s, not a tighter\n * bound: the abbreviated `/pkg/latest` endpoint is usually ~20-900ms, but a cold TLS/DNS handshake in a\n * freshly-spawned worker can spike past a 2.5s cap \u2014 and a single trip used to cost a `fetch-failed` that\n * pushed the next check a full day out. A detached child that lingers a few extra seconds harms nothing.\n */\nexport const FETCH_TIMEOUT_MS = 5_000\n\n/**\n * The registry this install actually talks to. A user behind a corporate mirror has `npm_config_registry`\n * set; hitting registry.npmjs.org directly would either fail closed (firewall) or, worse, report a public\n * version they cannot install.\n *\n * @example\n * registryUrl({ npm_config_registry: 'https://nexus.corp/repo/npm/' }) // => 'https://nexus.corp/repo/npm'\n */\n/**\n * `npm_config_registry` in WHICHEVER case the environment spells it.\n *\n * A bare `env.npm_config_registry` reads only the lowercase form, but npm itself matches `/^npm_config_/i`,\n * and POSIX `process.env` is case-SENSITIVE \u2014 so a `NPM_CONFIG_REGISTRY` (the form Dockerfiles and CI\n * images export) was invisible here while npm honoured it. The check then queried the public registry that\n * the install would never touch: the two halves of this feature were exactly inverted.\n */\nconst configuredRegistry = (env: NodeJS.ProcessEnv): string | undefined => {\n const hit = Object.entries(env).find(([key, value]) => {\n return /^npm_config_registry$/i.test(key) && value != null && value !== ''\n })\n\n return hit?.[1]\n}\n\nexport const registryUrl = (env: NodeJS.ProcessEnv): string => {\n const configured = configuredRegistry(env)\n\n let base = configured != null && configured !== '' ? configured : DEFAULT_REGISTRY\n\n // A `/\\/+$/` regex would do this in one line, but its backtracking is super-linear on a hostile input.\n while (base.endsWith('/')) {\n base = base.slice(0, -1)\n }\n\n return base\n}\n\n/**\n * The published `latest` version, or null on ANY failure (offline, timeout, non-200, malformed body).\n * Never throws: a failed check must be indistinguishable from \"no update available\" to every caller.\n *\n * @example\n * await fetchLatestVersion(process.env) // => '0.1.131' | null\n */\nexport const fetchLatestVersion = async (\n env: NodeJS.ProcessEnv,\n fetchFn: typeof fetch = fetch,\n): Promise<string | null> => {\n const controller = new AbortController()\n const timer = setTimeout(() => {\n controller.abort()\n }, FETCH_TIMEOUT_MS)\n\n try {\n const response = await fetchFn(`${registryUrl(env)}/${PACKAGE_NAME}/latest`, {\n signal: controller.signal,\n headers: { accept: 'application/json' },\n })\n\n if (!response.ok) return null\n\n const body: unknown = await response.json()\n const version = (body as { version?: unknown } | null)?.version\n\n return typeof version === 'string' && version !== '' ? version : null\n } catch {\n return null\n } finally {\n clearTimeout(timer)\n }\n}\n", "/**\n * Registry-safe version comparison for the auto-update check.\n *\n * Deliberately NOT `src/lib/version-utils`: `parseVersion` there does `versionStr.slice(1)` because it\n * only ever sees `v`-prefixed release tags, so it turns a bare registry version (`0.1.130`) into\n * `[NaN, 1, 130]`. Feeding npm's `dist-tags.latest` through it silently compares NaNs and never fires.\n * These inputs are bare semver from `registry.npmjs.org` and from our own `package.json`.\n */\n\n/** `1.2.3-beta.4+build` \u2192 the `[1, 2, 3]` release triple and the `beta.4` prerelease, or null if unparsable. */\ninterface ParsedVersion {\n release: [number, number, number]\n /** Dot-separated prerelease identifiers, empty when this is a final release. */\n prerelease: string[]\n}\n\nconst RELEASE_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/**\n * Parse bare semver. Returns null (never throws, never NaNs) for anything that is not\n * `major.minor.patch` with optional `-prerelease` and `+build` \u2014 a garbled registry body must read as\n * \"no update\", not as \"update to NaN\".\n *\n * @example\n * parseSemver('0.1.130') // => { release: [0, 1, 130], prerelease: [] }\n * parseSemver('1.0.0-rc.1+abc') // => { release: [1, 0, 0], prerelease: ['rc', '1'] }\n * parseSemver('v1.0.0') // => null\n */\nexport const parseSemver = (version: string): ParsedVersion | null => {\n // Build metadata is ignored entirely by semver precedence rules.\n const [withoutBuild = ''] = version.trim().split('+')\n const [core = '', ...prereleaseParts] = withoutBuild.split('-')\n const match = RELEASE_PATTERN.exec(core)\n\n if (!match) return null\n\n const [major, minor, patch] = [match[1], match[2], match[3]].map(Number) as [number, number, number]\n\n return {\n release: [major, minor, patch],\n // Re-join on '-' so `1.0.0-rc-1` keeps its hyphen inside a single identifier.\n prerelease: prereleaseParts.length > 0 ? prereleaseParts.join('-').split('.') : [],\n }\n}\n\nconst NUMERIC_IDENTIFIER = /^\\d+$/\n\n/** Compare two unequal prerelease identifiers per semver \u00A711. Numeric ones rank below alphanumeric ones. */\nconst compareIdentifier = (left: string, right: string): number => {\n const leftNumeric = NUMERIC_IDENTIFIER.test(left)\n const rightNumeric = NUMERIC_IDENTIFIER.test(right)\n\n if (leftNumeric && rightNumeric) return Number(left) - Number(right)\n if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1\n\n return left < right ? -1 : 1\n}\n\n/** Compare prerelease identifier lists. A shorter list has lower precedence: `1.0.0-rc` < `1.0.0-rc.1`. */\nconst comparePrerelease = (a: string[], b: string[]): number => {\n for (let index = 0; index < Math.max(a.length, b.length); index += 1) {\n const left = a[index]\n const right = b[index]\n\n if (left === undefined) return -1\n if (right === undefined) return 1\n if (left !== right) return compareIdentifier(left, right)\n }\n\n return 0\n}\n\n/**\n * Is `latest` strictly newer than `current`? False when either is unparsable, so a bad registry\n * response can never trigger an install.\n *\n * The load-bearing case is NUMERIC, not lexical, comparison: `0.1.9` must be older than `0.1.130`.\n * A string compare would order them the other way and pin every user to the older build forever.\n *\n * A final release outranks its own prereleases (`1.0.0` > `1.0.0-rc.1`), so a user on `rc` is offered\n * the release, and a user on the release is never \"downgraded\" to an rc.\n *\n * @example\n * isNewerVersion('0.1.130', '0.1.9') // => true (numeric, not lexical)\n * isNewerVersion('1.0.0', '1.0.0-rc.1') // => true\n * isNewerVersion('0.1.130', '0.1.130') // => false\n * isNewerVersion('garbage', '0.1.0') // => false\n */\nexport const isNewerVersion = (latest: string, current: string): boolean => {\n const parsedLatest = parseSemver(latest)\n const parsedCurrent = parseSemver(current)\n\n if (!parsedLatest || !parsedCurrent) return false\n\n for (let index = 0; index < 3; index += 1) {\n const left = parsedLatest.release[index] as number\n const right = parsedCurrent.release[index] as number\n\n if (left !== right) return left > right\n }\n\n const latestIsFinal = parsedLatest.prerelease.length === 0\n const currentIsFinal = parsedCurrent.prerelease.length === 0\n\n if (latestIsFinal !== currentIsFinal) return latestIsFinal\n\n return comparePrerelease(parsedLatest.prerelease, parsedCurrent.prerelease) > 0\n}\n", "/**\n * The throttle + notice state for the auto-update check, at `$cacheRoot/update-check.json`.\n *\n * `getCacheRoot()` \u2014 NOT `getSessionCacheDir()`, which throws unless `INFRA_KIT_SESSION` is set. A user\n * who installed this CLI globally and never ran `infra-kit init` has no session, and the update check\n * must still work for exactly that person.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport { atomicWriteFileSync, getCacheRoot } from 'src/lib/constants'\n\nexport const CACHE_FILE_NAME = 'update-check.json'\n\n/** Refresh at most once a day after a SETTLED check. A background check is cheap, but not once per shell command. */\nexport const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000\n\n/**\n * The shorter re-check window after a TRANSIENT outcome (see {@link RETRYABLE_OUTCOMES}). A single\n * failed fetch used to burn the full 24h {@link CHECK_INTERVAL_MS}, so one network blip locked\n * auto-update out for a whole day \u2014 exactly the failure a publisher hits pushing a release mid-window.\n * An hour still stops the per-command spawn storm the throttle exists to prevent.\n */\nexport const RETRY_INTERVAL_MS = 60 * 60 * 1000\n\n/**\n * Outcomes that did NOT reach a settled \"checked, nothing left to do\" state \u2014 a transient failure, or\n * an install we could not complete this cycle. They get the short {@link RETRY_INTERVAL_MS}; every\n * settled outcome (`up-to-date`, `installed`, `cannot-self-spawn`) keeps the 24h window.\n *\n * Most members mirror `UpdateCheckOutcome` in `run-update-check.ts` \u2014 keep the two in step \u2014 with two\n * deliberate mismatches: `installing` is a cache-ONLY mid-install checkpoint (not a union member), and\n * the union's `already-running` never reaches the cache (it returns before any write). This set has no\n * compile-time tie to the union (that would import-cycle), so a rename there fails silently HERE \u2014 the\n * membership guard test in `__tests__/update-cache.test.ts` is what catches that drift.\n *\n * ACCEPTED tradeoff: `install-failed` covers both a transient blip and a permanently broken setup (EACCES\n * on a root-owned global dir), so a broken install now retries hourly rather than daily. It is bounded \u2014\n * single-flight lock, silent `stdio: 'ignore'`, and the manual command still surfaced via the notice \u2014 and\n * favouring fast recovery of the transient case is the point of this change.\n */\nconst RETRYABLE_OUTCOMES = new Set([\n 'fetch-failed',\n 'install-failed',\n 'parent-still-running',\n 'parent-unknown',\n 'installing',\n])\n\nexport interface UpdateCache {\n /**\n * When the last check was ATTEMPTED \u2014 never \"when it last succeeded\". An offline user whose fetch\n * throws must still burn their window, or every single command spawns another doomed child.\n */\n lastCheckMs: number\n /** Latest version seen on the registry, or null when the last attempt failed. */\n latestVersion: string | null\n /**\n * The command the USER must run, set only when the worker was not allowed to install for them\n * (Homebrew, or an install location it could not identify). Null means \"handled, say nothing\".\n *\n * The worker decides this, not the reader: identifying the owning package manager can cost an\n * `npm root -g` subprocess, and the CLI startup path must never pay for one. The background child\n * already pays it, so it writes the verdict down.\n */\n updateCommand: string[] | null\n /**\n * The last check's terminal outcome (`installed`, `fetch-failed`, `up-to-date`, \u2026), or absent on a\n * cache written before this field existed. Two jobs: (1) it is the signal {@link isStale} uses to\n * pick the short retry window after a transient failure; (2) it is the ONLY thing that makes the file\n * legible \u2014 a successful `installed` and a failed `fetch-failed` both write a byte-identical\n * `{latestVersion:null, updateCommand:null}`, so without this the cache cannot say which happened.\n */\n outcome?: string | null\n}\n\nexport const cacheFilePath = (): string => {\n return path.join(getCacheRoot(), CACHE_FILE_NAME)\n}\n\nconst isStringArray = (value: unknown): value is string[] => {\n return (\n Array.isArray(value) &&\n value.every((entry) => {\n return typeof entry === 'string'\n })\n )\n}\n\nconst isUpdateCache = (value: unknown): value is UpdateCache => {\n if (typeof value !== 'object' || value === null) return false\n\n const { lastCheckMs, latestVersion, updateCommand, outcome } = value as Partial<UpdateCache>\n\n return (\n typeof lastCheckMs === 'number' &&\n Number.isFinite(lastCheckMs) &&\n (latestVersion === null || typeof latestVersion === 'string') &&\n (updateCommand === null || isStringArray(updateCommand)) &&\n (outcome === undefined || outcome === null || typeof outcome === 'string')\n )\n}\n\n/**\n * Read the cache, or null when it is missing/unreadable/corrupt. A null read means \"stale\" to every\n * caller, so a first run and a hand-mangled file behave identically: check again.\n *\n * @example\n * readUpdateCache() // => { lastCheckMs: 1770000000000, latestVersion: '0.1.131' } | null\n */\nexport const readUpdateCache = (\n readFile: (p: string) => string = (p) => {\n return fs.readFileSync(p, 'utf8')\n },\n): UpdateCache | null => {\n try {\n const parsed: unknown = JSON.parse(readFile(cacheFilePath()))\n\n return isUpdateCache(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\n/**\n * Persist the check result. Creates `$cacheRoot` first: `atomicWriteFileSync` writes a temp file\n * beside the target and renames, so it throws ENOENT on a machine that has never had a `~/.cache/infra-kit`.\n * Without this mkdir the write fails, `lastCheckMs` never lands, and the throttle degrades into a\n * detached-child spawn on every invocation.\n *\n * @example\n * writeUpdateCache({ lastCheckMs: Date.now(), latestVersion: '0.1.131' })\n */\nexport const writeUpdateCache = (cache: UpdateCache): void => {\n const root = getCacheRoot()\n\n fs.mkdirSync(root, { recursive: true })\n atomicWriteFileSync(path.join(root, CACHE_FILE_NAME), JSON.stringify(cache), 0o600)\n}\n\n/**\n * Has the throttle window elapsed? A missing cache is stale by definition (first run).\n *\n * A `lastCheckMs` in the future (clock skew, or a restored backup) also reads as stale rather than\n * locking the user out of updates until their clock catches up.\n *\n * The window is outcome-aware: a transient last outcome (see {@link RETRYABLE_OUTCOMES}) is re-checked\n * after {@link RETRY_INTERVAL_MS}, every settled outcome after {@link CHECK_INTERVAL_MS}. A cache with\n * no `outcome` (pre-`outcome` format, or a hand-written file) falls through to the 24h bucket \u2014 the\n * safe default that cannot turn into an every-hour spawn storm.\n *\n * @example\n * isStale(null, 1_000) // => true\n * isStale({ lastCheckMs: 0, latestVersion: null, updateCommand: null }, CHECK_INTERVAL_MS + 1) // => true\n */\nexport const isStale = (cache: UpdateCache | null, nowMs: number): boolean => {\n if (!cache) return true\n\n const elapsed = nowMs - cache.lastCheckMs\n\n if (elapsed < 0) return true\n\n const interval =\n cache.outcome != null && RETRYABLE_OUTCOMES.has(cache.outcome) ? RETRY_INTERVAL_MS : CHECK_INTERVAL_MS\n\n return elapsed >= interval\n}\n"],
5
+ "mappings": "uFAQA,OAAOA,MAAU,YAGV,IAAMC,EAAe,YAEtBC,EAAS,GAAGD,CAAY,UAoCxBE,EAAW,CAACC,EAAgBC,EAAeC,IAAkC,CACjF,IAAMC,EAAMP,EAAK,SAASM,EAASN,EAAK,QAAQI,CAAM,CAAC,EAAGJ,EAAK,QAAQK,CAAK,CAAC,EAE7E,OAAOE,IAAQ,IAAM,CAACA,EAAI,WAAW,IAAI,GAAK,CAACP,EAAK,WAAWO,CAAG,CACpE,EAGMC,EAAa,CAACC,EAAWC,IACtBV,EAAK,QAAQS,CAAC,EAAE,MAAMT,EAAK,GAAG,EAAE,SAASU,CAAI,EAkBhDC,EAAc,CAACF,EAAWC,IAA0B,CACxD,IAAME,EAAWZ,EAAK,QAAQS,CAAC,EAAE,MAAMT,EAAK,GAAG,EACzCa,EAASD,EAAS,QAAQ,QAAQ,EAExC,OAAOC,IAAW,IAAMD,EAASC,EAAS,CAAC,IAAMH,CACnD,EAGMI,EAAc,CAACC,EAAwBC,EAAaC,EAAsBX,IAAkC,CAChH,IAAMY,EAAMH,EAAIC,CAAG,EAEnB,OAAOE,GAAO,MAAQA,IAAQ,IAAMf,EAASe,EAAKD,EAAcX,CAAQ,CAC1E,EAWMa,EAAsB,CAC1B,CACE,QAAS,QAET,KAAM,CAAC,CAAE,aAAAF,EAAc,IAAAF,EAAK,SAAAT,CAAS,IAEjCQ,EAAYC,EAAK,aAAcE,EAAcX,CAAQ,GACrD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,CAACS,EAAc,OAAOJ,EAAO,oBAAqB,CAAE,cAAAD,EAAe,cAAAM,CAAc,CAAC,EAKtF,GAAI1B,EAAK,WAAa,KAAM,OAAOqB,EAAO,iBAAkB,CAAE,cAAAD,EAAe,cAAe,IAAK,CAAC,EAqBlG,GALAT,EAAW,CAAE,YAAaH,EAAO,cAAAY,EAAe,cAAe,KAAM,QAAS,YAAa,CAAC,EAKxF,CAHe,MAAMtB,GAAkBE,EAAK,UAAW,CAAE,eAAAa,EAAgB,MAAAC,EAAO,MAAAC,CAAM,CAAC,EAG1E,OAAOM,EAAO,uBAAwB,CAAE,cAAAD,EAAe,cAAe,IAAK,CAAC,EAgB7F,IAAMS,EAASX,EAAMQ,EAAc,CAAC,EAAaA,EAAc,MAAM,CAAC,EAAG,CACvE,MAAO,SACP,MAAOhC,EAAQ,WAAa,QAC5B,IAAKoC,GAAQ,EACb,IAAKC,EAAyBxB,CAAG,EACjC,YAAa,EACf,CAAC,EAID,OAAIsB,EAAO,OAASA,EAAO,QAAUA,EAAO,SAAW,EAC9CR,EAAO,iBAAkB,CAAE,cAAAD,EAAe,cAAAM,CAAc,CAAC,EAI3DL,EAAO,YAAa,CAAE,cAAe,KAAM,cAAe,IAAK,CAAC,CACzE",
6
+ "names": ["path", "PACKAGE_NAME", "LATEST", "isWithin", "parent", "child", "realpath", "rel", "hasSegment", "p", "name", "isBrewKegOf", "segments", "cellar", "underEnvDir", "env", "key", "selfRealPath", "dir", "MATCHERS", "NPM_UPDATE_COMMAND", "detectInstallManager", "input", "lazyNpmRoot", "hit", "test", "npmRoot", "isLocalNodeModulesInstall", "cwd", "realpathSync", "path", "safeRealpath", "dir", "execFileSync", "process", "NPM_ROOT_TIMEOUT_MS", "defaultLazyNpmRoot", "trimmed", "spawnSync", "homedir", "process", "fs", "path", "process", "LOCK_FILE_NAME", "LOCK_STALE_MS", "lockFilePath", "path", "getCacheRoot", "reapIfStale", "lockPath", "nowMs", "fs", "acquireUpdateLock", "deps", "open", "fd", "process", "DEFAULT_REGISTRY", "FETCH_TIMEOUT_MS", "configuredRegistry", "env", "key", "value", "registryUrl", "configured", "base", "fetchLatestVersion", "fetchFn", "controller", "timer", "response", "PACKAGE_NAME", "version", "RELEASE_PATTERN", "parseSemver", "version", "withoutBuild", "core", "prereleaseParts", "match", "major", "minor", "patch", "NUMERIC_IDENTIFIER", "compareIdentifier", "left", "right", "leftNumeric", "rightNumeric", "comparePrerelease", "a", "b", "index", "isNewerVersion", "latest", "current", "parsedLatest", "parsedCurrent", "latestIsFinal", "currentIsFinal", "fs", "path", "CACHE_FILE_NAME", "CHECK_INTERVAL_MS", "RETRY_INTERVAL_MS", "RETRYABLE_OUTCOMES", "cacheFilePath", "path", "getCacheRoot", "isStringArray", "value", "entry", "isUpdateCache", "lastCheckMs", "latestVersion", "updateCommand", "outcome", "readUpdateCache", "readFile", "p", "fs", "parsed", "writeUpdateCache", "cache", "root", "atomicWriteFileSync", "isStale", "nowMs", "elapsed", "interval", "PARENT_POLL_INTERVAL_MS", "PARENT_WAIT_TIMEOUT_MS", "defaultIsProcessAlive", "pid", "process", "defaultSleep", "ms", "resolve", "waitForParentExit", "parentPid", "deps", "deadline", "runUpdateCheck", "currentVersion", "release", "acquireUpdateLock", "runUpdateCheckLocked", "env", "nowMs", "fetchLatest", "fetchLatestVersion", "writeCache", "writeUpdateCache", "isProcessAlive", "sleep", "clock", "lazyNpmRoot", "defaultLazyNpmRoot", "spawn", "spawnSync", "latestVersion", "finish", "outcome", "cache", "isNewerVersion", "canSelfSpawn", "updateCommand", "detectInstallManager", "safeRealpath", "result", "homedir", "packageManagerInstallEnv"]
7
+ }
@@ -1,2 +1,2 @@
1
- var i={name:"infra-kit",type:"module",version:"0.3.4",files:["dist"],description:"infra-kit",bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js"},engines:{node:">=24.x"},scripts:{inspector:"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug",build:"pnpm run clean-artifacts && node ./scripts/build.js",prepack:"pnpm run build",prepublishOnly:"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 --quiet --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:"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.33.1","@inquirer/checkbox":"^5.2.1","@inquirer/confirm":"^6.1.1","@inquirer/password":"^5.0.2","@inquirer/select":"^5.2.1","@modelcontextprotocol/sdk":"^1.29.0","@slip-stream-kit/config":"^0.3.3",chalk:"^5.6.2",chokidar:"^5.0.0",commander:"^15.0.0",fastify:"5.10.0",ink:"^7.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",portless:"^0.15.2",react:"19.2.7",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@types/aws-lambda":"^8.10.162","@types/react":"19.2.17","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};export{i as a};
2
- //# sourceMappingURL=chunk-Y72C523R.js.map
1
+ var i={name:"infra-kit",type:"module",version:"0.3.6",files:["dist"],description:"infra-kit",bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js"},engines:{node:">=24.x"},scripts:{inspector:"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug",build:"pnpm run clean-artifacts && node ./scripts/build.js",prepack:"pnpm run build",prepublishOnly:"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 --quiet --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:"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.33.1","@inquirer/checkbox":"^5.2.1","@inquirer/confirm":"^6.1.1","@inquirer/password":"^5.0.2","@inquirer/select":"^5.2.1","@modelcontextprotocol/sdk":"^1.29.0","@slip-stream-kit/config":"^0.3.3",chalk:"^5.6.2",chokidar:"^5.0.0",commander:"^15.0.0",fastify:"5.10.0",ink:"^7.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",portless:"^0.15.2",react:"19.2.7",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@types/aws-lambda":"^8.10.162","@types/react":"19.2.17","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};export{i as a};
2
+ //# sourceMappingURL=chunk-T74NOBEP.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.3.4\",\n \"files\": [\n \"dist\"\n ],\n \"description\": \"infra-kit\",\n \"bin\": {\n \"infra-kit\": \"dist/cli.js\",\n \"ik\": \"dist/cli.js\"\n },\n \"engines\": {\n \"node\": \">=24.x\"\n },\n \"scripts\": {\n \"inspector\": \"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug\",\n \"build\": \"pnpm run clean-artifacts && node ./scripts/build.js\",\n \"prepack\": \"pnpm run build\",\n \"prepublishOnly\": \"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 --quiet --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\": \"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.33.1\",\n \"@inquirer/checkbox\": \"^5.2.1\",\n \"@inquirer/confirm\": \"^6.1.1\",\n \"@inquirer/password\": \"^5.0.2\",\n \"@inquirer/select\": \"^5.2.1\",\n \"@modelcontextprotocol/sdk\": \"^1.29.0\",\n \"@slip-stream-kit/config\": \"^0.3.3\",\n \"chalk\": \"^5.6.2\",\n \"chokidar\": \"^5.0.0\",\n \"commander\": \"^15.0.0\",\n \"fastify\": \"5.10.0\",\n \"ink\": \"^7.1.0\",\n \"pino\": \"^10.3.1\",\n \"pino-pretty\": \"^13.1.3\",\n \"portless\": \"^0.15.2\",\n \"react\": \"19.2.7\",\n \"yaml\": \"^2.9.0\",\n \"zod\": \"^4.4.3\",\n \"zx\": \"^8.8.5\"\n },\n \"devDependencies\": {\n \"@types/aws-lambda\": \"^8.10.162\",\n \"@types/react\": \"19.2.17\",\n \"@wl/eslint-config\": \"workspace:*\",\n \"@wl/vitest-config\": \"workspace:*\",\n \"esbuild\": \"^0.28.1\",\n \"ink-testing-library\": \"^4.0.0\",\n \"typescript\": \"^6.0.3\"\n }\n}\n"],
4
+ "sourcesContent": ["{\n \"name\": \"infra-kit\",\n \"type\": \"module\",\n \"version\": \"0.3.6\",\n \"files\": [\n \"dist\"\n ],\n \"description\": \"infra-kit\",\n \"bin\": {\n \"infra-kit\": \"dist/cli.js\",\n \"ik\": \"dist/cli.js\"\n },\n \"engines\": {\n \"node\": \">=24.x\"\n },\n \"scripts\": {\n \"inspector\": \"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug\",\n \"build\": \"pnpm run clean-artifacts && node ./scripts/build.js\",\n \"prepack\": \"pnpm run build\",\n \"prepublishOnly\": \"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 --quiet --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\": \"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.33.1\",\n \"@inquirer/checkbox\": \"^5.2.1\",\n \"@inquirer/confirm\": \"^6.1.1\",\n \"@inquirer/password\": \"^5.0.2\",\n \"@inquirer/select\": \"^5.2.1\",\n \"@modelcontextprotocol/sdk\": \"^1.29.0\",\n \"@slip-stream-kit/config\": \"^0.3.3\",\n \"chalk\": \"^5.6.2\",\n \"chokidar\": \"^5.0.0\",\n \"commander\": \"^15.0.0\",\n \"fastify\": \"5.10.0\",\n \"ink\": \"^7.1.0\",\n \"pino\": \"^10.3.1\",\n \"pino-pretty\": \"^13.1.3\",\n \"portless\": \"^0.15.2\",\n \"react\": \"19.2.7\",\n \"yaml\": \"^2.9.0\",\n \"zod\": \"^4.4.3\",\n \"zx\": \"^8.8.5\"\n },\n \"devDependencies\": {\n \"@types/aws-lambda\": \"^8.10.162\",\n \"@types/react\": \"19.2.17\",\n \"@wl/eslint-config\": \"workspace:*\",\n \"@wl/vitest-config\": \"workspace:*\",\n \"esbuild\": \"^0.28.1\",\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,QACX,MAAS,CACP,MACF,EACA,YAAe,YACf,IAAO,CACL,YAAa,cACb,GAAM,aACR,EACA,QAAW,CACT,KAAQ,QACV,EACA,QAAW,CACT,UAAa,iEACb,MAAS,sDACT,QAAW,iBACX,eAAkB,iBAClB,kBAAmB,4BACnB,kBAAmB,cACnB,cAAe,2EACf,eAAgB,4HAChB,iBAAkB,4HAClB,eAAgB,4EAChB,aAAc,kFACd,WAAY,eACZ,KAAQ,0CACR,aAAc,gDACd,UAAW,6CACX,cAAe,uDACf,GAAM,gHACN,IAAO,6DACT,EACA,aAAgB,CACd,gCAAiC,UACjC,qBAAsB,SACtB,oBAAqB,SACrB,qBAAsB,SACtB,mBAAoB,SACpB,4BAA6B,UAC7B,0BAA2B,SAC3B,MAAS,SACT,SAAY,SACZ,UAAa,UACb,QAAW,SACX,IAAO,SACP,KAAQ,UACR,cAAe,UACf,SAAY,UACZ,MAAS,SACT,KAAQ,SACR,IAAO,SACP,GAAM,QACR,EACA,gBAAmB,CACjB,oBAAqB,YACrB,eAAgB,UAChB,oBAAqB,cACrB,oBAAqB,cACrB,QAAW,UACX,sBAAuB,SACvB,WAAc,QAChB,CACF",
6
6
  "names": ["package_default"]
7
7
  }
package/dist/cli.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{$ as $t,A as te,B as ft,C as U,D as d,E as gt,F as ht,G as vt,H as yt,I as wt,J as St,K as kt,L as Rt,M as Et,N as xt,O as Tt,P as At,Q as Ct,R as bt,S as oe,T as Pt,U as It,V as Nt,W as Lt,X as _t,Y as Dt,Z as Ot,a as D,aa as Ft,b as De,ba as Ut,c as $e,d as Fe,e as Me,f as O,g as He,h as j,i as Ye,j as ze,k as Xe,l as Qe,m as Ze,n as tt,o as ot,p as rt,q as Z,r as nt,s as it,t as ee,u as ct,v as lt,w as mt,x as dt,y as ut,z as pt}from"./chunk-LM7IE2UD.js";import{r as re}from"./chunk-S45AAYXO.js";import{a as Mt,b as G,c as jt,d as C,e as ne,f as ie,g as se}from"./chunk-UO3FYLPX.js";import{a as et}from"./chunk-Y72C523R.js";import{a as st,b as at}from"./chunk-A7FAXZGI.js";import{b as Oe,c as T,d as h,e as F,f as We,g as Ke,h as Be,i as A,l as M}from"./chunk-GZNE5CBQ.js";import{O as X,P as Le,R as _e,m as Ne,u as l}from"./chunk-IVWPZEMC.js";import{a as $,b as je,d as Ue,f as Ge,g as qe,j as Q,k as Ve,n as v,q as Je}from"./chunk-CHETBZ6M.js";import en,{Separator as Eo}from"@inquirer/select";import{realpathSync as tn}from"node:fs";import g from"node:process";import{fileURLToPath as To}from"node:url";var Co=(e,t)=>{let o=e,r;for(let s of t){if(r=o.find(n=>n.name()===s),!r)return;o=r.commands}return r},Gt=e=>Dt.flatMap(({key:t,label:o})=>$t(t).flatMap(r=>{let s=Co(e,r.groupPath);return s?[{name:r.groupPath.join(" "),description:s.description(),group:o}]:[]}));import{Command as lr}from"commander";import _ from"node:process";import qt from"node:process";import{$ as bo}from"zx";var ae=async()=>{let e=await X(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await T(i.path)}))),o=t.at(-1)?.exists===!0,r=await ct(e.userProject,o),s=o?lt(r):"";l.info(`Project name: ${e.projectName}
2
+ import{$ as $t,A as te,B as ft,C as U,D as d,E as gt,F as ht,G as vt,H as yt,I as wt,J as St,K as kt,L as Rt,M as Et,N as xt,O as Tt,P as At,Q as Ct,R as bt,S as oe,T as Pt,U as It,V as Nt,W as Lt,X as _t,Y as Dt,Z as Ot,a as D,aa as Ft,b as De,ba as Ut,c as $e,d as Fe,e as Me,f as O,g as He,h as j,i as Ye,j as ze,k as Xe,l as Qe,m as Ze,n as tt,o as ot,p as rt,q as Z,r as nt,s as it,t as ee,u as ct,v as lt,w as mt,x as dt,y as ut,z as pt}from"./chunk-3G6O7MCC.js";import{r as re}from"./chunk-S45AAYXO.js";import{a as Mt,b as G,c as jt,d as C,e as ne,f as ie,g as se}from"./chunk-EX66ZFV5.js";import{a as et}from"./chunk-T74NOBEP.js";import{a as st,b as at}from"./chunk-A7FAXZGI.js";import{b as Oe,c as T,d as h,e as F,f as We,g as Ke,h as Be,i as A,l as M}from"./chunk-GZNE5CBQ.js";import{O as X,P as Le,R as _e,m as Ne,u as l}from"./chunk-IVWPZEMC.js";import{a as $,b as je,d as Ue,f as Ge,g as Ve,j as Q,k as qe,n as v,q as Je}from"./chunk-CHETBZ6M.js";import en,{Separator as Eo}from"@inquirer/select";import{realpathSync as tn}from"node:fs";import g from"node:process";import{fileURLToPath as To}from"node:url";var Co=(e,t)=>{let o=e,r;for(let s of t){if(r=o.find(n=>n.name()===s),!r)return;o=r.commands}return r},Gt=e=>Dt.flatMap(({key:t,label:o})=>$t(t).flatMap(r=>{let s=Co(e,r.groupPath);return s?[{name:r.groupPath.join(" "),description:s.description(),group:o}]:[]}));import{Command as lr}from"commander";import _ from"node:process";import Vt from"node:process";import{$ as bo}from"zx";var ae=async()=>{let e=await X(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await T(i.path)}))),o=t.at(-1)?.exists===!0,r=await ct(e.userProject,o),s=o?lt(r):"";l.info(`Project name: ${e.projectName}
3
3
  `),l.info(`Config merge chain (later overrides earlier):
4
- `);for(let i of t){let c=i.exists?" [\u2713]":" [ ]",a=i.path===e.userProject&&s!==""?` ${s}`:"";l.info(`${c} ${i.label.padEnd(22)} ${h(i.path)}${a}`)}let n={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},ce=async()=>{let e=await X(),t=qt.env.EDITOR||qt.env.VISUAL||"vi",o=await tt(e);o.createdConfig&&l.info(ot(o)),l.info(`Opening ${h(e.userProject)} in ${t}`),await bo({stdio:"inherit"})`${t} ${e.userProject}`,_e();let r={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}};var le=e=>{if(typeof e!="object"||e===null)return null;let{config:t,reason:o,at:r}=e;return typeof t!="string"||t.length===0||typeof o!="string"||typeof r!="number"||!Number.isFinite(r)?null:{config:t,reason:o,at:r}},I=e=>`infra-kit: Doppler token for env "${e}" is missing, invalid, or unreadable \u2014 env auto-load is not running. Fix: run \`infra-kit env-token-set ${e}\` (mint one at https://dashboard.doppler.com under this config's Access tab).`;import p from"node:fs";import y from"node:path";import N from"node:process";var Po="autoload-warn-fail.flag",me="autoload-warn-auth-fail.flag",de="autoload-fail.flag",ue="autoload-auth-fail.json",Io=3e4,Jt=async(e=!0)=>{let t;try{t=await Le()}catch{return null}let o=t.envAutoLoad;if(!o)return null;let r={trigger:o.trigger,config:o.config,project:t.envManagement.config.name};try{if(await He(o.config))return r}catch{return r}return Kt({config:o.config,reason:`No Doppler service token for env "${o.config}"`,at:Date.now()}),e&&q(I(o.config),me),null},Wt=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:s,env:n,force:i}=e;return t!==o||!n.session||n.cleared||n.currentConfig&&!n.autoLoadedMarker||!i&&n.autoLoadedMarker&&n.currentConfig===r&&n.currentProject===s?"skip":"load"},L=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=Oe})=>{let s=e==="cli-invocation";s&&V();let n=null;try{if(n=await Jt(s),!n||Wt({trigger:n.trigger,expectedTrigger:e,targetConfig:n.config,targetProject:n.project,env:_o(),force:o})==="skip"||Vt()||$o())return null;let c=Do(),a=await Ye({config:n.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!Vt()&&!Oo(c)});return a?(Mo(),Lo(),a.filePath):null}catch(i){let c=i.message,a=r(i);return Fo(),a&&n&&Kt({config:n.config,reason:c,at:Date.now()}),s&&a&&n?(q(I(n.config),me),l.debug(`env auto-load auth failure: ${c}`)):s?q(`infra-kit: env auto-load failed \u2014 ${c} (will retry later)`,Po):l.debug(`env auto-load skipped: ${c}`),null}},V=()=>{let e=No();e&&(q(I(e.config),me),l.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},No=()=>{try{let e=p.readFileSync(y.join(v(),ue),"utf-8");return le(JSON.parse(e))}catch{return null}},Kt=e=>{try{let t=v();p.mkdirSync(t,{recursive:!0,mode:448}),Je(y.join(t,ue),JSON.stringify(e),384)}catch{}},Lo=()=>{try{p.rmSync(y.join(v(),ue),{force:!0})}catch{}},_o=()=>({session:N.env[Ue],cleared:N.env[Ve],currentConfig:N.env[Ge],currentProject:N.env[qe],autoLoadedMarker:N.env[Q]}),Do=()=>{try{return p.statSync(y.join(v(),$)).mtimeMs}catch{return null}},Oo=e=>{try{let t=y.join(v(),$);if(!p.existsSync(t))return!1;let o=p.statSync(t).mtimeMs;return e!==null&&o<=e?!1:new RegExp(`^unset ${Q}$`,"m").test(p.readFileSync(t,"utf-8"))}catch{return!1}},Vt=()=>{try{let e=v(),t=y.join(e,je);if(!p.existsSync(t))return!1;let o=y.join(e,$);return p.existsSync(o)?p.statSync(t).mtimeMs>=p.statSync(o).mtimeMs:!0}catch{return!1}},$o=()=>{try{let e=y.join(v(),de);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<Io:!1}catch{return!1}},Fo=()=>{try{let e=v();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(y.join(e,de),"",{mode:384})}catch{}},Mo=()=>{try{p.rmSync(y.join(v(),de),{force:!0})}catch{}},q=(e,t)=>{try{let o=v(),r=y.join(o,t);if(p.existsSync(r))return;p.mkdirSync(o,{recursive:!0,mode:448}),p.writeFileSync(r,"",{mode:384})}catch{}l.warn(e)};var pe=async({projectDir:e}={})=>{await L({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var Bt="https://dashboard.doppler.com/workplace/projects",jo=(e,t)=>["Removing it locally does NOT revoke it \u2014 the token still works anywhere else it is stored.",`Revoke it in Doppler (project "${e}", config "${t}"): ${Bt}/${e}`],fe=async({env:e})=>{let o=!!(await We())?.envs[e];await Be(e);let r=await j(),s=await O(),n=await F();o?l.info(`Removed the "${e}" service token from ${h(n)}.`):l.info(`No "${e}" service token was stored in ${h(n)} \u2014 nothing to remove.`),r.length>0&&l.info(`Purged ${r.length} warm cache(s) across this repo's worktrees.`);for(let c of jo(s,e))l.warn(c);let i={env:e,removed:o,storePath:n,warmCachesPurged:r.length,revokeUrl:`${Bt}/${s}`};return{content:D(JSON.stringify(i,null,2)),structuredContent:i}};import Uo from"@inquirer/password";import W from"node:process";import{$ as J}from"zx";var Go=async({stdin:e,fromEnv:t})=>{if(e)return{token:await qo(),source:"stdin"};if(t){let r=W.env[t];if(!r)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:r,source:"env"}}return A.setInteractive(),{token:(await M(r=>Uo({message:"Paste the Doppler service token (input is hidden)",mask:!0},r),{output:W.stderr})).trim(),source:"prompt"}},qo=async()=>{let e=[];W.stdin.setEncoding("utf8");for await(let t of W.stdin)e.push(t);return e.join("").trim()},ge="DOPPLER_CONFIG",Vo=3e4,Jo=async(e,t,o)=>{let r=J.quiet;J.quiet=!0;let s;try{s=(await J({env:Xe(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(Vo)).stdout}catch(n){throw Wo(n,o)}finally{J.quiet=r}return Ze(s)},Wo=(e,t)=>{let o=Me(e)??(e instanceof Error?e.message:String(e));if($e(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=Fe(o)==="mis-scoped"?"it is scoped to a DIFFERENT config (pasting another environment's token here is the mistake this check exists to catch).":"it is invalid or has been revoked.";return new Error([`Doppler refused this token for config "${t}" \u2014 ${r}`,"Nothing was written. Issue a service token scoped to that config and try again."].join(`
4
+ `);for(let i of t){let c=i.exists?" [\u2713]":" [ ]",a=i.path===e.userProject&&s!==""?` ${s}`:"";l.info(`${c} ${i.label.padEnd(22)} ${h(i.path)}${a}`)}let n={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:r.hasOverrides,overrideKeys:r.overrideKeys};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}},ce=async()=>{let e=await X(),t=Vt.env.EDITOR||Vt.env.VISUAL||"vi",o=await tt(e);o.createdConfig&&l.info(ot(o)),l.info(`Opening ${h(e.userProject)} in ${t}`),await bo({stdio:"inherit"})`${t} ${e.userProject}`,_e();let r={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(r,null,2)}],structuredContent:r}};var le=e=>{if(typeof e!="object"||e===null)return null;let{config:t,reason:o,at:r}=e;return typeof t!="string"||t.length===0||typeof o!="string"||typeof r!="number"||!Number.isFinite(r)?null:{config:t,reason:o,at:r}},I=e=>`infra-kit: Doppler token for env "${e}" is missing, invalid, or unreadable \u2014 env auto-load is not running. Fix: run \`infra-kit env-token-set ${e}\` (mint one at https://dashboard.doppler.com under this config's Access tab).`;import p from"node:fs";import y from"node:path";import N from"node:process";var Po="autoload-warn-fail.flag",me="autoload-warn-auth-fail.flag",de="autoload-fail.flag",ue="autoload-auth-fail.json",Io=3e4,Jt=async(e=!0)=>{let t;try{t=await Le()}catch{return null}let o=t.envAutoLoad;if(!o)return null;let r={trigger:o.trigger,config:o.config,project:t.envManagement.config.name};try{if(await He(o.config))return r}catch{return r}return Kt({config:o.config,reason:`No Doppler service token for env "${o.config}"`,at:Date.now()}),e&&V(I(o.config),me),null},Wt=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:s,env:n,force:i}=e;return t!==o||!n.session||n.cleared||n.currentConfig&&!n.autoLoadedMarker||!i&&n.autoLoadedMarker&&n.currentConfig===r&&n.currentProject===s?"skip":"load"},L=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=Oe})=>{let s=e==="cli-invocation";s&&q();let n=null;try{if(n=await Jt(s),!n||Wt({trigger:n.trigger,expectedTrigger:e,targetConfig:n.config,targetProject:n.project,env:_o(),force:o})==="skip"||qt()||$o())return null;let c=Do(),a=await Ye({config:n.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!qt()&&!Oo(c)});return a?(Mo(),Lo(),a.filePath):null}catch(i){let c=i.message,a=r(i);return Fo(),a&&n&&Kt({config:n.config,reason:c,at:Date.now()}),s&&a&&n?(V(I(n.config),me),l.debug(`env auto-load auth failure: ${c}`)):s?V(`infra-kit: env auto-load failed \u2014 ${c} (will retry later)`,Po):l.debug(`env auto-load skipped: ${c}`),null}},q=()=>{let e=No();e&&(V(I(e.config),me),l.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},No=()=>{try{let e=p.readFileSync(y.join(v(),ue),"utf-8");return le(JSON.parse(e))}catch{return null}},Kt=e=>{try{let t=v();p.mkdirSync(t,{recursive:!0,mode:448}),Je(y.join(t,ue),JSON.stringify(e),384)}catch{}},Lo=()=>{try{p.rmSync(y.join(v(),ue),{force:!0})}catch{}},_o=()=>({session:N.env[Ue],cleared:N.env[qe],currentConfig:N.env[Ge],currentProject:N.env[Ve],autoLoadedMarker:N.env[Q]}),Do=()=>{try{return p.statSync(y.join(v(),$)).mtimeMs}catch{return null}},Oo=e=>{try{let t=y.join(v(),$);if(!p.existsSync(t))return!1;let o=p.statSync(t).mtimeMs;return e!==null&&o<=e?!1:new RegExp(`^unset ${Q}$`,"m").test(p.readFileSync(t,"utf-8"))}catch{return!1}},qt=()=>{try{let e=v(),t=y.join(e,je);if(!p.existsSync(t))return!1;let o=y.join(e,$);return p.existsSync(o)?p.statSync(t).mtimeMs>=p.statSync(o).mtimeMs:!0}catch{return!1}},$o=()=>{try{let e=y.join(v(),de);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<Io:!1}catch{return!1}},Fo=()=>{try{let e=v();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(y.join(e,de),"",{mode:384})}catch{}},Mo=()=>{try{p.rmSync(y.join(v(),de),{force:!0})}catch{}},V=(e,t)=>{try{let o=v(),r=y.join(o,t);if(p.existsSync(r))return;p.mkdirSync(o,{recursive:!0,mode:448}),p.writeFileSync(r,"",{mode:384})}catch{}l.warn(e)};var pe=async({projectDir:e}={})=>{await L({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var Bt="https://dashboard.doppler.com/workplace/projects",jo=(e,t)=>["Removing it locally does NOT revoke it \u2014 the token still works anywhere else it is stored.",`Revoke it in Doppler (project "${e}", config "${t}"): ${Bt}/${e}`],fe=async({env:e})=>{let o=!!(await We())?.envs[e];await Be(e);let r=await j(),s=await O(),n=await F();o?l.info(`Removed the "${e}" service token from ${h(n)}.`):l.info(`No "${e}" service token was stored in ${h(n)} \u2014 nothing to remove.`),r.length>0&&l.info(`Purged ${r.length} warm cache(s) across this repo's worktrees.`);for(let c of jo(s,e))l.warn(c);let i={env:e,removed:o,storePath:n,warmCachesPurged:r.length,revokeUrl:`${Bt}/${s}`};return{content:D(JSON.stringify(i,null,2)),structuredContent:i}};import Uo from"@inquirer/password";import W from"node:process";import{$ as J}from"zx";var Go=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Vo(),source:"stdin"};if(t){let r=W.env[t];if(!r)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:r,source:"env"}}return A.setInteractive(),{token:(await M(r=>Uo({message:"Paste the Doppler service token (input is hidden)",mask:!0},r),{output:W.stderr})).trim(),source:"prompt"}},Vo=async()=>{let e=[];W.stdin.setEncoding("utf8");for await(let t of W.stdin)e.push(t);return e.join("").trim()},ge="DOPPLER_CONFIG",qo=3e4,Jo=async(e,t,o)=>{let r=J.quiet;J.quiet=!0;let s;try{s=(await J({env:Xe(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(qo)).stdout}catch(n){throw Wo(n,o)}finally{J.quiet=r}return Ze(s)},Wo=(e,t)=>{let o=Me(e)??(e instanceof Error?e.message:String(e));if($e(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=Fe(o)==="mis-scoped"?"it is scoped to a DIFFERENT config (pasting another environment's token here is the mistake this check exists to catch).":"it is invalid or has been revoked.";return new Error([`Doppler refused this token for config "${t}" \u2014 ${r}`,"Nothing was written. Issue a service token scoped to that config and try again."].join(`
5
5
  `))},Ko=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${ge}.`,"Refusing to store a credential whose scope is unknown (a token for the wrong environment would load","the wrong secrets into every shell).","Re-run with --force if you are certain the token is scoped to this config."].join(`
6
6
  `),he=async({env:e,stdin:t,fromEnv:o,force:r})=>{let s=await O(),{token:n,source:i}=await Go({stdin:t,fromEnv:o});if(!n)throw new Error("No token provided \u2014 nothing was written.");let c=await Jo(n,s,e);Qe(c,e);let a=c.some(([k])=>k===ge);if(!a&&!r)throw new Error(Ko(e));await Ke(e,n);let m=await j(),u=await F();l.info(`Stored the "${e}" service token (${te(n)}) in ${h(u)} (mode 0600).`),a||l.warn(`Scope was NOT verified (no ${ge} in the payload) \u2014 written because --force was given.`),m.length>0&&l.info(`Purged ${m.length} warm cache(s) so the next shell cannot serve secrets fetched with an old token.`);let f={env:e,source:i,redactedToken:te(n),storePath:u,scopeVerified:a,warmCachesPurged:m.length};return A.print(),{content:D(JSON.stringify(f,null,2)),structuredContent:f}};import{spawn as Bo}from"node:child_process";import K from"node:process";import{fileURLToPath as Ho}from"node:url";var Yo=["SIGINT","SIGTERM"],Ht=()=>Ho(new URL("./mcp.js",import.meta.url)),ve=(e={})=>{let t=e.spawn??Bo,o=e.exit??(i=>K.exit(i)),r=e.env??K.env,s=e.onError??(i=>l.error(i)),n=t(K.execPath,[Ht()],{stdio:"inherit",env:st(r)});n.on("error",i=>{s(`failed to launch the MCP server: ${i.message}`),o(1)}),Yo.forEach(i=>{K.on(i,()=>{n.kill(i)})}),n.on("exit",(i,c)=>{o(c?1:i??1)})};import{spawnSync as zo}from"node:child_process";import{realpathSync as Xo}from"node:fs";import{homedir as Qo}from"node:os";import ye from"node:process";import{fileURLToPath as Zo}from"node:url";var er=()=>Xo(Zo(import.meta.url)),tr=(e,t,o,r)=>e.error?(o(`${t} not found on PATH: ${e.error.message}`),r(1)):e.signal?(o(`update terminated by signal ${e.signal}`),r(1)):r(e.status??1),we=({dryRun:e},t={})=>{let o=t.spawnSync??zo,r=t.print??(R=>l.info(R)),s=t.exit??(R=>ye.exit(R)),n=t.env??ye.env,i=t.selfRealPath??er(),c=t.lazyNpmRoot??jt,{manager:a,updateCommand:m,canSelfSpawn:u}=Mt({selfRealPath:i,env:n,realpath:C,lazyNpmRoot:c}),f=m.join(" ");if(e){r(`Detected install manager: ${a}`),r(`Would run: ${f}`);return}if(!u){r(`Detected install manager: ${a}`),r(`Run this yourself: ${f}`),r(a==="homebrew"?"Not run for you: Homebrew manages this install; running a package manager would create a split-brain install.":"Not run for you: the install location is unrecognized, so the command above is a guess \u2014 a guessed global install is worse than a printed one.");return}let k=o(m[0],m.slice(1),{stdio:"inherit",shell:ye.platform==="win32",cwd:Qo(),env:at(n)});tr(k,a,r,s)};import{VENDOR_CONFIG_FILE as zt}from"@slip-stream-kit/config/internal";import Se from"node:fs/promises";import ke from"node:path";import Yt from"node:process";import{pathToFileURL as or}from"node:url";var Xt="~/projects",Re=async(e={})=>{if(e.init){await nr(e.cwd);return}await rr()},rr=async()=>{let e=Z(),t=await T(e);if(l.info(`Factory config: ${h(e)} ${t?"[\u2713]":"[ ]"}`),!t){l.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Yt.exitCode=1;return}let{workspaceDir:o,targets:r}=await it(),s=nt(o),n=await T(s);l.info(`workspaceDir: ${o} (resolved: ${s}) ${n?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let i=n;for(let c of r){let a=ke.join(s,c),m=await T(a);m||(i=!1);let u=m?"[\u2713]":"[ ]",f=m?"":" (not found \u2014 clone or remove)";l.info(` ${u} ${c} ${h(a)}${f}`)}i||(Yt.exitCode=1)},nr=async e=>{let t=Z();if(await T(t)){l.info(`Factory config already exists at ${h(t)} \u2014 leaving it untouched.`);return}let o=e??await Ne(),r=await ir(o);await Se.mkdir(ke.dirname(t),{recursive:!0}),await Se.writeFile(t,sr(r),"utf-8"),l.info(`\u2713 Created ${h(t)}`),r.length>0&&l.info(` Seeded ${r.length} target(s) from the source ${zt}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${Xt}) to point at where your repos live.`),r.length===0&&l.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},ir=async e=>{try{let t=ke.join(e,zt),o=await Se.stat(t),n=(await import(`${or(t).href}?mtime=${Number(o.mtimeMs)}`)).default,i=typeof n=="function"?await n():n;if(i&&typeof i=="object"&&"targets"in i){let c=i.targets;if(Array.isArray(c)&&c.every(a=>typeof a=="string"))return c}}catch{}return[]},sr=e=>`${JSON.stringify({workspaceDir:Xt,targets:e},null,2)}
7
- `;var B=(e,t=!0)=>({line:e,reproducible:t});import H from"node:fs";import ar from"node:os";import cr from"node:path";import to from"node:process";var Y="INFRA_KIT_SESSION_REPORT",Ee=null,Qt=!1,Zt=[],oo=(e=to.env)=>{Qt||(Ee=e[Y]??null,Qt=!0,delete e[Y])};var ro=(e,t)=>{if(!Ee)return;let o=e.summary??(Zt.length>0?[...Zt]:void 0),r={...e,...o?{summary:o}:{}},s=t?.write??((n,i)=>{H.writeFileSync(n,i)});try{s(Ee,JSON.stringify(r))}catch{}},eo=0,no=e=>{let t=e?.tmpdir?.()??ar.tmpdir(),o=e?.pid??to.pid;return eo+=1,cr.join(t,`infra-kit-session-${o}-${eo}.json`)},io=(e,t)=>{if(!(t?.exists??(i=>H.existsSync(i)))(e))return null;let r=t?.read??(i=>H.readFileSync(i,"utf-8")),s=t?.unlink??(i=>H.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{s(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var mr=(e,t)=>[...t,e],xe=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,so=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&oe.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${oe.join(", ")}.`)}},dr=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await ht({all:t.all,confirmedCommand:t.yes}))}),ur=e=>e.description("List all release branches").action(async()=>{d(await St())}),pr=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',mr,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(kt),s=r.length>0?r:void 0;d(await Rt({releases:s,confirmedCommand:t.yes}))}),fr=e=>e.description("Edit a release's description in Jira and in the matching GitHub PR body").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await Et({version:t.version,description:t.description,confirmedCommand:t.yes}))}),gr=e=>e.description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await yt({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),hr=e=>e.description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await wt({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),vr=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await vt({version:t.version,confirmedCommand:t.yes}))}),yr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await _t({confirmedCommand:t.yes}))}),wr=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async t=>{let o=so(t.ide,"--ide")??so(t.cursor,"--cursor");d(await Pt({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),Sr=e=>e.description("List all git worktrees with detailed information").action(async()=>{d(await It())}),kr=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{d(await Lt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Rr=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{d(await Nt())}),Er=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{d(await Re({init:t.init}))}),xr=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await xt();d(t),t.structuredContent.ok||(_.exitCode=1)}),Tr=e=>e.description("Source-aware drift check (rsync dry-run) of each target vendored subtree vs the source").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async t=>{let o=await Tt({repos:xe(t.repos)});d(o),o.structuredContent.ok||(_.exitCode=1)}),Ar=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{d(await ae())}),Cr=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{d(await ce())}),br=new Set(["init","doctor","version","dev","self-update","mcp"]),Pr=e=>e.startsWith("env-")||br.has(e),Ir=new Set(["env-autoload","mcp","version","self-update"]),z=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},Te=()=>{let e=new lr,t=e.command("release").description("Release management commands");dr(t.command("merge-dev")),ur(t.command("list")),pr(t.command("create")),fr(t.command("desc-edit")),gr(t.command("deploy-all")),hr(t.command("deploy-selected")),vr(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");wr(o.command("add")),Sr(o.command("list")),kr(o.command("remove")),yr(o.command("sync")),Rr(o.command("reload"));let r=e.command("config").description("Manage infra-kit configuration files");Ar(r.command("path")),Cr(r.command("edit")),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").action(async n=>{let i=await De({all:n.all,root:n.root});d(i),i.structuredContent.allPassed||(_.exitCode=1)});let s=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return xr(s.command("check")),s.command("sync").description("Copy vendored files from the source repo into each target and regenerate manifests").option("-y, --yes","Skip confirmation prompt").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await Ct({confirmedCommand:n.yes,repos:xe(n.repos)}))}),s.command("manifest").description("Regenerate each target vendor/.sync-manifest.json + README from current content (no copy)").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await At({confirmedCommand:!0,repos:xe(n.repos)}))}),Tr(s.command("diff")),Er(s.command("config")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").action(async n=>{d(await mt({fix:!!n.fix}))}),e.command("self-update").description("Update this CLI using the package manager that installed it").option("--dry-run","Print the detected manager and the command that would run; install nothing").action(n=>{we({dryRun:!!n.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{ve()}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--cmux","Run each app in its own cmux pane (one workspace, N panes; falls back to single terminal if cmux is unavailable)").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)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(n,i)=>{let{runDevServerCli:c}=await import("./dev-server.js"),a=!!(_.stdout.isTTY&&_.stdin.isTTY);await c({...i,preset:n},a,U.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{d(await bt())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{d(await pt())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{d(await ut())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{d(await ee())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async n=>{d(await ze({config:n.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").option("--purge","Also delete this project's warm cache outright (durable disable)").action(async n=>{d(await dt({purge:!!n.purge}))}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(n,i)=>{d(await he({env:n,stdin:i.stdin,fromEnv:i.fromEnv,force:i.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async n=>{d(await ft({check:!!n.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async n=>{d(await fe({env:n}))}),e.command("env-autoload",{hidden:!0}).description("Internal: prime env for the shell-startup auto-load trigger").option("--project-dir <dir>","Canonical project dir for the warm-cache key (shell-startup only)").action(async n=>{await pe({projectDir:n.projectDir})}),e.commands.forEach(gt),e.hook("preAction",async(n,i)=>{A.start(z(i)),U.enabled=!!i.optsWithGlobals().json,U.enabled&&(l.level="warn"),Ir.has(z(i))||await rt(),V(),Pr(i.name())||await L({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let c=z(i);if(Ft(c))return;let m=A.snapshot()?.formattedOptions??"",u=m?` ${m}`:"",f=`infra-kit ${c}${u}`;ro({equivalent:B(f,!0)})}),e};var Ae=(e,t=" ")=>{let o=e.reduce((r,[s])=>Math.max(r,s.length),0);return e.map(([r,s])=>`${r.padEnd(o)}${t}${s}`)};import{chalkStderr as jr}from"chalk";import{spawn as Ur}from"node:child_process";import S from"node:process";import{Chalk as Nr}from"chalk";var b=new Nr({level:1}),w={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},ao={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},co={unicode:"\u2500",ascii:"-"},Lr=3,Ce=e=>e,_r={ok:e=>b.green(e),findings:e=>b.yellow(e),failed:e=>b.red(e),cancelled:e=>b.gray(e)},mo=e=>e?{dim:t=>b.dim(t),bold:t=>b.bold(t)}:{dim:Ce,bold:Ce},Dr=(e,t)=>e?_r[t]:Ce,lo=e=>[...e].length,uo=(e,t={})=>{let o=mo(t.color===!0);return`${o.dim(w.reproPrefix.trim())} ${o.bold(e)}`},Or=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,$r=(e,t)=>e==="findings"?t!=null?`${t} ${w.findingsSuffix}`:w.findingsPlain:{ok:w.ok,failed:w.failed,cancelled:w.cancelled}[e],Fr=(e,t,o,r)=>{if(t==null)return"";let s=t-2-e;return s<Lr?"":` ${r(o.repeat(s))}`},po=e=>{let t=e.color===!0,o=mo(t),r=Dr(t,e.outcome),s=e.ascii===!0,n=e.equivalent.reproducible?w.reproPrefix:w.nonReproPrefix,i=s?ao[e.outcome].ascii:ao[e.outcome].unicode,c=$r(e.outcome,e.findingsCount),a=[Or(e.durationMs)],m=e.summary?.[0]?.split(`
7
+ `;var B=(e,t=!0)=>({line:e,reproducible:t});import H from"node:fs";import ar from"node:os";import cr from"node:path";import to from"node:process";var Y="INFRA_KIT_SESSION_REPORT",Ee=null,Qt=!1,Zt=[],oo=(e=to.env)=>{Qt||(Ee=e[Y]??null,Qt=!0,delete e[Y])};var ro=(e,t)=>{if(!Ee)return;let o=e.summary??(Zt.length>0?[...Zt]:void 0),r={...e,...o?{summary:o}:{}},s=t?.write??((n,i)=>{H.writeFileSync(n,i)});try{s(Ee,JSON.stringify(r))}catch{}},eo=0,no=e=>{let t=e?.tmpdir?.()??ar.tmpdir(),o=e?.pid??to.pid;return eo+=1,cr.join(t,`infra-kit-session-${o}-${eo}.json`)},io=(e,t)=>{if(!(t?.exists??(i=>H.existsSync(i)))(e))return null;let r=t?.read??(i=>H.readFileSync(i,"utf-8")),s=t?.unlink??(i=>H.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{s(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var mr=(e,t)=>[...t,e],xe=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,so=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&oe.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${oe.join(", ")}.`)}},dr=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await ht({all:t.all,confirmedCommand:t.yes}))}),ur=e=>e.description("List all release branches").action(async()=>{d(await St())}),pr=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',mr,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(kt),s=r.length>0?r:void 0;d(await Rt({releases:s,confirmedCommand:t.yes}))}),fr=e=>e.description("Edit a release's description in Jira and in the matching GitHub PR body").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await Et({version:t.version,description:t.description,confirmedCommand:t.yes}))}),gr=e=>e.description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await yt({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),hr=e=>e.description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await wt({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),vr=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await vt({version:t.version,confirmedCommand:t.yes}))}),yr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{d(await _t({confirmedCommand:t.yes}))}),wr=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async t=>{let o=so(t.ide,"--ide")??so(t.cursor,"--cursor");d(await Pt({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),Sr=e=>e.description("List all git worktrees with detailed information").action(async()=>{d(await It())}),kr=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{d(await Lt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Rr=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{d(await Nt())}),Er=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{d(await Re({init:t.init}))}),xr=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await xt();d(t),t.structuredContent.ok||(_.exitCode=1)}),Tr=e=>e.description("Source-aware drift check (rsync dry-run) of each target vendored subtree vs the source").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async t=>{let o=await Tt({repos:xe(t.repos)});d(o),o.structuredContent.ok||(_.exitCode=1)}),Ar=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{d(await ae())}),Cr=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{d(await ce())}),br=new Set(["init","doctor","version","dev","self-update","mcp"]),Pr=e=>e.startsWith("env-")||br.has(e),Ir=new Set(["env-autoload","mcp","version","self-update"]),z=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},Te=()=>{let e=new lr,t=e.command("release").description("Release management commands");dr(t.command("merge-dev")),ur(t.command("list")),pr(t.command("create")),fr(t.command("desc-edit")),gr(t.command("deploy-all")),hr(t.command("deploy-selected")),vr(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");wr(o.command("add")),Sr(o.command("list")),kr(o.command("remove")),yr(o.command("sync")),Rr(o.command("reload"));let r=e.command("config").description("Manage infra-kit configuration files");Ar(r.command("path")),Cr(r.command("edit")),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").action(async n=>{let i=await De({all:n.all,root:n.root});d(i),i.structuredContent.allPassed||(_.exitCode=1)});let s=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return xr(s.command("check")),s.command("sync").description("Copy vendored files from the source repo into each target and regenerate manifests").option("-y, --yes","Skip confirmation prompt").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await Ct({confirmedCommand:n.yes,repos:xe(n.repos)}))}),s.command("manifest").description("Regenerate each target vendor/.sync-manifest.json + README from current content (no copy)").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async n=>{d(await At({confirmedCommand:!0,repos:xe(n.repos)}))}),Tr(s.command("diff")),Er(s.command("config")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").action(async n=>{d(await mt({fix:!!n.fix}))}),e.command("self-update").description("Update this CLI using the package manager that installed it").option("--dry-run","Print the detected manager and the command that would run; install nothing").action(n=>{we({dryRun:!!n.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{ve()}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--cmux","Run each app in its own cmux pane (one workspace, N panes; falls back to single terminal if cmux is unavailable)").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)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(n,i)=>{let{runDevServerCli:c}=await import("./dev-server.js"),a=!!(_.stdout.isTTY&&_.stdin.isTTY);await c({...i,preset:n},a,U.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{d(await bt())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{d(await pt())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{d(await ut())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{d(await ee())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async n=>{d(await ze({config:n.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").option("--purge","Also delete this project's warm cache outright (durable disable)").action(async n=>{d(await dt({purge:!!n.purge}))}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(n,i)=>{d(await he({env:n,stdin:i.stdin,fromEnv:i.fromEnv,force:i.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async n=>{d(await ft({check:!!n.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async n=>{d(await fe({env:n}))}),e.command("env-autoload",{hidden:!0}).description("Internal: prime env for the shell-startup auto-load trigger").option("--project-dir <dir>","Canonical project dir for the warm-cache key (shell-startup only)").action(async n=>{await pe({projectDir:n.projectDir})}),e.commands.forEach(gt),e.hook("preAction",async(n,i)=>{A.start(z(i)),U.enabled=!!i.optsWithGlobals().json,U.enabled&&(l.level="warn"),Ir.has(z(i))||await rt(),q(),Pr(i.name())||await L({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let c=z(i);if(Ft(c))return;let m=A.snapshot()?.formattedOptions??"",u=m?` ${m}`:"",f=`infra-kit ${c}${u}`;ro({equivalent:B(f,!0)})}),e};var Ae=(e,t=" ")=>{let o=e.reduce((r,[s])=>Math.max(r,s.length),0);return e.map(([r,s])=>`${r.padEnd(o)}${t}${s}`)};import{chalkStderr as jr}from"chalk";import{spawn as Ur}from"node:child_process";import S from"node:process";import{Chalk as Nr}from"chalk";var b=new Nr({level:1}),w={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},ao={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},co={unicode:"\u2500",ascii:"-"},Lr=3,Ce=e=>e,_r={ok:e=>b.green(e),findings:e=>b.yellow(e),failed:e=>b.red(e),cancelled:e=>b.gray(e)},mo=e=>e?{dim:t=>b.dim(t),bold:t=>b.bold(t)}:{dim:Ce,bold:Ce},Dr=(e,t)=>e?_r[t]:Ce,lo=e=>[...e].length,uo=(e,t={})=>{let o=mo(t.color===!0);return`${o.dim(w.reproPrefix.trim())} ${o.bold(e)}`},Or=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,$r=(e,t)=>e==="findings"?t!=null?`${t} ${w.findingsSuffix}`:w.findingsPlain:{ok:w.ok,failed:w.failed,cancelled:w.cancelled}[e],Fr=(e,t,o,r)=>{if(t==null)return"";let s=t-2-e;return s<Lr?"":` ${r(o.repeat(s))}`},po=e=>{let t=e.color===!0,o=mo(t),r=Dr(t,e.outcome),s=e.ascii===!0,n=e.equivalent.reproducible?w.reproPrefix:w.nonReproPrefix,i=s?ao[e.outcome].ascii:ao[e.outcome].unicode,c=$r(e.outcome,e.findingsCount),a=[Or(e.durationMs)],m=e.summary?.[0]?.split(`
8
8
  `)[0];m!=null&&m.length>0&&a.push(m);let u=`${i} ${c}`,f=`${w.sep}${a.join(w.sep)}`,k=lo(u)+lo(f),R=Fr(k,e.width,s?co.ascii:co.unicode,o.dim),x=[`${r(u)}${o.dim(f)}${R}`];return e.showEquivalent!==!1&&x.unshift(`${o.dim(n.trim())} ${o.bold(e.equivalent.line)}`),e.envNotice===!0&&x.push(o.dim(w.envNotice)),x.join(`
9
- `)};var Mr=new Set([130,143]),fo=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Mr.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import go from"node:process";var E={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},ho=(e,t)=>{let o=t?.write??(n=>{go.stderr.write(n)}),r=t?.stdin??go.stdin,s=[E.saveCursor,E.scrollRegion,E.restoreCursor,E.column,E.sgr,E.cursor,E.wrap];e.entersAltScreen===!0&&s.push(E.primaryBuffer),o(s.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var vo=e=>`infra-kit ${e.groupPath.join(" ")}`,Gr=()=>{let e=S.stderr.columns;return e!=null&&e>0?e:void 0},qr=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),Vr=async(e,t,o)=>{let r=no(),s={...t.env,[Y]:r,INFRA_KIT_NO_AUTO_UPDATE:"1"},n=t.now(),i={code:1,signal:null};o();try{let f=t.spawn(S.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:s});i=await qr(f)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let c=io(r),a=fo(i.code,i.signal,c!=null,e.longRunning),m=vo(e),u=c?.equivalent??B(m,!0);return po({equivalent:u,outcome:a,durationMs:t.now()-n,summary:c?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===m)})},Jr=(e,t)=>{let o=!1,r=!1,s=()=>{if(e()){o=!0;return}t.exit(0)},n=()=>{if(!e()){t.exit(0);return}o||(r=!0)},i=()=>{t.exit(129)},c=()=>{e()&&t.raise("SIGSTOP")};return t.register("SIGINT",s),t.register("SIGTERM",n),t.register("SIGHUP",i),t.register("SIGTSTP",c),{dispose:()=>{t.unregister("SIGINT",s),t.unregister("SIGTERM",n),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",c)},childStarted:()=>{o=!1},quitRequested:()=>r}},yo=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),wo=async(e,t)=>{let o={spawn:t.spawn??Ur,now:t.now??(()=>Date.now()),env:t.env??S.env,cliPath:t.cliPath,ascii:t.ascii??!(S.stdout.isTTY&&S.env.TERM!=="dumb"),color:t.color??jr.level>0,columns:t.columns??Gr,resetTerminal:t.resetTerminal??(a=>{ho(a)})},r=t.write??(a=>S.stderr.write(a)),s=t.signals??{register:(a,m)=>{S.on(a,m)},unregister:(a,m)=>{S.off(a,m)},exit:a=>{S.exit(a)},raise:a=>{S.kill(S.pid,a)}},n=!1,i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},c=t.installSignals===!1?i:Jr(()=>n,s);try{for(;;){if(c.quitRequested())return;n=!1;let a=await t.renderPalette(e);if(a==null)return;let m=t.resolveCommand(a);if(!m)continue;let u=uo(vo(m),{color:o.color});r(`
9
+ `)};var Mr=new Set([130,143]),fo=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Mr.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import go from"node:process";var E={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},ho=(e,t)=>{let o=t?.write??(n=>{go.stderr.write(n)}),r=t?.stdin??go.stdin,s=[E.saveCursor,E.scrollRegion,E.restoreCursor,E.column,E.sgr,E.cursor,E.wrap];e.entersAltScreen===!0&&s.push(E.primaryBuffer),o(s.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var vo=e=>`infra-kit ${e.groupPath.join(" ")}`,Gr=()=>{let e=S.stderr.columns;return e!=null&&e>0?e:void 0},Vr=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),qr=async(e,t,o)=>{let r=no(),s={...t.env,[Y]:r,INFRA_KIT_NO_AUTO_UPDATE:"1"},n=t.now(),i={code:1,signal:null};o();try{let f=t.spawn(S.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:s});i=await Vr(f)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let c=io(r),a=fo(i.code,i.signal,c!=null,e.longRunning),m=vo(e),u=c?.equivalent??B(m,!0);return po({equivalent:u,outcome:a,durationMs:t.now()-n,summary:c?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===m)})},Jr=(e,t)=>{let o=!1,r=!1,s=()=>{if(e()){o=!0;return}t.exit(0)},n=()=>{if(!e()){t.exit(0);return}o||(r=!0)},i=()=>{t.exit(129)},c=()=>{e()&&t.raise("SIGSTOP")};return t.register("SIGINT",s),t.register("SIGTERM",n),t.register("SIGHUP",i),t.register("SIGTSTP",c),{dispose:()=>{t.unregister("SIGINT",s),t.unregister("SIGTERM",n),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",c)},childStarted:()=>{o=!1},quitRequested:()=>r}},yo=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),wo=async(e,t)=>{let o={spawn:t.spawn??Ur,now:t.now??(()=>Date.now()),env:t.env??S.env,cliPath:t.cliPath,ascii:t.ascii??!(S.stdout.isTTY&&S.env.TERM!=="dumb"),color:t.color??jr.level>0,columns:t.columns??Gr,resetTerminal:t.resetTerminal??(a=>{ho(a)})},r=t.write??(a=>S.stderr.write(a)),s=t.signals??{register:(a,m)=>{S.on(a,m)},unregister:(a,m)=>{S.off(a,m)},exit:a=>{S.exit(a)},raise:a=>{S.kill(S.pid,a)}},n=!1,i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},c=t.installSignals===!1?i:Jr(()=>n,s);try{for(;;){if(c.quitRequested())return;n=!1;let a=await t.renderPalette(e);if(a==null)return;let m=t.resolveCommand(a);if(!m)continue;let u=uo(vo(m),{color:o.color});r(`
10
10
  ${u}
11
- `),c.childStarted();let f=await Vr(m,o,()=>{n=!0});r(`
11
+ `),c.childStarted();let f=await qr(m,o,()=>{n=!0});r(`
12
12
  ${f}
13
- `)}}finally{c.dispose()}};import{spawn as Br}from"node:child_process";import ko from"node:fs";import P from"node:process";import{fileURLToPath as Ro}from"node:url";var So=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Wr=new Set(["mcp","self-update"]),Kr=e=>e[2]!=null&&Wr.has(e[2]),be=e=>{let{argv:t,env:o,isTty:r,selfRealPath:s,cwd:n,realpath:i}=e;return So.some(a=>{let m=o[a];return m!=null&&m!==""})?"opt-out":t.includes("--json")?"json":Kr(t)?"own-command":r?G(s,n,i)?"local-install":null:"not-a-tty"};var Hr=e=>{Br(P.execPath,[e,"--parent-pid",String(P.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Yr=()=>Ro(new URL("./update-check.js",import.meta.url)),zr=()=>ko.realpathSync(Ro(new URL("./cli.js",import.meta.url))),Xr=/^[\w@./+-]+$/i,Qr=e=>Xr.test(e),Zr=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||ne(e.latestVersion,t)&&e.updateCommand.every(Qr)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},Pe=(e,t={})=>{try{let o=t.argv??P.argv,r=t.env??P.env,s=t.isTty??!!P.stdout.isTTY,n=t.cwd??P.cwd(),i=t.nowMs??Date.now(),c=t.selfRealPath??zr(),a=t.readCache??ie,m=t.spawnChild??Hr,u=t.fileExists??(x=>ko.existsSync(x)),f=t.notify??(x=>{l.info(x)});if(be({argv:o,env:r,isTty:s,selfRealPath:c,cwd:n,realpath:C})!==null)return;let k=a();if(Zr(k,e,f),!se(k,i))return;let R=t.childPath??Yr();if(!u(R))return;m(R)}catch{}};Ut();oo();var Ie=Te(),xo=async e=>{try{e?await Ie.parseAsync(e):await Ie.parseAsync()}catch(t){re(t)&&(l.info("Operation cancelled."),g.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),g.exit(1)}},on=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;G(tn(To(import.meta.url)),g.cwd(),C)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};on();Pe(et.version);var Ao=()=>Gt(Ie.commands),rn=async()=>{let e=Ao(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-EEEVHAMO.js");t=await o(e)}else{let o=Ae(e.map(s=>[s.name,s.description])),r=e.flatMap((s,n)=>[...e[n-1]?.group===s.group?[]:[new Eo(" "),new Eo(`\u2014 ${s.group} \u2014`)],{name:o[n]??s.name,value:s.name}]);t=await M(s=>en({message:"Select a command to run",choices:r},s),{output:g.stderr})}}catch(o){if(!re(o))throw o}return t},nn=async()=>{let{runCommandPalette:e}=await import("./boot-EEEVHAMO.js"),t=To(import.meta.url),o=new Map(Ot.map(r=>[r.groupPath.join(" "),r]));await wo(Ao(),{renderPalette:e,resolveCommand:r=>{let s=o.get(r);return s?{groupPath:s.groupPath,entersAltScreen:s.entersAltScreen,sessionEnvNotice:s.sessionEnvNotice,longRunning:s.longRunning}:void 0},cliPath:t})};if(g.argv.length<=2){let e={stdoutIsTTY:!!g.stdout.isTTY,stdinIsTTY:!!g.stdin.isTTY,stderrIsTTY:!!g.stderr.isTTY};if(yo(g.env,e))await nn();else{let t=await rn();t&&await xo(["node","infra-kit",...t.split(" ")])}}else await xo();
13
+ `)}}finally{c.dispose()}};import{spawn as Br}from"node:child_process";import ko from"node:fs";import P from"node:process";import{fileURLToPath as Ro}from"node:url";var So=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Wr=new Set(["mcp","self-update"]),Kr=e=>e[2]!=null&&Wr.has(e[2]),be=e=>{let{argv:t,env:o,isTty:r,selfRealPath:s,cwd:n,realpath:i}=e;return So.some(a=>{let m=o[a];return m!=null&&m!==""})?"opt-out":t.includes("--json")?"json":Kr(t)?"own-command":r?G(s,n,i)?"local-install":null:"not-a-tty"};var Hr=e=>{Br(P.execPath,[e,"--parent-pid",String(P.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Yr=()=>Ro(new URL("./update-check.js",import.meta.url)),zr=()=>ko.realpathSync(Ro(new URL("./cli.js",import.meta.url))),Xr=/^[\w@./+-]+$/i,Qr=e=>Xr.test(e),Zr=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||ne(e.latestVersion,t)&&e.updateCommand.every(Qr)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},Pe=(e,t={})=>{try{let o=t.argv??P.argv,r=t.env??P.env,s=t.isTty??!!P.stdout.isTTY,n=t.cwd??P.cwd(),i=t.nowMs??Date.now(),c=t.selfRealPath??zr(),a=t.readCache??ie,m=t.spawnChild??Hr,u=t.fileExists??(x=>ko.existsSync(x)),f=t.notify??(x=>{l.info(x)});if(be({argv:o,env:r,isTty:s,selfRealPath:c,cwd:n,realpath:C})!==null)return;let k=a();if(Zr(k,e,f),!se(k,i))return;let R=t.childPath??Yr();if(!u(R))return;m(R)}catch{}};Ut();oo();var Ie=Te(),xo=async e=>{try{e?await Ie.parseAsync(e):await Ie.parseAsync()}catch(t){re(t)&&(l.info("Operation cancelled."),g.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),g.exit(1)}},on=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;G(tn(To(import.meta.url)),g.cwd(),C)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};on();Pe(et.version);var Ao=()=>Gt(Ie.commands),rn=async()=>{let e=Ao(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-FHXCA53R.js");t=await o(e)}else{let o=Ae(e.map(s=>[s.name,s.description])),r=e.flatMap((s,n)=>[...e[n-1]?.group===s.group?[]:[new Eo(" "),new Eo(`\u2014 ${s.group} \u2014`)],{name:o[n]??s.name,value:s.name}]);t=await M(s=>en({message:"Select a command to run",choices:r},s),{output:g.stderr})}}catch(o){if(!re(o))throw o}return t},nn=async()=>{let{runCommandPalette:e}=await import("./boot-FHXCA53R.js"),t=To(import.meta.url),o=new Map(Ot.map(r=>[r.groupPath.join(" "),r]));await wo(Ao(),{renderPalette:e,resolveCommand:r=>{let s=o.get(r);return s?{groupPath:s.groupPath,entersAltScreen:s.entersAltScreen,sessionEnvNotice:s.sessionEnvNotice,longRunning:s.longRunning}:void 0},cliPath:t})};if(g.argv.length<=2){let e={stdoutIsTTY:!!g.stdout.isTTY,stdinIsTTY:!!g.stdin.isTTY,stderrIsTTY:!!g.stderr.isTTY};if(yo(g.env,e))await nn();else{let t=await rn();t&&await xo(["node","infra-kit",...t.split(" ")])}}else await xo();
14
14
  //# sourceMappingURL=cli.js.map
package/dist/mcp.js CHANGED
@@ -1,2 +1,2 @@
1
- import{_ as u,ba as f,p as d}from"./chunk-LM7IE2UD.js";import"./chunk-S45AAYXO.js";import"./chunk-Y72C523R.js";import"./chunk-A7FAXZGI.js";import{i as m,j as l}from"./chunk-GZNE5CBQ.js";import{s as c,t as p,u as s}from"./chunk-IVWPZEMC.js";import"./chunk-CHETBZ6M.js";import{StdioServerTransport as w}from"@modelcontextprotocol/sdk/server/stdio.js";import T from"node:process";import o from"node:process";var v=r=>{o.on("SIGINT",()=>{r.info({msg:"Received SIGINT. Shutting down..."}),o.exit(0)}),o.on("SIGTERM",()=>{r.info({msg:"Received SIGTERM. Shutting down..."}),o.exit(0)}),o.on("uncaughtException",e=>{r.fatal({err:e,msg:"Uncaught Exception"}),r.error(`Uncaught Exception! Check ${c}. Shutting down...`),r.flush(),o.exit(1)}),o.on("unhandledRejection",(e,n)=>{r.fatal({reason:e,promise:n,msg:"Unhandled Rejection"}),r.error(`Unhandled Rejection! Check ${c}. Shutting down...`),r.flush(),o.exit(1)})};import{McpServer as y}from"@modelcontextprotocol/sdk/server/mcp.js";var h=async r=>{};var x=async r=>{};var a=({toolName:r,handler:e})=>async n=>{s.info({msg:`Tool execution started: ${r}`,params:n});try{await d(),m.reset();let i=await e({...n,confirmedCommand:!0});return s.info({msg:`Tool execution successful: ${r}`}),i}catch(i){throw s.error({err:i,params:n,msg:`Tool execution failed: ${r}`}),i}};var S=async r=>{for(let e of u())r.registerTool(e.name,{description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema},a({toolName:e.name,handler:e.handler}))};async function g(){l.enabled=!0;let r=new y({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await h(r),await x(r),await S(r),r}f();var t=p(),M=async()=>{let r;try{r=await g(),t.info("MCP Server instance created")}catch(e){t.error({err:e,msg:"Failed to create MCP server"}),t.error("Fatal error during server creation."),T.exit(1)}try{let e=new w;await r.connect(e),t.info({msg:"Server connected to transport. Ready."})}catch(e){t.error({err:e,msg:"Failed to initialize server"}),t.error("Fatal error during server transport init."),T.exit(1)}};v(t);M();
1
+ import{_ as u,ba as f,p as d}from"./chunk-3G6O7MCC.js";import"./chunk-S45AAYXO.js";import"./chunk-T74NOBEP.js";import"./chunk-A7FAXZGI.js";import{i as m,j as l}from"./chunk-GZNE5CBQ.js";import{s as c,t as p,u as s}from"./chunk-IVWPZEMC.js";import"./chunk-CHETBZ6M.js";import{StdioServerTransport as w}from"@modelcontextprotocol/sdk/server/stdio.js";import T from"node:process";import o from"node:process";var v=r=>{o.on("SIGINT",()=>{r.info({msg:"Received SIGINT. Shutting down..."}),o.exit(0)}),o.on("SIGTERM",()=>{r.info({msg:"Received SIGTERM. Shutting down..."}),o.exit(0)}),o.on("uncaughtException",e=>{r.fatal({err:e,msg:"Uncaught Exception"}),r.error(`Uncaught Exception! Check ${c}. Shutting down...`),r.flush(),o.exit(1)}),o.on("unhandledRejection",(e,n)=>{r.fatal({reason:e,promise:n,msg:"Unhandled Rejection"}),r.error(`Unhandled Rejection! Check ${c}. Shutting down...`),r.flush(),o.exit(1)})};import{McpServer as y}from"@modelcontextprotocol/sdk/server/mcp.js";var h=async r=>{};var x=async r=>{};var a=({toolName:r,handler:e})=>async n=>{s.info({msg:`Tool execution started: ${r}`,params:n});try{await d(),m.reset();let i=await e({...n,confirmedCommand:!0});return s.info({msg:`Tool execution successful: ${r}`}),i}catch(i){throw s.error({err:i,params:n,msg:`Tool execution failed: ${r}`}),i}};var S=async r=>{for(let e of u())r.registerTool(e.name,{description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema},a({toolName:e.name,handler:e.handler}))};async function g(){l.enabled=!0;let r=new y({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await h(r),await x(r),await S(r),r}f();var t=p(),M=async()=>{let r;try{r=await g(),t.info("MCP Server instance created")}catch(e){t.error({err:e,msg:"Failed to create MCP server"}),t.error("Fatal error during server creation."),T.exit(1)}try{let e=new w;await r.connect(e),t.info({msg:"Server connected to transport. Ready."})}catch(e){t.error({err:e,msg:"Failed to initialize server"}),t.error("Fatal error during server transport init."),T.exit(1)}};v(t);M();
2
2
  //# sourceMappingURL=mcp.js.map
@@ -1,2 +1,2 @@
1
- import{h as i}from"./chunk-UO3FYLPX.js";import{a as t}from"./chunk-Y72C523R.js";import"./chunk-A7FAXZGI.js";import"./chunk-CHETBZ6M.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});
1
+ import{h as i}from"./chunk-EX66ZFV5.js";import{a as t}from"./chunk-T74NOBEP.js";import"./chunk-A7FAXZGI.js";import"./chunk-CHETBZ6M.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.3.4",
4
+ "version": "0.3.6",
5
5
  "files": [
6
6
  "dist"
7
7
  ],
@@ -1,2 +0,0 @@
1
- import{b as Z}from"./chunk-TPVXMJ7N.js";import{render as Ie}from"ink";import ce from"node:process";import{Box as J,Text as R,useApp as he,useInput as we,useWindowSize as xe}from"ink";import{useEffect as ee,useState as F}from"react";import{useMemo as de,useState as V}from"react";var D=(e,t)=>{let[r,m]=V(""),[n,a]=V(0),o=de(()=>{let d=r.trim().toLowerCase();return d?e.filter(p=>t(p).toLowerCase().includes(d)):e},[e,r,t]),u=Math.min(n,Math.max(0,o.length-1));return{filtered:o,activeIndex:u,query:r,handleNavigation:(d,p)=>{let S=o.length;return p.upArrow?(S>0&&a((u-1+S)%S),!0):p.downArrow?(S>0&&a((u+1)%S),!0):p.backspace||p.delete?(m(r.slice(0,-1)),a(0),!0):d&&!p.ctrl&&!p.meta?(m(r+d),a(0),!0):!1},clearQuery:()=>r?(m(""),a(0),!0):!1}};var pe=()=>{},_=(e,t=0)=>e<5?{mode:"tiny",chromeRows:0,groups:!1}:e<10?{mode:"compact",chromeRows:4+t,groups:!1}:{mode:"full",chromeRows:6+t,groups:!0},fe=(e,t,r,m)=>{let n=0,a;for(let o=t;o<r;o+=1){let u=e[o];if(!u)break;let w=m(u),T=w!==void 0&&w!==a;n+=1+(T?1:0)+(T&&o>t?1:0),a=w}return n},j=(e,t,r,m)=>{let n=t;for(;n<e.length&&fe(e,t,n+1,m)<=r;)n+=1;return n},$=(e,t,r,m,n)=>{let a=n?.groupOf??pe,o=Math.max(0,m-(n?.chromeRows??6)),u=Math.min(t,r);for(;r>=j(e,u,o,a)&&u<r;)u+=1;let w=j(e,u,o,a);return{visible:e.slice(u,w),start:u,hiddenBefore:u,hiddenAfter:Math.max(0,e.length-w)}};import{jsx as I,jsxs as G}from"react/jsx-runtime";var te=e=>{let{items:t,onSubmit:r,onCancel:m,required:n=!0,allowSelectAll:a=!0}=e,o=Te,u=t.reduce((s,x)=>Math.max(s,x.label.length),0),{exit:w}=he(),{rows:T}=xe(),{filtered:d,activeIndex:p,query:S,handleNavigation:v,clearQuery:M}=D(t,ge),[B,O]=F(()=>new Set),[E,h]=F(!1),[C,f]=F(0),[l,b]=F(!1);ee(()=>{l&&w()},[l,w]);let q=_(T,1),y=$(d,C,p,T,{chromeRows:q.chromeRows});ee(()=>{y.start!==C&&f(y.start)},[y.start,C]);let k=s=>{O(x=>{let g=new Set(x);return g.has(s)?g.delete(s):g.add(s),g})},H=()=>{O(s=>t.every(g=>s.has(g.value))?new Set:new Set(t.map(g=>g.value)))},i=()=>{m(),b(!0)},c=()=>{if(n&&B.size===0){h(!0);return}r([...B]),b(!0)};return we((s,x)=>{if(!l){if(x.ctrl&&s==="c"){i();return}if(x.escape){M()||i();return}if(x.ctrl&&s==="a"){a&&H();return}if(s===" "){let g=d[p];g&&k(g.value);return}if(x.return){c();return}v(s,x)}}),l?null:q.mode==="tiny"?I(R,{dimColor:!0,wrap:"truncate",children:o.tiny}):G(J,{flexDirection:"column",children:[q.mode==="full"?I(R,{dimColor:!0,wrap:"truncate",children:o.hint}):null,G(J,{children:[I(R,{color:"cyan",children:o.prompt}),I(R,{wrap:"truncate-start",children:S})]}),G(J,{flexDirection:"column",marginTop:q.mode==="full"?1:0,children:[d.length===0?I(R,{dimColor:!0,wrap:"truncate",children:o.empty}):null,y.hiddenBefore>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenBefore} above`}):null,y.visible.map((s,x)=>{let g=y.start+x===p,me=B.has(s.value);return G(R,{color:g?"green":void 0,wrap:"truncate",children:[g?"\u203A ":" ",me?"[x] ":"[ ] ",s.label.padEnd(u)," ",I(R,{dimColor:!0,children:s.description??""})]},s.value)}),y.hiddenAfter>0?I(R,{dimColor:!0,wrap:"truncate",children:`${o.more} ${y.hiddenAfter} below`}):null]}),E?I(R,{dimColor:!0,wrap:"truncate",children:o.requiredHint}):null]})};function ge(e){return`${e.label} ${e.description??""}`}var Te={hint:"filter \xB7 \u2191\u2193 move \xB7 Space toggle \xB7 Ctrl-A all \xB7 Enter submit \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick branches",requiredHint:"select at least one",more:"\u2026"};import{Box as U,Text as W,useApp as be,useInput as Se,useWindowSize as Ce}from"ink";import{useEffect as re,useState as ne}from"react";import{jsx as L,jsxs as z}from"react/jsx-runtime";var oe=e=>{let{items:t,onSelect:r,onCancel:m}=e,n=ve,a=t.reduce((f,l)=>Math.max(f,l.label.length),0),{exit:o}=be(),{rows:u}=Ce(),{filtered:w,activeIndex:T,query:d,handleNavigation:p,clearQuery:S}=D(t,Pe),[v,M]=ne(0),[B,O]=ne(!1);re(()=>{B&&o()},[B,o]);let E=_(u),h=$(w,v,T,u,{chromeRows:E.chromeRows});re(()=>{h.start!==v&&M(h.start)},[h.start,v]);let C=()=>{m(),O(!0)};return Se((f,l)=>{if(!B){if(l.ctrl&&f==="c"){C();return}if(l.escape){S()||C();return}if(l.return){let b=w[T];b&&(r(b.value),O(!0));return}p(f,l)}}),B?null:E.mode==="tiny"?L(W,{dimColor:!0,wrap:"truncate",children:n.tiny}):z(U,{flexDirection:"column",children:[E.mode==="full"?L(W,{dimColor:!0,wrap:"truncate",children:n.hint}):null,z(U,{children:[L(W,{color:"cyan",children:n.prompt}),L(W,{wrap:"truncate-start",children:d})]}),z(U,{flexDirection:"column",marginTop:E.mode==="full"?1:0,children:[w.length===0?L(W,{dimColor:!0,wrap:"truncate",children:n.empty}):null,h.hiddenBefore>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenBefore} above`}):null,h.visible.map((f,l)=>{let b=h.start+l===T;return z(W,{color:ye(f.type,b),wrap:"truncate",children:[b?"\u203A ":" ",f.label.padEnd(a)," ",L(W,{dimColor:!0,children:f.description??""})]},f.value)}),h.hiddenAfter>0?L(W,{dimColor:!0,wrap:"truncate",children:`${n.more} ${h.hiddenAfter} below`}):null]})]})};function ye(e,t){return e==="hotfix"?"red":t?"green":void 0}function Pe(e){return`${e.label} ${e.description??""}`}var ve={hint:"type to filter \xB7 \u2191\u2193 move \xB7 Enter select \xB7 Esc clear/cancel",prompt:"\u276F ",empty:"No matching branches",tiny:"terminal too short \u2014 resize to pick a branch",more:"\u2026"};import{Box as Q,Text as P,useApp as Be,useInput as Oe,useWindowSize as Re}from"ink";import{useEffect as ie,useMemo as Ae,useState as K}from"react";import{jsx as A,jsxs as N}from"react/jsx-runtime";var se=e=>{let{items:t,onSelect:r,onCancel:m,onSuspend:n}=e,a={hint:Ee(!!n),prompt:"\u276F ",empty:"No matching commands",tiny:"terminal too short \u2014 resize to pick a command",more:"\u2026"},o=24,{exit:u,suspendTerminal:w}=Be(),{rows:T}=Re(),[d,p]=K(""),[S,v]=K(0),[M,B]=K(0),[O,E]=K(!1);ie(()=>{O&&u()},[O,u]);let h=Ae(()=>{let i=d.trim().toLowerCase();return i?t.filter(c=>`${c.name} ${c.description}`.toLowerCase().includes(i)):t},[t,d]),C=Math.min(S,Math.max(0,h.length-1)),f=_(T),l=$(h,M,C,T,{chromeRows:f.chromeRows,groupOf:f.groups?i=>i.group:void 0});ie(()=>{l.start!==M&&B(l.start)},[l.start,M]);let b=()=>{m(),E(!0)},q=()=>{n&&w(n).catch(()=>{})},y=i=>i==="c"||i==="d"?(b(),!0):i==="z"?(q(),!0):!1,k=i=>{let c=h.length;c>0&&v((C+i+c)%c)};if(Oe((i,c)=>{if(!O&&!(c.ctrl&&y(i))){if(c.escape&&d){p(""),v(0);return}if(c.escape){b();return}if(c.return){let s=h[C];s&&(r(s.name),E(!0));return}if(c.upArrow){k(-1);return}if(c.downArrow){k(1);return}if(c.backspace||c.delete){p(d.slice(0,-1)),v(0);return}i&&!c.ctrl&&!c.meta&&(p(d+i),v(0))}}),O)return null;if(f.mode==="tiny")return A(P,{dimColor:!0,wrap:"truncate",children:a.tiny});let H="";return N(Q,{flexDirection:"column",children:[f.mode==="full"?A(P,{dimColor:!0,wrap:"truncate",children:a.hint}):null,N(Q,{children:[A(P,{color:"cyan",children:a.prompt}),A(P,{wrap:"truncate-start",children:d})]}),N(Q,{flexDirection:"column",marginTop:f.mode==="full"?1:0,children:[h.length===0?A(P,{dimColor:!0,wrap:"truncate",children:a.empty}):null,l.hiddenBefore>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenBefore} above`}):null,l.visible.map((i,c)=>{let s=l.start+c===C,x=f.groups&&i.group!==H;return H=i.group,N(Q,{flexDirection:"column",children:[x&&c>0?A(P,{children:" "}):null,x?A(P,{color:"yellow",wrap:"truncate",children:`\u2014 ${i.group} \u2014`}):null,N(P,{color:s?"green":void 0,wrap:"truncate",children:[s?"\u203A ":" ",i.name.padEnd(o)," ",A(P,{dimColor:!0,children:i.description})]})]},i.name)}),l.hiddenAfter>0?A(P,{dimColor:!0,wrap:"truncate",children:`${a.more} ${l.hiddenAfter} below`}):null]})]})},le={suspend:"filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear/quit \xB7 Ctrl-D quit \xB7 Ctrl-Z suspend",plain:"type to filter \xB7 \u2191\u2193 move \xB7 Enter run \xB7 Esc clear/quit \xB7 Ctrl-D quit"},Ee=e=>e?le.suspend:le.plain;import ae from"node:process";var ue=(e={})=>{let t=e.platform??ae.platform,r=e.kill??((m,n)=>{ae.kill(m,n)});if(t!=="win32")try{r(0,"SIGSTOP")}catch{}};import{jsx as X}from"react/jsx-runtime";var Y=async e=>{let t=Z(),{waitUntilExit:r}=Ie(e,{stdout:t,exitOnCtrlC:!1,interactive:!!t.isTTY});try{await r()}catch{}finally{ce.stdin.ref()}},st=async e=>{let t=null;return await Y(X(se,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null},onSuspend:ce.platform==="win32"?void 0:()=>{ue()}})),t},at=async e=>{let t=null;return await Y(X(oe,{items:e,onSelect:r=>{t=r},onCancel:()=>{t=null}})),t},ut=async(e,t)=>{let r=null;return await Y(X(te,{items:e,required:t?.required,allowSelectAll:t?.allowSelectAll,onSubmit:m=>{r=m},onCancel:()=>{r=null}})),r};export{ut as runBranchMultiPicker,at as runBranchPicker,st as runCommandPalette};
2
- //# sourceMappingURL=boot-EEEVHAMO.js.map
@@ -1,2 +0,0 @@
1
- import{b as P}from"./chunk-A7FAXZGI.js";import{m as f,q as x}from"./chunk-CHETBZ6M.js";import u from"node:path";var m="infra-kit",g=`${m}@latest`,S=(t,e,n)=>{let r=u.relative(n(u.resolve(t)),u.resolve(e));return r!==""&&!r.startsWith("..")&&!u.isAbsolute(r)},l=(t,e)=>u.resolve(t).split(u.sep).includes(e),z=(t,e)=>{let n=u.resolve(t).split(u.sep),r=n.indexOf("Cellar");return r!==-1&&n[r+1]===e},C=(t,e,n,r)=>{let a=t[e];return a!=null&&a!==""&&S(a,n,r)},H=[{manager:"volta",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"VOLTA_HOME",t,n)||l(t,".volta")||l(t,"volta"),updateCommand:["volta","install",m],canSelfSpawn:!0},{manager:"homebrew",test:({selfRealPath:t})=>z(t,m),updateCommand:["brew","upgrade",m],canSelfSpawn:!1},{manager:"pnpm",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"PNPM_HOME",t,n)||l(t,"pnpm")&&l(t,"global"),updateCommand:["pnpm","add","-g",g],canSelfSpawn:!0},{manager:"bun",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"BUN_INSTALL",t,n)||l(t,".bun"),updateCommand:["bun","add","-g",g],canSelfSpawn:!0},{manager:"yarn",test:({selfRealPath:t})=>l(t,".yarn")||l(t,"yarn")&&l(t,"global"),updateCommand:["yarn","global","add",g],canSelfSpawn:!0},{manager:"npm",test:({selfRealPath:t,env:e,realpath:n})=>C(e,"npm_config_prefix",t,n),updateCommand:["npm","install","-g",g],canSelfSpawn:!0}],E=["npm","install","-g",g],b=t=>{let{selfRealPath:e,env:n,realpath:r,lazyNpmRoot:a}=t,s=H.find(({test:i})=>i({selfRealPath:e,env:n,realpath:r}));if(s)return{manager:s.manager,updateCommand:s.updateCommand,canSelfSpawn:s.canSelfSpawn};let o=a?.();return o!=null&&o!==""&&S(o,e,r)?{manager:"npm",updateCommand:E,canSelfSpawn:!0}:{manager:"unknown",updateCommand:E,canSelfSpawn:!1}},K=(t,e,n)=>l(t,"node_modules")&&S(e,t,n);import{realpathSync as G}from"node:fs";import $ from"node:path";var M=t=>{try{return G(t)}catch{return $.resolve(t)}};import{execFileSync as W}from"node:child_process";import B from"node:process";var Y=3e3,k=()=>{try{let e=W("npm",["root","-g"],{encoding:"utf-8",timeout:Y,stdio:["ignore","pipe","ignore"],shell:B.platform==="win32"}).trim();return e===""?void 0:e}catch{return}};import{spawnSync as de}from"node:child_process";import{homedir as fe}from"node:os";import v from"node:process";import d from"node:fs";import I from"node:path";import Q from"node:process";var X="update-check.lock",Z=1800*1e3,ee=()=>I.join(f(),X),te=(t,e)=>{try{e-d.statSync(t).mtimeMs>Z&&d.rmSync(t,{force:!0})}catch{}},N=(t={})=>{let e=t.nowMs??Date.now(),n=t.lockPath??ee();try{d.mkdirSync(I.dirname(n),{recursive:!0})}catch{return null}let r=()=>{try{return d.openSync(n,"wx",384)}catch{return null}},a=r();if(a===null&&(te(n,e),a=r()),a===null)return null;try{d.writeFileSync(a,String(Q.pid))}catch{}return()=>{try{d.closeSync(a)}catch{}try{d.rmSync(n,{force:!0})}catch{}}};var ne="https://registry.npmjs.org",re=2500,ae=t=>Object.entries(t).find(([n,r])=>/^npm_config_registry$/i.test(n)&&r!=null&&r!=="")?.[1],oe=t=>{let e=ae(t),n=e!=null&&e!==""?e:ne;for(;n.endsWith("/");)n=n.slice(0,-1);return n},A=async(t,e=fetch)=>{let n=new AbortController,r=setTimeout(()=>{n.abort()},re);try{let a=await e(`${oe(t)}/${m}/latest`,{signal:n.signal,headers:{accept:"application/json"}});if(!a.ok)return null;let o=(await a.json())?.version;return typeof o=="string"&&o!==""?o:null}catch{return null}finally{clearTimeout(r)}};var se=/^(\d+)\.(\d+)\.(\d+)$/,R=t=>{let[e=""]=t.trim().split("+"),[n="",...r]=e.split("-"),a=se.exec(n);if(!a)return null;let[s,o,i]=[a[1],a[2],a[3]].map(Number);return{release:[s,o,i],prerelease:r.length>0?r.join("-").split("."):[]}},_=/^\d+$/,le=(t,e)=>{let n=_.test(t),r=_.test(e);return n&&r?Number(t)-Number(e):n!==r?n?-1:1:t<e?-1:1},ie=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n+=1){let r=t[n],a=e[n];if(r===void 0)return-1;if(a===void 0)return 1;if(r!==a)return le(r,a)}return 0},L=(t,e)=>{let n=R(t),r=R(e);if(!n||!r)return!1;for(let o=0;o<3;o+=1){let i=n.release[o],h=r.release[o];if(i!==h)return i>h}let a=n.prerelease.length===0,s=r.prerelease.length===0;return a!==s?a:ie(n.prerelease,r.prerelease)>0};import U from"node:fs";import T from"node:path";var O="update-check.json",ce=1440*60*1e3,ue=()=>T.join(f(),O),pe=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),me=t=>{if(typeof t!="object"||t===null)return!1;let{lastCheckMs:e,latestVersion:n,updateCommand:r}=t;return typeof e=="number"&&Number.isFinite(e)&&(n===null||typeof n=="string")&&(r===null||pe(r))},Ke=(t=e=>U.readFileSync(e,"utf8"))=>{try{let e=JSON.parse(t(ue()));return me(e)?e:null}catch{return null}},F=t=>{let e=f();U.mkdirSync(e,{recursive:!0}),x(T.join(e,O),JSON.stringify(t),384)},Ge=(t,e)=>{if(!t)return!0;let n=e-t.lastCheckMs;return n>=ce||n<0};var ge=200,he=300*1e3,ye=t=>{try{return v.kill(t,0),!0}catch{return!1}},Ce=t=>new Promise(e=>{setTimeout(e,t)}),we=async(t,e)=>{let n=e.clock()+he;for(;e.clock()<n;){if(!e.isProcessAlive(t))return!0;await e.sleep(ge)}return!e.isProcessAlive(t)},rt=async(t,e)=>{let r=(e.acquireLock??N)();if(!r)return"already-running";try{return await Se(t,e)}finally{r()}},Se=async(t,e)=>{let n=e.env??v.env,r=e.nowMs??Date.now(),a=e.fetchLatest??A,s=e.writeCache??F,o=e.isProcessAlive??ye,i=e.sleep??Ce,h=e.clock??Date.now,D=e.lazyNpmRoot??k,V=e.spawnSync??de,c=await a(n),p=(J,q)=>(s({lastCheckMs:r,...q}),J);if(c===null)return p("fetch-failed",{latestVersion:null,updateCommand:null});if(!L(c,t))return p("up-to-date",{latestVersion:c,updateCommand:null});let{canSelfSpawn:j,updateCommand:y}=b({selfRealPath:e.selfRealPath,env:n,realpath:M,lazyNpmRoot:D});if(!j)return p("cannot-self-spawn",{latestVersion:c,updateCommand:y});if(e.parentPid==null)return p("parent-unknown",{latestVersion:c,updateCommand:null});if(s({lastCheckMs:r,latestVersion:c,updateCommand:null}),!await we(e.parentPid,{isProcessAlive:o,sleep:i,clock:h}))return p("parent-still-running",{latestVersion:c,updateCommand:null});let w=V(y[0],y.slice(1),{stdio:"ignore",shell:v.platform==="win32",cwd:fe(),env:P(n),windowsHide:!0});return w.error||w.signal||w.status!==0?p("install-failed",{latestVersion:c,updateCommand:y}):p("installed",{latestVersion:null,updateCommand:null})};export{b as a,K as b,k as c,M as d,L as e,Ke as f,Ge as g,rt as h};
2
- //# sourceMappingURL=chunk-UO3FYLPX.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/lib/install-manager/install-manager.ts", "../src/lib/install-manager/safe-realpath.ts", "../src/lib/install-manager/npm-root.ts", "../src/lib/update-check/run-update-check.ts", "../src/lib/update-check/lock.ts", "../src/lib/update-check/registry.ts", "../src/lib/update-check/semver.ts", "../src/lib/update-check/update-cache.ts"],
4
- "sourcesContent": ["/**\n * Pure detection of *how* this CLI was installed, so a self-update advisory can name the one command\n * that will actually work. No fs, no spawn, no `process.env` read \u2014 every input is injected, which is\n * what lets the whole matrix be table-tested.\n *\n * Detection is env-first and LAZY: the only signal that costs a subprocess (`npm root -g`) is passed in\n * as `lazyNpmRoot` and consulted solely when every cheaper matcher has missed.\n */\nimport path from 'node:path'\n\n/** The published package this CLI updates itself to. Single source for every suggested argv. */\nexport const PACKAGE_NAME = 'infra-kit'\n\nconst LATEST = `${PACKAGE_NAME}@latest`\n\nexport type InstallManager = 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | 'homebrew' | 'unknown'\n\nexport interface InstallManagerInfo {\n manager: InstallManager\n /** The command to run. Only safe to spawn ourselves when `canSelfSpawn`; otherwise print it. */\n updateCommand: string[]\n /** False when we must not run the command for the user \u2014 either it needs sudo/a tap, or we guessed. */\n canSelfSpawn: boolean\n}\n\n/**\n * Canonicalises a candidate *root* directory. Required, not optional: `selfRealPath` has already had its\n * symlinks followed, so comparing it against a raw `PNPM_HOME`/`npm root -g`/`cwd` compares a resolved\n * path to an unresolved one and silently never matches. macOS is the everyday proof \u2014 `/var` is a symlink\n * to `/private/var`, so a global install under `/var/...` reports `unknown` unless both sides are resolved.\n * Callers inject the real thing; tests inject a stub.\n */\nexport type RealpathFn = (dir: string) => string\n\nexport interface DetectInstallManagerInput {\n /** Fully-resolved (symlinks followed) path to this CLI's entry file. */\n selfRealPath: string\n env: NodeJS.ProcessEnv\n /** Canonicalises each candidate root before comparison. See {@link RealpathFn}. */\n realpath: RealpathFn\n /** `npm root -g`, deferred: invoked at most once, and only when no cheaper matcher hit. */\n lazyNpmRoot?: () => string | undefined\n}\n\n/**\n * Is `child` inside the `parent` subtree? Boundary-aware: a naive `startsWith` would call\n * `/Users/x/pnpm-ish` a child of `/Users/x/pnpm`. `parent` is canonicalised first because it arrives raw\n * from the environment while `child` is already a realpath.\n */\nconst isWithin = (parent: string, child: string, realpath: RealpathFn): boolean => {\n const rel = path.relative(realpath(path.resolve(parent)), path.resolve(child))\n\n return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)\n}\n\n/** Does `p` contain `name` as a whole path SEGMENT? `/a/node_modules_backup/b` must not match `node_modules`. */\nconst hasSegment = (p: string, name: string): boolean => {\n return path.resolve(p).split(path.sep).includes(name)\n}\n\n/**\n * Is `p` inside a Homebrew keg belonging to the `name` FORMULA \u2014 i.e. `.../Cellar/<name>/<version>/...`?\n *\n * The formula name is what makes this sound. A bare `Cellar` segment says only \"somewhere under a keg\",\n * and the keg it lands in is routinely someone else's: when npm's global prefix is a node keg\n * (`npm config set prefix \"$(brew --prefix node)\"`, or any keg-only `node@X`), an `npm i -g` package\n * installs to `Cellar/node/<v>/lib/node_modules/<pkg>/...` \u2014 brew has never heard of it, yet the segment\n * is right there. Requiring `<name>` to sit directly after `Cellar` is what separates \"brew installed\n * THIS\" from \"brew installed the runtime that installed this\".\n *\n * Works for both keg layouts, since each is rooted at the formula: a plain formula\n * (`Cellar/infra-kit/1.2.3/bin/infra-kit`) and brew's node-CLI layout\n * (`Cellar/infra-kit/1.2.3/libexec/lib/node_modules/infra-kit/dist/cli.js`). Do NOT try to tell them\n * apart by excluding `node_modules` \u2014 the second one contains it.\n */\nconst isBrewKegOf = (p: string, name: string): boolean => {\n const segments = path.resolve(p).split(path.sep)\n const cellar = segments.indexOf('Cellar')\n\n return cellar !== -1 && segments[cellar + 1] === name\n}\n\n/** `env[key]` names a directory that contains `selfRealPath`. Absent/empty env var \u2192 no match. */\nconst underEnvDir = (env: NodeJS.ProcessEnv, key: string, selfRealPath: string, realpath: RealpathFn): boolean => {\n const dir = env[key]\n\n return dir != null && dir !== '' && isWithin(dir, selfRealPath, realpath)\n}\n\ninterface Matcher extends Omit<InstallManagerInfo, 'manager'> {\n manager: InstallManager\n test: (input: Required<Pick<DetectInstallManagerInput, 'selfRealPath' | 'env' | 'realpath'>>) => boolean\n}\n\n/**\n * Ordered, first-hit-wins. Order matters: volta and homebrew wrap an npm-shaped layout, so they must be\n * consulted before the generic npm prefix matcher would claim them.\n */\nconst MATCHERS: Matcher[] = [\n {\n manager: 'volta',\n // volta owns the shim; `volta install` is the correct tool, not a workaround \u2014 so we may run it.\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'VOLTA_HOME', selfRealPath, realpath) ||\n hasSegment(selfRealPath, '.volta') ||\n hasSegment(selfRealPath, 'volta')\n )\n },\n updateCommand: ['volta', 'install', PACKAGE_NAME],\n canSelfSpawn: true,\n },\n {\n manager: 'homebrew',\n // `brew upgrade` can touch the prefix, relink, and prompt \u2014 never ours to run unattended.\n //\n // Our own keg is the ONLY sound signal \u2014 see {@link isBrewKegOf}. Two broader tests look plausible\n // and are both wrong, because each answers \"did brew put something here?\" when the question is \"does\n // brew own THIS package?\":\n // - `HOMEBREW_PREFIX` containment: when node comes from brew, npm's global prefix IS\n // $HOMEBREW_PREFIX, so EVERY `npm i -g` package lands under it, unknown to brew.\n // - a bare `Cellar` segment: an npm prefix pointed at a node keg puts packages inside that keg.\n // Either misfire tells macOS users to run `brew upgrade infra-kit` \u2014 a formula that does not exist \u2014\n // and, far worse, makes the background auto-updater bail with `cannot-self-spawn` forever, so the\n // very fix for it can never reach them. Detection runs on the realpath, and a linked brew bin always\n // resolves into its own keg, so the narrow test has no false negatives to trade for this.\n test: ({ selfRealPath }) => {\n return isBrewKegOf(selfRealPath, PACKAGE_NAME)\n },\n updateCommand: ['brew', 'upgrade', PACKAGE_NAME],\n canSelfSpawn: false,\n },\n {\n manager: 'pnpm',\n test: ({ selfRealPath, env, realpath }) => {\n return (\n underEnvDir(env, 'PNPM_HOME', selfRealPath, realpath) ||\n (hasSegment(selfRealPath, 'pnpm') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['pnpm', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'bun',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'BUN_INSTALL', selfRealPath, realpath) || hasSegment(selfRealPath, '.bun')\n },\n updateCommand: ['bun', 'add', '-g', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'yarn',\n test: ({ selfRealPath }) => {\n return (\n hasSegment(selfRealPath, '.yarn') || (hasSegment(selfRealPath, 'yarn') && hasSegment(selfRealPath, 'global'))\n )\n },\n updateCommand: ['yarn', 'global', 'add', LATEST],\n canSelfSpawn: true,\n },\n {\n manager: 'npm',\n test: ({ selfRealPath, env, realpath }) => {\n return underEnvDir(env, 'npm_config_prefix', selfRealPath, realpath)\n },\n updateCommand: ['npm', 'install', '-g', LATEST],\n canSelfSpawn: true,\n },\n]\n\nconst NPM_UPDATE_COMMAND = ['npm', 'install', '-g', LATEST]\n\n/**\n * Identify the package manager that owns `selfRealPath`.\n *\n * `lazyNpmRoot` is the fallback probe and is invoked at most once, only after every env/path matcher has\n * missed \u2014 a global `npm root -g` subprocess is never paid for a pnpm or volta install. When nothing\n * matches we report `unknown` with an npm command that is a *suggestion only* (`canSelfSpawn: false`):\n * running a guessed global install is worse than printing one.\n *\n * @example\n * detectInstallManager({ selfRealPath: '/Users/x/Library/pnpm/global/5/node_modules/infra-kit/dist/cli.js', env: {} })\n * // => { manager: 'pnpm', updateCommand: ['pnpm', 'add', '-g', 'infra-kit@latest'], canSelfSpawn: true }\n */\nexport const detectInstallManager = (input: DetectInstallManagerInput): InstallManagerInfo => {\n const { selfRealPath, env, realpath, lazyNpmRoot } = input\n const hit = MATCHERS.find(({ test }) => {\n return test({ selfRealPath, env, realpath })\n })\n\n if (hit) return { manager: hit.manager, updateCommand: hit.updateCommand, canSelfSpawn: hit.canSelfSpawn }\n\n const npmRoot = lazyNpmRoot?.()\n\n if (npmRoot != null && npmRoot !== '' && isWithin(npmRoot, selfRealPath, realpath)) {\n return { manager: 'npm', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: true }\n }\n\n return { manager: 'unknown', updateCommand: NPM_UPDATE_COMMAND, canSelfSpawn: false }\n}\n\n/**\n * Is this CLI running from a *project-local* `node_modules` (as opposed to a global root)?\n *\n * The cwd clause is what does the distinguishing \u2014 BOTH a project install and a global root contain a\n * `/node_modules/` segment (`pnpm root -g` is `~/Library/pnpm/global/5/node_modules`). Without it we\n * would nag every global pnpm user to stop using a local install they do not have.\n *\n * Accepted false-negative: invoked from a subdirectory (cwd `project/apps/x`, deps at\n * `project/node_modules`) this returns false and the advisory stays silent. Under-warning is the safe\n * direction for a best-effort, never-throwing advisory \u2014 do not \"fix\" it by dropping the cwd clause.\n *\n * `cwd` is canonicalised before comparison for the same reason `detectInstallManager` canonicalises its\n * roots: `selfRealPath` is a realpath, and comparing it to an unresolved cwd never matches.\n *\n * @example\n * isLocalNodeModulesInstall('/repo/node_modules/infra-kit/dist/cli.js', '/repo', (p) => p) // => true\n */\nexport const isLocalNodeModulesInstall = (selfRealPath: string, cwd: string, realpath: RealpathFn): boolean => {\n return hasSegment(selfRealPath, 'node_modules') && isWithin(cwd, selfRealPath, realpath)\n}\n", "import { realpathSync } from 'node:fs'\nimport path from 'node:path'\n\n/**\n * The impure companion to the pure detection module: canonicalise a directory that may not exist.\n *\n * `realpathSync` throws on a missing path, and candidate roots routinely miss \u2014 `PNPM_HOME` can point at a\n * directory the user never created, `npm root -g` can name a prefix that was removed. A throw there would\n * turn \"we could not identify your install\" into a crash, so an unresolvable path falls back to\n * `path.resolve`, which still normalises `.`/`..` and yields a usable, non-matching absolute path.\n */\nexport const safeRealpath = (dir: string): string => {\n try {\n return realpathSync(dir)\n } catch {\n return path.resolve(dir)\n }\n}\n", "/* eslint-disable sonarjs/no-os-command-from-path */\n/**\n * `npm root -g`, the LAZY fallback for {@link detectInstallManager}.\n *\n * Why it is indispensable: the `npm` matcher keys off `npm_config_prefix`, which npm sets only while npm\n * itself is running. A user who ran `npm i -g infra-kit` months ago and now types `ik` has no such var,\n * so every cheap matcher misses and detection reports `unknown` / `canSelfSpawn: false`. Without this\n * probe the single most common install method can never update itself.\n *\n * Shared by `self-update` (interactive) and the background update worker so the two can never disagree\n * about who owns the install.\n */\nimport { execFileSync } from 'node:child_process'\nimport process from 'node:process'\n\nconst NPM_ROOT_TIMEOUT_MS = 3_000\n\n/**\n * The global npm root, or undefined when npm is absent, slow, or errors. Costs a subprocess, so\n * `detectInstallManager` invokes it at most once and only after every env/path matcher has missed \u2014 a\n * pnpm or volta install never pays for it.\n *\n * Resolving the user's `npm` from PATH is inherent here: we must ask the very package manager that owns\n * this install where its global root is. Pinning an absolute path would defeat the detection.\n *\n * @example\n * defaultLazyNpmRoot() // => '/usr/local/lib/node_modules' | undefined\n */\nexport const defaultLazyNpmRoot = (): string | undefined => {\n try {\n const out = execFileSync('npm', ['root', '-g'], {\n encoding: 'utf-8',\n timeout: NPM_ROOT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n shell: process.platform === 'win32',\n })\n const trimmed = out.trim()\n\n return trimmed === '' ? undefined : trimmed\n } catch {\n return undefined\n }\n}\n", "/**\n * The CHILD half of the auto-update, spawned detached by `maybeAutoUpdate`. It outlives the CLI\n * invocation that started it, so it may take its time and it may replace the binary.\n *\n * WHY IT WAITS FOR THE PARENT TO EXIT \u2014 the load-bearing invariant of this whole feature:\n * `scripts/build.js` sets esbuild `splitting: true`, so `dist/cli.js` lazily imports sibling\n * `chunk-*.js` files at runtime (that is how the Ink TUI stays off the fast path). A package manager\n * installing over `dist/` mid-command deletes chunks the parent has not imported yet, and the parent\n * dies on a dynamic import of a file that no longer exists. Waiting for the parent to exit is what\n * makes a silent background install safe rather than a random crash under `infra-kit dev`.\n */\nimport { spawnSync } from 'node:child_process'\nimport { homedir } from 'node:os'\nimport process from 'node:process'\n\nimport { defaultLazyNpmRoot, detectInstallManager, safeRealpath } from 'src/lib/install-manager'\nimport { packageManagerInstallEnv } from 'src/lib/pm-env'\n\nimport { acquireUpdateLock } from './lock'\nimport { fetchLatestVersion } from './registry'\nimport { isNewerVersion } from './semver'\nimport { writeUpdateCache } from './update-cache'\nimport type { UpdateCache } from './update-cache'\n\n/** How often to re-check whether the parent is gone. */\nexport const PARENT_POLL_INTERVAL_MS = 200\n\n/**\n * Give up waiting after this long. A long-lived parent (`infra-kit dev` runs for hours) must not leave\n * an immortal child pinned to a stale version: we simply skip this cycle. `lastCheckMs` is already\n * persisted by then, so the next short-lived command re-checks after the normal 24h window.\n */\nexport const PARENT_WAIT_TIMEOUT_MS = 5 * 60 * 1000\n\nexport interface RunUpdateCheckDeps {\n env?: NodeJS.ProcessEnv\n nowMs?: number\n fetchLatest?: (env: NodeJS.ProcessEnv) => Promise<string | null>\n writeCache?: typeof writeUpdateCache\n isProcessAlive?: (pid: number) => boolean\n sleep?: (ms: number) => Promise<void>\n /** Monotonic-ish source for the parent-wait deadline. Injected so the timeout is testable without real time. */\n clock?: () => number\n /** `npm root -g` probe. Defaults to the real subprocess; this child is detached, so it can afford one. */\n lazyNpmRoot?: () => string | undefined\n /** Single-flight guard. Returns a release fn, or null when another worker already holds the lock. */\n acquireLock?: () => (() => void) | null\n spawnSync?: typeof spawnSync\n /** Realpath of the installed `dist/cli.js`, used to identify the owning package manager. */\n selfRealPath: string\n parentPid?: number\n}\n\n/** Signal 0 performs the permission/existence check without delivering anything. */\nconst defaultIsProcessAlive = (pid: number): boolean => {\n try {\n process.kill(pid, 0)\n\n return true\n } catch {\n return false\n }\n}\n\nconst defaultSleep = (ms: number): Promise<void> => {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\n/**\n * Block until `parentPid` exits or {@link PARENT_WAIT_TIMEOUT_MS} elapses. Returns whether the parent\n * is actually gone \u2014 the caller must not install on a timeout.\n */\nconst waitForParentExit = async (\n parentPid: number,\n deps: Required<Pick<RunUpdateCheckDeps, 'isProcessAlive' | 'sleep' | 'clock'>>,\n): Promise<boolean> => {\n const deadline = deps.clock() + PARENT_WAIT_TIMEOUT_MS\n\n while (deps.clock() < deadline) {\n if (!deps.isProcessAlive(parentPid)) return true\n\n await deps.sleep(PARENT_POLL_INTERVAL_MS)\n }\n\n return !deps.isProcessAlive(parentPid)\n}\n\nexport type UpdateCheckOutcome =\n | 'installed'\n | 'install-failed'\n | 'up-to-date'\n | 'fetch-failed'\n | 'cannot-self-spawn'\n | 'parent-still-running'\n | 'parent-unknown'\n | 'already-running'\n\n/**\n * Fetch, decide, and (when safe) install \u2014 returning WHY it did what it did so tests can distinguish\n * \"no update\" from \"could not install\". Never throws.\n *\n * `lastCheckMs` is written from the ATTEMPT, before any early return. If it were written only on\n * success, an offline user would re-spawn a doomed child on every single command.\n *\n * @example\n * await runUpdateCheck('0.1.130', { selfRealPath: '/usr/local/lib/node_modules/infra-kit/dist/cli.js' })\n * // => 'installed'\n */\nexport const runUpdateCheck = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const acquireLock = deps.acquireLock ?? acquireUpdateLock\n\n // Single-flight. N shells launched at once all read the same stale cache and each spawns a worker;\n // the cache throttle cannot stop them because it is only written after the fetch returns. Without\n // this, a pending update means N concurrent `npm install -g` over one global directory.\n const release = acquireLock()\n\n if (!release) return 'already-running'\n\n try {\n return await runUpdateCheckLocked(currentVersion, deps)\n } finally {\n release()\n }\n}\n\nconst runUpdateCheckLocked = async (currentVersion: string, deps: RunUpdateCheckDeps): Promise<UpdateCheckOutcome> => {\n const env = deps.env ?? process.env\n const nowMs = deps.nowMs ?? Date.now()\n const fetchLatest = deps.fetchLatest ?? fetchLatestVersion\n const writeCache = deps.writeCache ?? writeUpdateCache\n const isProcessAlive = deps.isProcessAlive ?? defaultIsProcessAlive\n const sleep = deps.sleep ?? defaultSleep\n const clock = deps.clock ?? Date.now\n const lazyNpmRoot = deps.lazyNpmRoot ?? defaultLazyNpmRoot\n const spawn = deps.spawnSync ?? spawnSync\n\n const latestVersion = await fetchLatest(env)\n\n // Every path below writes the cache EXACTLY once, and always with `lastCheckMs: nowMs` \u2014 the throttle\n // burns on the ATTEMPT, never on success. If it burned only on success, an offline user would respawn\n // a doomed child on every command.\n const finish = (outcome: UpdateCheckOutcome, cache: Omit<UpdateCache, 'lastCheckMs'>): UpdateCheckOutcome => {\n writeCache({ lastCheckMs: nowMs, ...cache })\n\n return outcome\n }\n\n if (latestVersion === null) return finish('fetch-failed', { latestVersion: null, updateCommand: null })\n if (!isNewerVersion(latestVersion, currentVersion))\n return finish('up-to-date', { latestVersion, updateCommand: null })\n\n // `lazyNpmRoot` is what makes the COMMON case work: a plain `npm i -g infra-kit` leaves no\n // `npm_config_prefix` in the user's shell, so every cheap matcher misses and detection would report\n // `unknown` / `canSelfSpawn: false`. Without this probe the auto-update would silently degrade to a\n // notice for the majority of installs. The subprocess is affordable here and nowhere else.\n const { canSelfSpawn, updateCommand } = detectInstallManager({\n selfRealPath: deps.selfRealPath,\n env,\n realpath: safeRealpath,\n lazyNpmRoot,\n })\n\n // Homebrew relinks its prefix and may prompt; an unknown location means the command is a guess.\n // Both stay the user's call, so record the command for `maybeAutoUpdate` to print next invocation.\n if (!canSelfSpawn) return finish('cannot-self-spawn', { latestVersion, updateCommand })\n\n // Fail SAFE. Without a parent to outlive we cannot know whether a live CLI is still lazily importing\n // `chunk-*.js` out of the `dist/` we are about to replace, so we skip the cycle rather than install\n // blind. The real spawn always passes `--parent-pid`; only a hand-run worker lands here.\n if (deps.parentPid == null) return finish('parent-unknown', { latestVersion, updateCommand: null })\n\n // Burn the throttle NOW, before the two unbounded-ish operations below (a 5-minute parent wait, then an\n // install of no fixed duration). Everything after this point can take many minutes, and until the cache\n // is written it still reads as STALE \u2014 so every new shell in that window spawns its own worker, and the\n // single-flight lock becomes the only thing standing between them and concurrent `npm install -g` runs\n // over one global directory. The lock is reaped by mtime (LOCK_STALE_MS), so a slow enough install has\n // its live lock stolen and we get exactly the pile-up the lock exists to prevent.\n //\n // Writing the stamp here makes the throttle \u2014 not the lock \u2014 the primary guard, which is what the cache\n // was always for. `finish()` overwrites this with the real outcome; this is the only path that writes\n // the cache twice, and deliberately so.\n writeCache({ lastCheckMs: nowMs, latestVersion, updateCommand: null })\n\n const parentGone = await waitForParentExit(deps.parentPid, { isProcessAlive, sleep, clock })\n\n // A long-lived parent (`infra-kit dev`) outlasted the wait. Stay silent and retry next window.\n if (!parentGone) return finish('parent-still-running', { latestVersion, updateCommand: null })\n\n // `shell` on win32 so the `.cmd` shims npm/pnpm/yarn ship as global bins resolve.\n //\n // `packageManagerInstallEnv` strips the inherited npx/dlx markers \u2014 which otherwise make\n // pnpm/portless-style tools believe they were invoked via `npx`/`dlx` and refuse to run \u2014 while KEEPING\n // `npm_config_prefix` and `npm_config_registry`. Using the blunt `withoutPackageManagerEnv` here was a\n // bug: it also erased the prefix that `detectInstallManager` had just matched on, so we would detect a\n // global install at prefix P and then install into the default prefix instead \u2014 silently, forever. See\n // the module doc on `packageManagerInstallEnv`.\n //\n // `cwd` is pinned to the home directory, and this is a SECURITY control, not tidiness: npm resolves\n // `registry=` from an `.npmrc` on disk relative to the cwd. Inheriting the caller's cwd would let any\n // repo containing a hostile `.npmrc` silently redirect this unattended `install -g` to an attacker's\n // registry, executing its lifecycle scripts. Stripping `npm_config_registry` from the env does NOT\n // close that hole, because the redirect lives in a file, not the environment.\n const result = spawn(updateCommand[0] as string, updateCommand.slice(1), {\n stdio: 'ignore',\n shell: process.platform === 'win32',\n cwd: homedir(),\n env: packageManagerInstallEnv(env),\n windowsHide: true,\n })\n\n // Record the manual command so a persistently failing silent install (EACCES on a root-owned global\n // dir, say) still surfaces ONE actionable line, instead of failing invisibly forever.\n if (result.error || result.signal || result.status !== 0) {\n return finish('install-failed', { latestVersion, updateCommand })\n }\n\n // The installed version is now `latestVersion`; clear it so the next run does not re-notify.\n return finish('installed', { latestVersion: null, updateCommand: null })\n}\n", "/**\n * Single-flight lock for the background update worker.\n *\n * Without it, N shells starting at once all read the same stale cache and each spawns a worker \u2014 and\n * once a newer version exists, each of those runs `npm install -g` concurrently, over the same global\n * directory. (Measured: five concurrent `ik` invocations spawn five workers.) The throttle in the cache\n * cannot prevent this: it is only written AFTER the fetch returns, long after the other workers launched.\n *\n * `openSync(path, 'wx')` is the primitive \u2014 an atomic create-if-absent, so exactly one worker wins even\n * if all of them call it in the same millisecond.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { getCacheRoot } from 'src/lib/constants'\n\nexport const LOCK_FILE_NAME = 'update-check.lock'\n\n/**\n * A lock older than this is assumed to belong to a worker that was killed before it could clean up.\n *\n * Must exceed the worker's ENTIRE critical section, and the install is part of it: the lock is held across\n * `fetch` (\u22642.5s) + the parent wait (\u22645min) + `npm install -g`, which has no bound at all \u2014 a cold cache on\n * a slow link can run for many minutes. The previous 10 minutes was budgeted from the wait and the fetch\n * alone, silently omitting the very operation the lock exists to serialise. A slow enough install therefore\n * had its own LIVE lock reaped as stale by the next worker, which then ran a second concurrent\n * `npm install -g` over the same global directory \u2014 precisely the pile-up described above.\n *\n * The throttle, not this timeout, is now the primary guard: `runUpdateCheck` stamps `lastCheckMs` BEFORE\n * the wait and the install, so concurrent shells stop spawning workers at all. This value only has to\n * outlive a plausible install, and is deliberately generous \u2014 the cost of being too large is that a worker\n * killed mid-install delays the next attempt, which the 24h throttle would delay anyway.\n */\nexport const LOCK_STALE_MS = 30 * 60 * 1000\n\nexport const lockFilePath = (): string => {\n return path.join(getCacheRoot(), LOCK_FILE_NAME)\n}\n\nexport interface LockDeps {\n nowMs?: number\n lockPath?: string\n}\n\n/** Delete a lock whose mtime predates the staleness window. Best-effort: losing the race is harmless. */\nconst reapIfStale = (lockPath: string, nowMs: number): void => {\n try {\n if (nowMs - fs.statSync(lockPath).mtimeMs > LOCK_STALE_MS) fs.rmSync(lockPath, { force: true })\n } catch {\n // Vanished under us \u2014 another worker reaped it. Nothing to do.\n }\n}\n\n/**\n * Take the lock, or return null when another worker already holds it.\n *\n * Returns a release function rather than a boolean so the caller cannot forget which path releases:\n * there is exactly one handle, and it is the only thing that can unlink the file.\n *\n * @example\n * const release = acquireUpdateLock()\n * if (!release) return 'already-running'\n * try { ... } finally { release() }\n */\nexport const acquireUpdateLock = (deps: LockDeps = {}): (() => void) | null => {\n const nowMs = deps.nowMs ?? Date.now()\n const lockPath = deps.lockPath ?? lockFilePath()\n\n try {\n fs.mkdirSync(path.dirname(lockPath), { recursive: true })\n } catch {\n return null\n }\n\n const open = (): number | null => {\n try {\n // 'wx' fails with EEXIST if the file is already there: an atomic test-and-set.\n return fs.openSync(lockPath, 'wx', 0o600)\n } catch {\n return null\n }\n }\n\n let fd = open()\n\n if (fd === null) {\n reapIfStale(lockPath, nowMs)\n // One retry only. If a live worker holds the lock, we are the loser and must simply stand down.\n fd = open()\n }\n\n if (fd === null) return null\n\n try {\n fs.writeFileSync(fd, String(process.pid))\n } catch {\n // The pid is a debugging aid, not part of the protocol; the lock is held either way.\n }\n\n return () => {\n try {\n fs.closeSync(fd)\n } catch {\n // Already closed.\n }\n\n try {\n fs.rmSync(lockPath, { force: true })\n } catch {\n // Already gone; a later worker will reap it via LOCK_STALE_MS regardless.\n }\n }\n}\n", "/**\n * Ask the npm registry for the `latest` dist-tag. Node >= 24 (see `engines`), so global `fetch` is\n * available and this needs no dependency.\n */\nimport { PACKAGE_NAME } from 'src/lib/install-manager'\n\nexport const DEFAULT_REGISTRY = 'https://registry.npmjs.org'\n\n/** Bounded so a hanging registry can never keep a detached child alive indefinitely. */\nexport const FETCH_TIMEOUT_MS = 2_500\n\n/**\n * The registry this install actually talks to. A user behind a corporate mirror has `npm_config_registry`\n * set; hitting registry.npmjs.org directly would either fail closed (firewall) or, worse, report a public\n * version they cannot install.\n *\n * @example\n * registryUrl({ npm_config_registry: 'https://nexus.corp/repo/npm/' }) // => 'https://nexus.corp/repo/npm'\n */\n/**\n * `npm_config_registry` in WHICHEVER case the environment spells it.\n *\n * A bare `env.npm_config_registry` reads only the lowercase form, but npm itself matches `/^npm_config_/i`,\n * and POSIX `process.env` is case-SENSITIVE \u2014 so a `NPM_CONFIG_REGISTRY` (the form Dockerfiles and CI\n * images export) was invisible here while npm honoured it. The check then queried the public registry that\n * the install would never touch: the two halves of this feature were exactly inverted.\n */\nconst configuredRegistry = (env: NodeJS.ProcessEnv): string | undefined => {\n const hit = Object.entries(env).find(([key, value]) => {\n return /^npm_config_registry$/i.test(key) && value != null && value !== ''\n })\n\n return hit?.[1]\n}\n\nexport const registryUrl = (env: NodeJS.ProcessEnv): string => {\n const configured = configuredRegistry(env)\n\n let base = configured != null && configured !== '' ? configured : DEFAULT_REGISTRY\n\n // A `/\\/+$/` regex would do this in one line, but its backtracking is super-linear on a hostile input.\n while (base.endsWith('/')) {\n base = base.slice(0, -1)\n }\n\n return base\n}\n\n/**\n * The published `latest` version, or null on ANY failure (offline, timeout, non-200, malformed body).\n * Never throws: a failed check must be indistinguishable from \"no update available\" to every caller.\n *\n * @example\n * await fetchLatestVersion(process.env) // => '0.1.131' | null\n */\nexport const fetchLatestVersion = async (\n env: NodeJS.ProcessEnv,\n fetchFn: typeof fetch = fetch,\n): Promise<string | null> => {\n const controller = new AbortController()\n const timer = setTimeout(() => {\n controller.abort()\n }, FETCH_TIMEOUT_MS)\n\n try {\n const response = await fetchFn(`${registryUrl(env)}/${PACKAGE_NAME}/latest`, {\n signal: controller.signal,\n headers: { accept: 'application/json' },\n })\n\n if (!response.ok) return null\n\n const body: unknown = await response.json()\n const version = (body as { version?: unknown } | null)?.version\n\n return typeof version === 'string' && version !== '' ? version : null\n } catch {\n return null\n } finally {\n clearTimeout(timer)\n }\n}\n", "/**\n * Registry-safe version comparison for the auto-update check.\n *\n * Deliberately NOT `src/lib/version-utils`: `parseVersion` there does `versionStr.slice(1)` because it\n * only ever sees `v`-prefixed release tags, so it turns a bare registry version (`0.1.130`) into\n * `[NaN, 1, 130]`. Feeding npm's `dist-tags.latest` through it silently compares NaNs and never fires.\n * These inputs are bare semver from `registry.npmjs.org` and from our own `package.json`.\n */\n\n/** `1.2.3-beta.4+build` \u2192 the `[1, 2, 3]` release triple and the `beta.4` prerelease, or null if unparsable. */\ninterface ParsedVersion {\n release: [number, number, number]\n /** Dot-separated prerelease identifiers, empty when this is a final release. */\n prerelease: string[]\n}\n\nconst RELEASE_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/**\n * Parse bare semver. Returns null (never throws, never NaNs) for anything that is not\n * `major.minor.patch` with optional `-prerelease` and `+build` \u2014 a garbled registry body must read as\n * \"no update\", not as \"update to NaN\".\n *\n * @example\n * parseSemver('0.1.130') // => { release: [0, 1, 130], prerelease: [] }\n * parseSemver('1.0.0-rc.1+abc') // => { release: [1, 0, 0], prerelease: ['rc', '1'] }\n * parseSemver('v1.0.0') // => null\n */\nexport const parseSemver = (version: string): ParsedVersion | null => {\n // Build metadata is ignored entirely by semver precedence rules.\n const [withoutBuild = ''] = version.trim().split('+')\n const [core = '', ...prereleaseParts] = withoutBuild.split('-')\n const match = RELEASE_PATTERN.exec(core)\n\n if (!match) return null\n\n const [major, minor, patch] = [match[1], match[2], match[3]].map(Number) as [number, number, number]\n\n return {\n release: [major, minor, patch],\n // Re-join on '-' so `1.0.0-rc-1` keeps its hyphen inside a single identifier.\n prerelease: prereleaseParts.length > 0 ? prereleaseParts.join('-').split('.') : [],\n }\n}\n\nconst NUMERIC_IDENTIFIER = /^\\d+$/\n\n/** Compare two unequal prerelease identifiers per semver \u00A711. Numeric ones rank below alphanumeric ones. */\nconst compareIdentifier = (left: string, right: string): number => {\n const leftNumeric = NUMERIC_IDENTIFIER.test(left)\n const rightNumeric = NUMERIC_IDENTIFIER.test(right)\n\n if (leftNumeric && rightNumeric) return Number(left) - Number(right)\n if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1\n\n return left < right ? -1 : 1\n}\n\n/** Compare prerelease identifier lists. A shorter list has lower precedence: `1.0.0-rc` < `1.0.0-rc.1`. */\nconst comparePrerelease = (a: string[], b: string[]): number => {\n for (let index = 0; index < Math.max(a.length, b.length); index += 1) {\n const left = a[index]\n const right = b[index]\n\n if (left === undefined) return -1\n if (right === undefined) return 1\n if (left !== right) return compareIdentifier(left, right)\n }\n\n return 0\n}\n\n/**\n * Is `latest` strictly newer than `current`? False when either is unparsable, so a bad registry\n * response can never trigger an install.\n *\n * The load-bearing case is NUMERIC, not lexical, comparison: `0.1.9` must be older than `0.1.130`.\n * A string compare would order them the other way and pin every user to the older build forever.\n *\n * A final release outranks its own prereleases (`1.0.0` > `1.0.0-rc.1`), so a user on `rc` is offered\n * the release, and a user on the release is never \"downgraded\" to an rc.\n *\n * @example\n * isNewerVersion('0.1.130', '0.1.9') // => true (numeric, not lexical)\n * isNewerVersion('1.0.0', '1.0.0-rc.1') // => true\n * isNewerVersion('0.1.130', '0.1.130') // => false\n * isNewerVersion('garbage', '0.1.0') // => false\n */\nexport const isNewerVersion = (latest: string, current: string): boolean => {\n const parsedLatest = parseSemver(latest)\n const parsedCurrent = parseSemver(current)\n\n if (!parsedLatest || !parsedCurrent) return false\n\n for (let index = 0; index < 3; index += 1) {\n const left = parsedLatest.release[index] as number\n const right = parsedCurrent.release[index] as number\n\n if (left !== right) return left > right\n }\n\n const latestIsFinal = parsedLatest.prerelease.length === 0\n const currentIsFinal = parsedCurrent.prerelease.length === 0\n\n if (latestIsFinal !== currentIsFinal) return latestIsFinal\n\n return comparePrerelease(parsedLatest.prerelease, parsedCurrent.prerelease) > 0\n}\n", "/**\n * The throttle + notice state for the auto-update check, at `$cacheRoot/update-check.json`.\n *\n * `getCacheRoot()` \u2014 NOT `getSessionCacheDir()`, which throws unless `INFRA_KIT_SESSION` is set. A user\n * who installed this CLI globally and never ran `infra-kit init` has no session, and the update check\n * must still work for exactly that person.\n */\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport { atomicWriteFileSync, getCacheRoot } from 'src/lib/constants'\n\nexport const CACHE_FILE_NAME = 'update-check.json'\n\n/** Refresh at most once a day. A background check is cheap, but not once per shell command. */\nexport const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000\n\nexport interface UpdateCache {\n /**\n * When the last check was ATTEMPTED \u2014 never \"when it last succeeded\". An offline user whose fetch\n * throws must still burn their 24h window, or every single command spawns another doomed child.\n */\n lastCheckMs: number\n /** Latest version seen on the registry, or null when the last attempt failed. */\n latestVersion: string | null\n /**\n * The command the USER must run, set only when the worker was not allowed to install for them\n * (Homebrew, or an install location it could not identify). Null means \"handled, say nothing\".\n *\n * The worker decides this, not the reader: identifying the owning package manager can cost an\n * `npm root -g` subprocess, and the CLI startup path must never pay for one. The background child\n * already pays it, so it writes the verdict down.\n */\n updateCommand: string[] | null\n}\n\nexport const cacheFilePath = (): string => {\n return path.join(getCacheRoot(), CACHE_FILE_NAME)\n}\n\nconst isStringArray = (value: unknown): value is string[] => {\n return (\n Array.isArray(value) &&\n value.every((entry) => {\n return typeof entry === 'string'\n })\n )\n}\n\nconst isUpdateCache = (value: unknown): value is UpdateCache => {\n if (typeof value !== 'object' || value === null) return false\n\n const { lastCheckMs, latestVersion, updateCommand } = value as Partial<UpdateCache>\n\n return (\n typeof lastCheckMs === 'number' &&\n Number.isFinite(lastCheckMs) &&\n (latestVersion === null || typeof latestVersion === 'string') &&\n (updateCommand === null || isStringArray(updateCommand))\n )\n}\n\n/**\n * Read the cache, or null when it is missing/unreadable/corrupt. A null read means \"stale\" to every\n * caller, so a first run and a hand-mangled file behave identically: check again.\n *\n * @example\n * readUpdateCache() // => { lastCheckMs: 1770000000000, latestVersion: '0.1.131' } | null\n */\nexport const readUpdateCache = (\n readFile: (p: string) => string = (p) => {\n return fs.readFileSync(p, 'utf8')\n },\n): UpdateCache | null => {\n try {\n const parsed: unknown = JSON.parse(readFile(cacheFilePath()))\n\n return isUpdateCache(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\n/**\n * Persist the check result. Creates `$cacheRoot` first: `atomicWriteFileSync` writes a temp file\n * beside the target and renames, so it throws ENOENT on a machine that has never had a `~/.cache/infra-kit`.\n * Without this mkdir the write fails, `lastCheckMs` never lands, and the throttle degrades into a\n * detached-child spawn on every invocation.\n *\n * @example\n * writeUpdateCache({ lastCheckMs: Date.now(), latestVersion: '0.1.131' })\n */\nexport const writeUpdateCache = (cache: UpdateCache): void => {\n const root = getCacheRoot()\n\n fs.mkdirSync(root, { recursive: true })\n atomicWriteFileSync(path.join(root, CACHE_FILE_NAME), JSON.stringify(cache), 0o600)\n}\n\n/**\n * Has the throttle window elapsed? A missing cache is stale by definition (first run).\n *\n * A `lastCheckMs` in the future (clock skew, or a restored backup) also reads as stale rather than\n * locking the user out of updates until their clock catches up.\n *\n * @example\n * isStale(null, 1_000) // => true\n * isStale({ lastCheckMs: 0, latestVersion: null }, CHECK_INTERVAL_MS + 1) // => true\n */\nexport const isStale = (cache: UpdateCache | null, nowMs: number): boolean => {\n if (!cache) return true\n\n const elapsed = nowMs - cache.lastCheckMs\n\n return elapsed >= CHECK_INTERVAL_MS || elapsed < 0\n}\n"],
5
- "mappings": "uFAQA,OAAOA,MAAU,YAGV,IAAMC,EAAe,YAEtBC,EAAS,GAAGD,CAAY,UAoCxBE,EAAW,CAACC,EAAgBC,EAAeC,IAAkC,CACjF,IAAMC,EAAMP,EAAK,SAASM,EAASN,EAAK,QAAQI,CAAM,CAAC,EAAGJ,EAAK,QAAQK,CAAK,CAAC,EAE7E,OAAOE,IAAQ,IAAM,CAACA,EAAI,WAAW,IAAI,GAAK,CAACP,EAAK,WAAWO,CAAG,CACpE,EAGMC,EAAa,CAACC,EAAWC,IACtBV,EAAK,QAAQS,CAAC,EAAE,MAAMT,EAAK,GAAG,EAAE,SAASU,CAAI,EAkBhDC,EAAc,CAACF,EAAWC,IAA0B,CACxD,IAAME,EAAWZ,EAAK,QAAQS,CAAC,EAAE,MAAMT,EAAK,GAAG,EACzCa,EAASD,EAAS,QAAQ,QAAQ,EAExC,OAAOC,IAAW,IAAMD,EAASC,EAAS,CAAC,IAAMH,CACnD,EAGMI,EAAc,CAACC,EAAwBC,EAAaC,EAAsBX,IAAkC,CAChH,IAAMY,EAAMH,EAAIC,CAAG,EAEnB,OAAOE,GAAO,MAAQA,IAAQ,IAAMf,EAASe,EAAKD,EAAcX,CAAQ,CAC1E,EAWMa,EAAsB,CAC1B,CACE,QAAS,QAET,KAAM,CAAC,CAAE,aAAAF,EAAc,IAAAF,EAAK,SAAAT,CAAS,IAEjCQ,EAAYC,EAAK,aAAcE,EAAcX,CAAQ,GACrDE,EAAWS,EAAc,QAAQ,GACjCT,EAAWS,EAAc,OAAO,EAGpC,cAAe,CAAC,QAAS,UAAWhB,CAAY,EAChD,aAAc,EAChB,EACA,CACE,QAAS,WAaT,KAAM,CAAC,CAA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,CAAC,EAgB7F,IAAMS,EAASX,EAAMQ,EAAc,CAAC,EAAaA,EAAc,MAAM,CAAC,EAAG,CACvE,MAAO,SACP,MAAOhC,EAAQ,WAAa,QAC5B,IAAKoC,GAAQ,EACb,IAAKC,EAAyBxB,CAAG,EACjC,YAAa,EACf,CAAC,EAID,OAAIsB,EAAO,OAASA,EAAO,QAAUA,EAAO,SAAW,EAC9CR,EAAO,iBAAkB,CAAE,cAAAD,EAAe,cAAAM,CAAc,CAAC,EAI3DL,EAAO,YAAa,CAAE,cAAe,KAAM,cAAe,IAAK,CAAC,CACzE",
6
- "names": ["path", "PACKAGE_NAME", "LATEST", "isWithin", "parent", "child", "realpath", "rel", "hasSegment", "p", "name", "isBrewKegOf", "segments", "cellar", "underEnvDir", "env", "key", "selfRealPath", "dir", "MATCHERS", "NPM_UPDATE_COMMAND", "detectInstallManager", "input", "lazyNpmRoot", "hit", "test", "npmRoot", "isLocalNodeModulesInstall", "cwd", "realpathSync", "path", "safeRealpath", "dir", "execFileSync", "process", "NPM_ROOT_TIMEOUT_MS", "defaultLazyNpmRoot", "trimmed", "spawnSync", "homedir", "process", "fs", "path", "process", "LOCK_FILE_NAME", "LOCK_STALE_MS", "lockFilePath", "path", "getCacheRoot", "reapIfStale", "lockPath", "nowMs", "fs", "acquireUpdateLock", "deps", "open", "fd", "process", "DEFAULT_REGISTRY", "FETCH_TIMEOUT_MS", "configuredRegistry", "env", "key", "value", "registryUrl", "configured", "base", "fetchLatestVersion", "fetchFn", "controller", "timer", "response", "PACKAGE_NAME", "version", "RELEASE_PATTERN", "parseSemver", "version", "withoutBuild", "core", "prereleaseParts", "match", "major", "minor", "patch", "NUMERIC_IDENTIFIER", "compareIdentifier", "left", "right", "leftNumeric", "rightNumeric", "comparePrerelease", "a", "b", "index", "isNewerVersion", "latest", "current", "parsedLatest", "parsedCurrent", "latestIsFinal", "currentIsFinal", "fs", "path", "CACHE_FILE_NAME", "CHECK_INTERVAL_MS", "cacheFilePath", "path", "getCacheRoot", "isStringArray", "value", "entry", "isUpdateCache", "lastCheckMs", "latestVersion", "updateCommand", "readUpdateCache", "readFile", "p", "fs", "parsed", "writeUpdateCache", "cache", "root", "atomicWriteFileSync", "isStale", "nowMs", "elapsed", "PARENT_POLL_INTERVAL_MS", "PARENT_WAIT_TIMEOUT_MS", "defaultIsProcessAlive", "pid", "process", "defaultSleep", "ms", "resolve", "waitForParentExit", "parentPid", "deps", "deadline", "runUpdateCheck", "currentVersion", "release", "acquireUpdateLock", "runUpdateCheckLocked", "env", "nowMs", "fetchLatest", "fetchLatestVersion", "writeCache", "writeUpdateCache", "isProcessAlive", "sleep", "clock", "lazyNpmRoot", "defaultLazyNpmRoot", "spawn", "spawnSync", "latestVersion", "finish", "outcome", "cache", "isNewerVersion", "canSelfSpawn", "updateCommand", "detectInstallManager", "safeRealpath", "result", "homedir", "packageManagerInstallEnv"]
7
- }