infra-kit 0.1.134 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{boot-YCABHUPP.js → boot-MTVHM4N7.js} +2 -2
- package/dist/{chunk-TFHVQOVF.js → chunk-4MRYIYJP.js} +2 -2
- package/dist/chunk-E2NWNNC6.js +2 -0
- package/dist/chunk-E2NWNNC6.js.map +7 -0
- package/dist/{chunk-3OMHS5RE.js → chunk-E2SEBLGJ.js} +2 -2
- package/dist/chunk-KZP2SY37.js +4 -0
- package/dist/chunk-KZP2SY37.js.map +7 -0
- package/dist/{chunk-27PDA2PN.js → chunk-NC2TIQ3M.js} +2 -2
- package/dist/chunk-RLZ5IB2E.js +238 -0
- package/dist/chunk-RLZ5IB2E.js.map +7 -0
- package/dist/chunk-TI33V5G2.js +6 -0
- package/dist/chunk-TI33V5G2.js.map +7 -0
- package/dist/{chunk-FAR2L74S.js → chunk-TPVXMJ7N.js} +1 -1
- package/dist/cli.js +10 -8
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +23 -20
- package/dist/dev-server.js.map +4 -4
- package/dist/dev-wizard-run-5HQOGE3R.js +2 -0
- package/dist/dev-wizard-run-5HQOGE3R.js.map +7 -0
- package/dist/mcp.js +1 -1
- package/dist/mcp.js.map +3 -3
- package/dist/persistent-ink-dev-ui-KOI44ZVT.js +2 -0
- package/dist/persistent-ink-dev-ui-KOI44ZVT.js.map +7 -0
- package/dist/safe-stderr-HXDR2DNJ.js +2 -0
- package/dist/update-check.js +1 -1
- package/package.json +3 -14
- package/dist/chunk-2YHPK2VY.js +0 -221
- package/dist/chunk-2YHPK2VY.js.map +0 -7
- package/dist/chunk-3F7XYJWY.js +0 -3
- package/dist/chunk-3F7XYJWY.js.map +0 -7
- package/dist/chunk-DOG3OPNW.js +0 -2
- package/dist/chunk-DOG3OPNW.js.map +0 -7
- package/dist/chunk-JD5T4VCB.js +0 -6
- package/dist/chunk-JD5T4VCB.js.map +0 -7
- package/dist/chunk-LTKR3F4N.js +0 -2
- package/dist/chunk-LTKR3F4N.js.map +0 -7
- package/dist/chunk-TUVUKM4K.js +0 -2
- package/dist/chunk-TUVUKM4K.js.map +0 -7
- package/dist/chunk-Z6KTUVIC.js +0 -2
- package/dist/chunk-Z6KTUVIC.js.map +0 -7
- package/dist/dev-wizard-run-HGQO6FZV.js +0 -2
- package/dist/dev-wizard-run-HGQO6FZV.js.map +0 -7
- package/dist/entry/index.d.ts +0 -4
- package/dist/entry/vite.d.ts +0 -2
- package/dist/index.js +0 -2
- package/dist/lib/package-config/package-config-schema.d.ts +0 -35
- package/dist/lib/package-config/package-config.d.ts +0 -99
- package/dist/lib/release-slug/release-slug.d.ts +0 -43
- package/dist/lib/vendor/config-schema.d.ts +0 -58
- package/dist/lib/vite/vite.d.ts +0 -168
- package/dist/persistent-ink-dev-ui-FUJQDFNY.js +0 -8
- package/dist/persistent-ink-dev-ui-FUJQDFNY.js.map +0 -7
- package/dist/vite.js +0 -2
- package/dist/vite.js.map +0 -7
- /package/dist/{boot-YCABHUPP.js.map → boot-MTVHM4N7.js.map} +0 -0
- /package/dist/{chunk-TFHVQOVF.js.map → chunk-4MRYIYJP.js.map} +0 -0
- /package/dist/{chunk-3OMHS5RE.js.map → chunk-E2SEBLGJ.js.map} +0 -0
- /package/dist/{chunk-27PDA2PN.js.map → chunk-NC2TIQ3M.js.map} +0 -0
- /package/dist/{chunk-FAR2L74S.js.map → chunk-TPVXMJ7N.js.map} +0 -0
- /package/dist/{index.js.map → safe-stderr-HXDR2DNJ.js.map} +0 -0
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import p from"node:process";var d=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],f=80,s={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",teal:"\x1B[36m",green:"\x1B[32m",blue:"\x1B[34m",red:"\x1B[31m"},h="\r\x1B[2K",m=/\x1B\[[0-9;]*m|\x1B\]8;;.*?\x1B\\/g,$=n=>n.replace(m,""),l=n=>String(n).padStart(2,"0"),v=n=>`${l(n.getHours())}:${l(n.getMinutes())}:${l(n.getSeconds())}`,x=n=>`${(n/1e3).toFixed(1)}s`,u=n=>{let t=Math.max(0,Math.floor(n/1e3)),e=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return e>0?`${e}h${l(r)}m`:r>0?`${r}m${l(i)}s`:`${i}s`},R=n=>`https://${n.alias}${n.prefixUrl}`,g=class{deps;spinnerTimer=null;spinnerPhase="";spinnerFrame=0;constructor(t={}){this.deps={write:t.write??(e=>{p.stdout.write(e)}),appendLog:t.appendLog??(()=>{}),isTTY:t.isTTY??!!p.stdout.isTTY,now:t.now??(()=>new Date),verbose:t.verbose??!1}}color(t,e){return this.deps.isTTY?`${t}${e}${s.reset}`:e}hyperlink(t,e){return!this.deps.isTTY||t===""?e:`\x1B]8;;file://${encodeURI(t).replace(/[#?]/g,i=>`%${i.charCodeAt(0).toString(16).toUpperCase()}`)}\x1B\\${e}\x1B]8;;\x1B\\`}teeOnly(t,e){this.deps.appendLog(`[${this.deps.now().toISOString()}] [${e.toUpperCase()}] ${$(t)}
|
|
2
|
+
`)}tee(t,e){this.teeOnly(t,e)}dispose(){}emit(t){if(this.spinnerTimer!=null&&this.deps.isTTY){this.deps.write(`${h}${t}
|
|
3
|
+
`),this.paintSpinner();return}this.deps.write(`${t}
|
|
4
|
+
`)}log(t,e="info"){(e!=="debug"||this.deps.verbose)&&this.emit(t),this.tee(t,e)}narrate(t){this.deps.verbose&&this.emit(t),this.tee(t,"info")}logFn=(t,e="info")=>{this.log(t,e)};paintSpinner(){let t=d[this.spinnerFrame%d.length];this.deps.write(`${h}${this.color(s.teal,t)} ${this.color(s.dim,this.spinnerPhase)}`)}bootStep(t){if(this.tee(t,"info"),this.spinnerPhase=t,!this.deps.isTTY){this.deps.write(`${t}
|
|
5
|
+
`);return}this.spinnerTimer==null&&(this.spinnerTimer=setInterval(()=>{this.spinnerFrame+=1,this.paintSpinner()},f),this.spinnerTimer.unref?.()),this.paintSpinner()}stopSpinner(){this.spinnerTimer!=null&&(clearInterval(this.spinnerTimer),this.spinnerTimer=null),this.deps.isTTY&&this.deps.write(h)}errorCount(t){let e=`\u26A0 ${t}`;return t>0?this.color(s.red,e):this.color(s.dim,e)}healthDot(t){return t===null?"":t?this.color(s.green,"\u25CF ok"):this.color(s.red,"\u25CF down")}ready(t){this.stopSpinner();let e=this.formatReadyLines(t);for(let r of e)this.emit(r),this.tee(r,"info")}tagWidth(t){return[...t.endpoints.map(r=>r.tag),...t.uiRefs.map(r=>r.tag),...(t.failed??[]).map(r=>r.tag)].reduce((r,i)=>Math.max(r,i.length),0)}titleLine(t){let e=[t.target,t.watch?"watch":null,t.release].filter(a=>!!a).join(" \xB7 "),r=t.failed?.length??0,i=x(t.elapsedMs),o=r>0?this.color(s.red,`${r} failed \xB7 started in ${i}`):this.color(s.green,`ready in ${i}`);return` ${this.color(s.bold,"infra-kit dev")} ${this.color(s.dim,e)} ${o}`}legendLines(t){let e=t.watch&&t.watchSummary?`watching ${t.watchSummary}`:"watch off",r=this.hyperlink(t.logHref,t.logPath),i=`${e} logs \u2192 ${r}`,o="\u2500".repeat(60);return[` ${this.color(s.dim,i)}`,` ${this.color(s.dim,o)}`]}uiRefLine(t,e,r){let i=r==null?"":` ${this.errorCount(r)}`;return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.dim,"no managed port (vite prints its own URL)")}${i}`}statusFields(t){let e=[];return t.uptimeMs!=null&&e.push(this.color(s.dim,`up ${u(t.uptimeMs)}`)),t.rpm!=null&&t.rpm>0&&e.push(this.color(s.dim,`${t.rpm}/min`)),t.restarts!=null&&t.restarts>0&&e.push(this.color(s.dim,`\u21BA${t.restarts}`)),t.errors!=null&&e.push(this.errorCount(t.errors)),e.join(" ")}endpointLine(t,e,r){let i=r?this.healthDot(t.healthy):"",o=this.statusFields(t),a=[i,o].filter(Boolean).join(" ");return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.blue,t.url)}${a?` ${a}`:""}`}failedLine(t,e){return` ${this.color(s.teal,t.tag.padEnd(e))} ${this.color(s.red,"\u25CF failed")} ${this.color(s.dim,t.reason)}`}formatLines(t,{withHealthDot:e}){let r=this.tagWidth(t),i=["",this.titleLine(t),""];for(let o of t.endpoints)i.push(this.endpointLine(o,r,e));for(let o of t.failed??[])i.push(this.failedLine(o,r));for(let o of t.uiRefs)i.push(this.uiRefLine(o,r,o.errors));return i.push("",...this.legendLines(t)),i}formatHeaderLines(t){return this.formatLines(t,{withHealthDot:!1})}formatFooterLines(t){let e=this.tagWidth(t),r=t.endpoints.map(i=>{let o=this.healthDot(i.healthy),a=this.statusFields(i),c=[o,a].filter(Boolean).join(" ");return` ${this.color(s.teal,i.tag.padEnd(e))} ${c}`});for(let i of t.uiRefs)i.errors!=null&&r.push(` ${this.color(s.teal,i.tag.padEnd(e))} ${this.errorCount(i.errors)}`);if(t.sessionUptimeMs!=null){let i=`up ${u(t.sessionUptimeMs)}`;r.push(` ${this.color(s.dim,i)}`)}return r}formatReadyLines(t){return this.formatLines(t,{withHealthDot:!0})}event(t){let e=v(this.deps.now()),r=` ${this.color(s.dim,e)} ${this.color(s.teal,t.tag)} ${t.text}`;this.emit(r),this.tee(`${t.tag} ${t.text}`,"info")}};export{v as a,R as b,g as c};
|
|
6
|
+
//# sourceMappingURL=chunk-TI33V5G2.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/dev/render.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Terminal renderer for `infra-kit dev` \u2014 a calm-print layer (never a full-screen TUI).\n *\n * The boot collapses into a single transient spinner; the final screen is a STATUS PANEL, one row per\n * server, carrying health, uptime, requests/min, restarts and an error count. There is no log tail:\n * every line \u2014 framework output, request logs, a handler's own `console.log` \u2014 is written to that\n * service's file under `<cacheRoot>/<session>/dev/<pid>/` and never printed. What still appears above\n * the panel is only what the RUNNER says: a restart, an unhealthy app, a dead engine.\n *\n * The panel's live fields are the reason it is a status surface and not a screenshot. With nothing\n * scrolling beside it, a panel whose numbers never move cannot be told apart from a hung process.\n *\n * All I/O is injected (`write` / `appendLog` / `isTTY` / `now`) so every frame is snapshot-testable and\n * the spinner is deterministically disabled in tests (`isTTY: false`).\n */\nimport process from 'node:process'\n\nimport type { DevUi } from './dev-ui.js'\n\nexport type LogLevel = 'info' | 'warn' | 'error' | 'debug'\n\n/** Injected I/O seams. Defaults wire to the real stdout + a caller-provided file appender. */\nexport interface DevRendererDeps {\n /** Terminal sink (default: `process.stdout.write`). */\n write: (text: string) => void\n /** File tee \u2014 always receives full detail (default: no-op; the runner passes its log appender). */\n appendLog: (text: string) => void\n /** Whether the terminal is a TTY. Gates the spinner + ANSI color; false in CI / when piped. */\n isTTY: boolean\n /** Clock seam (default: `() => new Date()`), so timestamps + `ready in Xs` are testable. */\n now: () => Date\n /** When true, boot narration reaches the terminal; otherwise it is file-only. */\n verbose: boolean\n}\n\n/**\n * One server's row on the status panel.\n *\n * The live fields below are what make the panel a STATUS surface rather than a screenshot. The terminal\n * no longer carries a log tail, so a static row would leave \"quiet\" indistinguishable from \"hung\" \u2014 the\n * moving numbers are the liveness tell, and they are not decoration.\n */\nexport interface EndpointRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** The app's `.localhost` alias URL \u2014 the only form, since an app that cannot be aliased never starts. */\n url: string\n /** Liveness: `true` \u2192 `\u25CF ok`, `false` \u2192 `\u25CF down`, `null` \u2192 no dot (not probed). */\n healthy: boolean | null\n /** Milliseconds since this server last (re)started. Omitted on the boot frame. */\n uptimeMs?: number\n /** Watch-triggered restarts so far this session. */\n restarts?: number\n /** Requests served in the last 60s. */\n rpm?: number\n /**\n * Errors this service has declared since boot \u2014 a 5xx, a `console.error`, a framework failure line.\n * This is the ONLY error signal the user gets now that nothing prints, so a row that cannot count is\n * a row that lies. A COUNT, never a classification: it is incremented from the level the emitter\n * declared, never from anything read out of the line's text.\n */\n errors?: number\n}\n\n/**\n * A UI app whose URL the runner does not own, so it streams its own below \u2014 referenced, never given a\n * (fabricated) endpoint row. The fallback case only: a UI whose port the runner pre-assigned is an\n * {@link EndpointRow}, proxy or no proxy.\n */\nexport interface UiRef {\n /** Stream tag, e.g. `client/ui`. */\n tag: string\n /**\n * Errors this UI has declared since boot. Present for the same reason an {@link EndpointRow} has one:\n * with nothing printing, a row that cannot count is a row that lies \u2014 and this row belongs to the app\n * whose vite config never wired `infraKitDev()`, i.e. the one most likely to be misconfigured.\n */\n errors?: number\n}\n\n/**\n * An app that was asked for but never came up. It has no URL and no health \u2014 but it MUST still get a\n * row: the header is a report of what the user asked for, and an app that silently vanishes from it\n * reads as \"not requested\" rather than \"broken\".\n */\nexport interface FailedRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** One-line reason, e.g. `config is missing field: 'connectionURL'`. */\n reason: string\n}\n\n/** Everything {@link DevRenderer.ready} needs to paint the final header in one shot. */\nexport interface ReadySummary {\n /** Resolved preset / target label (e.g. `client`, `*`). */\n target: string\n watch: boolean\n /** Slugified release for the header meta; omitted outside a git repo. */\n release?: string\n /** Backend readiness time in ms (UI is fire-and-forget, so this is BE-only \u2014 labeled honestly). */\n elapsedMs: number\n /** Real backend endpoint rows (owned ports + pre-probed health). */\n endpoints: EndpointRow[]\n /** UI apps that print their own URL below. */\n uiRefs: UiRef[]\n /**\n * Apps that failed to start. Optional only so the (many) existing summaries need not restate an\n * empty list; a non-empty one downgrades the title from a green `ready` to an honest `N failed`.\n */\n failed?: FailedRow[]\n /** Human watch summary, e.g. `1 app \u00B7 5 packages`; omitted when not watching. */\n watchSummary?: string\n /**\n * Compact, human-readable log path shown as the `logs \u2192 \u2026` label. A DIRECTORY, not a file\n * (e.g. `~/.cache/infra-kit/<session>/dev/<pid>`): there is one log per service, so a single path\n * would have to pick a favourite.\n */\n logPath: string\n /** Absolute log path backing the clickable OSC-8 hyperlink (wrapped as `file://<logHref>`). */\n logHref: string\n /**\n * Milliseconds since the session became ready \u2014 the panel's HEARTBEAT.\n *\n * Every other live field belongs to a backend: uptime, req/min, restarts. A UI-only session has no\n * backend, so its rows have nothing that moves \u2014 and Ink does not repaint an identical frame, so the\n * screen would sit perfectly still while the session ran. With no log tail left to prove otherwise,\n * a motionless panel is indistinguishable from a hung process. This is the one field that ticks for\n * EVERY session shape. Omitted on the boot frame, where nothing has elapsed yet.\n */\n sessionUptimeMs?: number\n}\n\nconst SPINNER_FRAMES = ['\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F']\nconst SPINNER_INTERVAL_MS = 80\n\nconst ANSI = {\n reset: '\\x1B[0m',\n dim: '\\x1B[2m',\n bold: '\\x1B[1m',\n teal: '\\x1B[36m',\n green: '\\x1B[32m',\n blue: '\\x1B[34m',\n red: '\\x1B[31m',\n} as const\n\n/** Erase the current line and return the cursor to column 0 (used to clear the spinner). */\nconst CLEAR_LINE = '\\r\\x1B[2K'\n\n/**\n * SGR color codes (`ESC [ \u2026 m`) and OSC-8 hyperlink wrappers (`ESC ] 8 ; ; \u2026 ESC \\`), non-greedy.\n * Matching the ESC control character is the whole point here \u2014 this pattern exists to remove it.\n */\n// eslint-disable-next-line sonarjs/no-control-regex, no-control-regex\nconst ANSI_PATTERN = /\\x1B\\[[0-9;]*m|\\x1B\\]8;;.*?\\x1B\\\\/g\n\n/**\n * Strip SGR colors + OSC-8 hyperlink escapes, keeping the hyperlink's visible label. Applied at the\n * file-tee seam so `logs.txt` stays greppable plain text even though the terminal frames it renders\n * from are colored + hyperlinked (both renderers format once, for a TTY, and tee the same string).\n */\nexport const stripAnsi = (s: string): string => {\n return s.replace(ANSI_PATTERN, '')\n}\n\n/** Zero-pad to 2 digits for `HH:MM:SS`. */\nconst pad2 = (n: number): string => {\n return String(n).padStart(2, '0')\n}\n\n/** `HH:MM:SS` for a tail timestamp. */\nexport const formatClock = (d: Date): string => {\n return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`\n}\n\n/** `2.4s` for the `ready in \u2026` header. */\nexport const formatElapsed = (ms: number): string => {\n return `${(ms / 1000).toFixed(1)}s`\n}\n\n/**\n * `47s` / `4m12s` / `2h03m` \u2014 the panel's liveness tell.\n *\n * With no log tail on screen, a panel whose numbers never move is indistinguishable from a hung\n * process. This is the field that proves the session is alive even when nothing is happening, so it is\n * always rendered and always advancing.\n */\nexport const formatUptime = (ms: number): string => {\n const total = Math.max(0, Math.floor(ms / 1000))\n const hours = Math.floor(total / 3600)\n const minutes = Math.floor((total % 3600) / 60)\n const seconds = total % 60\n\n if (hours > 0) return `${hours}h${pad2(minutes)}m`\n if (minutes > 0) return `${minutes}m${pad2(seconds)}s`\n\n return `${seconds}s`\n}\n\n/**\n * Resolve the endpoint URL for an app: `https://<alias><prefix>`, where `alias` is the portless hostname\n * the runner registered (e.g. `feat-x.backend-api.localhost`). The runner refuses to start an app it could\n * not alias, so there is no port-form to fall back to.\n *\n * There is no port and no scheme choice, by construction. The proxy serves TLS on 443 \u2014 the implicit HTTPS\n * port \u2014 so the URL is byte-identical to the `dev.proxy` local template that `infra-kit/vite` proxies to,\n * and what the table prints cannot drift from what the frontend calls. Any port suffix here would mean the\n * proxy is not on 443, which `ensureProxy` has already refused to start.\n */\nexport const resolveEndpointUrl = (input: { prefixUrl: string; alias: string }): string => {\n return `https://${input.alias}${input.prefixUrl}`\n}\n\nexport class DevRenderer implements DevUi {\n private readonly deps: DevRendererDeps\n private spinnerTimer: ReturnType<typeof setInterval> | null = null\n private spinnerPhase = ''\n private spinnerFrame = 0\n\n constructor(deps: Partial<DevRendererDeps> = {}) {\n this.deps = {\n write:\n deps.write ??\n ((text: string): void => {\n process.stdout.write(text)\n }),\n appendLog: deps.appendLog ?? ((): void => {}),\n isTTY: deps.isTTY ?? Boolean(process.stdout.isTTY),\n now:\n deps.now ??\n ((): Date => {\n return new Date()\n }),\n verbose: deps.verbose ?? false,\n }\n }\n\n /** Wrap `s` in an ANSI color on a TTY; return it untouched when piped (deterministic snapshots). */\n private color(code: string, s: string): string {\n return this.deps.isTTY ? `${code}${s}${ANSI.reset}` : s\n }\n\n /**\n * Wrap `label` in an OSC-8 terminal hyperlink to `href` (a filesystem path \u2192 `file://` URI) so the\n * log path is cmd/ctrl-clickable. Returns the bare `label` when piped (deterministic snapshots) or\n * when `href` is empty \u2014 terminals without OSC-8 support silently ignore the escapes anyway.\n */\n private hyperlink(href: string, label: string): string {\n if (!this.deps.isTTY || href === '') return label\n\n // `encodeURI` escapes spaces / non-ASCII but leaves `#` and `?`, which a file URI reads as a\n // fragment / query \u2014 encode those too so a path containing them still resolves to the real file.\n const uri = encodeURI(href).replace(/[#?]/g, (c) => {\n return `%${c.charCodeAt(0).toString(16).toUpperCase()}`\n })\n\n return `\\x1B]8;;file://${uri}\\x1B\\\\${label}\\x1B]8;;\\x1B\\\\`\n }\n\n /**\n * Append one line to the log file ONLY \u2014 the canonical `[iso] [LEVEL] msg` shape, no terminal write.\n * The single source of the file-tee format: the private {@link tee} and the Ink boot UI both route\n * here, so the log file stays identical whichever renderer is live.\n */\n teeOnly(message: string, level: LogLevel): void {\n this.deps.appendLog(`[${this.deps.now().toISOString()}] [${level.toUpperCase()}] ${stripAnsi(message)}\\n`)\n }\n\n /** File tee for a line that is ALSO written to the terminal; delegates the format to {@link teeOnly}. */\n private tee(message: string, level: LogLevel): void {\n this.teeOnly(message, level)\n }\n\n /**\n * No-op for the plain renderer: it owns no Ink / raw-mode terminal state to release. Present to\n * satisfy {@link DevUi} so the runner can call `dispose()` uniformly. Idempotent by construction.\n */\n dispose(): void {\n // Nothing to release \u2014 the plain renderer never seizes the terminal.\n }\n\n /**\n * Write one terminal line spinner-safely: if the spinner is live on a TTY, erase it, print the\n * line, then repaint the spinner, so a mid-boot message never shreds the `\\r`-based spinner.\n */\n private emit(line: string): void {\n if (this.spinnerTimer != null && this.deps.isTTY) {\n this.deps.write(`${CLEAR_LINE}${line}\\n`)\n this.paintSpinner()\n\n return\n }\n\n this.deps.write(`${line}\\n`)\n }\n\n /** A general message routed by level (terminal + file tee). Debug is terminal-only in verbose. */\n log(message: string, level: LogLevel = 'info'): void {\n if (level !== 'debug' || this.deps.verbose) {\n this.emit(message)\n }\n this.tee(message, level)\n }\n\n /** A boot-narration step: terminal only when `--verbose`, but always tee'd to the log. */\n narrate(message: string): void {\n if (this.deps.verbose) {\n this.emit(message)\n }\n this.tee(message, 'info')\n }\n\n /** `LogFn`-shaped adapter for the build runner seam (which passes `(msg, level)`). */\n readonly logFn = (message: string, level: LogLevel = 'info'): void => {\n this.log(message, level)\n }\n\n // ---- boot spinner -------------------------------------------------------\n\n /** Paint the current spinner frame in place (TTY only). */\n private paintSpinner(): void {\n const frame = SPINNER_FRAMES[this.spinnerFrame % SPINNER_FRAMES.length]!\n\n this.deps.write(`${CLEAR_LINE}${this.color(ANSI.teal, frame)} ${this.color(ANSI.dim, this.spinnerPhase)}`)\n }\n\n /**\n * Update the boot phase. On a TTY this drives a single transient spinner line; when piped it\n * prints one plain phase line (no ANSI, deterministic). Always tee'd to the log.\n */\n bootStep(phase: string): void {\n this.tee(phase, 'info')\n this.spinnerPhase = phase\n\n if (!this.deps.isTTY) {\n this.deps.write(`${phase}\\n`)\n\n return\n }\n\n if (this.spinnerTimer == null) {\n this.spinnerTimer = setInterval(() => {\n this.spinnerFrame += 1\n this.paintSpinner()\n }, SPINNER_INTERVAL_MS)\n // Never keep the event loop alive for the spinner alone.\n this.spinnerTimer.unref?.()\n }\n this.paintSpinner()\n }\n\n /** Stop + erase the spinner line (idempotent). Called before the ready header prints. */\n stopSpinner(): void {\n if (this.spinnerTimer != null) {\n clearInterval(this.spinnerTimer)\n this.spinnerTimer = null\n }\n if (this.deps.isTTY) {\n this.deps.write(CLEAR_LINE)\n }\n }\n\n // ---- the ready header ---------------------------------------------------\n\n /**\n * The error counter, shared by endpoint rows and UI reference rows.\n *\n * Zero is rendered, not omitted: with nothing else printing, this is the only failure signal on the\n * screen, so a dim `\u26A0 0` is a claim worth making. It turns red the moment it stops being zero.\n */\n private errorCount(errors: number): string {\n const text = `\u26A0 ${errors}`\n\n return errors > 0 ? this.color(ANSI.red, text) : this.color(ANSI.dim, text)\n }\n\n /** Format the health dot for an endpoint row (`\u25CF ok` / `\u25CF down` / '' when unprobed). */\n private healthDot(healthy: boolean | null): string {\n if (healthy === null) return ''\n if (healthy) return this.color(ANSI.green, '\u25CF ok')\n\n return this.color(ANSI.red, '\u25CF down')\n }\n\n /**\n * Collapse the boot and print the final header in one shot: title line, one endpoint row per\n * backend server (with health dot), a reference line per UI app, the watch line, the clickable\n * log path, and a separator rule. Synchronous \u2014 health is pre-probed by the caller.\n */\n ready(summary: ReadySummary): void {\n this.stopSpinner()\n\n const lines = this.formatReadyLines(summary)\n\n for (const line of lines) {\n this.emit(line)\n this.tee(line, 'info')\n }\n }\n\n /** Column width for the aligned `tag` gutter \u2014 the widest endpoint/UI/failed tag. */\n private tagWidth(summary: ReadySummary): number {\n const tags = [\n ...summary.endpoints.map((e) => {\n return e.tag\n }),\n ...summary.uiRefs.map((u) => {\n return u.tag\n }),\n ...(summary.failed ?? []).map((f) => {\n return f.tag\n }),\n ]\n\n return tags.reduce((w, t) => {\n return Math.max(w, t.length)\n }, 0)\n }\n\n /**\n * The `infra-kit dev \u00B7 <meta> ready in Xs` title line.\n *\n * A green `ready` is a claim about the whole session, so it is spent only when the whole session\n * is up. With anything in `failed` the status turns red and counts the casualties instead \u2014 the\n * boot time alone, next to a green word, is exactly how a half-dead session used to pass for a\n * healthy one.\n */\n private titleLine(summary: ReadySummary): string {\n const meta = [summary.target, summary.watch ? 'watch' : null, summary.release]\n .filter((s): s is string => {\n return Boolean(s)\n })\n .join(' \u00B7 ')\n\n const failedCount = summary.failed?.length ?? 0\n const elapsed = formatElapsed(summary.elapsedMs)\n const status =\n failedCount > 0\n ? this.color(ANSI.red, `${failedCount} failed \u00B7 started in ${elapsed}`)\n : this.color(ANSI.green, `ready in ${elapsed}`)\n\n return ` ${this.color(ANSI.bold, 'infra-kit dev')} ${this.color(ANSI.dim, meta)} ${status}`\n }\n\n /** The static legend tail: watch line + clickable log path, then a separator rule. */\n private legendLines(summary: ReadySummary): string[] {\n const watchText = summary.watch && summary.watchSummary ? `watching ${summary.watchSummary}` : 'watch off'\n const logLink = this.hyperlink(summary.logHref, summary.logPath)\n const watchLine = `${watchText} logs \u2192 ${logLink}`\n const rule = '\u2500'.repeat(60)\n\n return [` ${this.color(ANSI.dim, watchLine)}`, ` ${this.color(ANSI.dim, rule)}`]\n }\n\n /**\n * A UI reference row \u2014 used when infra-kit could not claim the UI's port, so it has no URL to print.\n *\n * It STILL carries an error count. That is the whole point: this row is exactly the misconfigured app\n * (its vite config never wired `infraKitDev()`), which is the app most likely to be broken \u2014 and with\n * no log tail on screen, a row with no error field is a row that cannot report the breakage. It used\n * to be a bare reference line, so its errors were counted into a file nobody had a reason to open.\n */\n private uiRefLine(ref: UiRef, tagWidth: number, errors: number | undefined): string {\n const errText = errors == null ? '' : ` ${this.errorCount(errors)}`\n\n return ` ${this.color(ANSI.teal, ref.tag.padEnd(tagWidth))} ${this.color(\n ANSI.dim,\n 'no managed port (vite prints its own URL)',\n )}${errText}`\n }\n\n /**\n * The live half of an endpoint row: `up 4m12s 18/min \u21BA2 \u26A0 3`.\n *\n * Empty on the boot frame (no field is set yet). Each field is omitted individually when absent \u2014 a\n * server with no restarts should not have to say so.\n */\n private statusFields(endpoint: ReadySummary['endpoints'][number]): string {\n const parts: string[] = []\n\n if (endpoint.uptimeMs != null) parts.push(this.color(ANSI.dim, `up ${formatUptime(endpoint.uptimeMs)}`))\n if (endpoint.rpm != null && endpoint.rpm > 0) parts.push(this.color(ANSI.dim, `${endpoint.rpm}/min`))\n if (endpoint.restarts != null && endpoint.restarts > 0) parts.push(this.color(ANSI.dim, `\u21BA${endpoint.restarts}`))\n // Errors are the exception to \"omit when zero\" \u2014 see {@link errorCount}.\n if (endpoint.errors != null) {\n parts.push(this.errorCount(endpoint.errors))\n }\n\n return parts.join(' ')\n }\n\n /** One endpoint row (`client/api https://\u2026 \u25CF ok up 4m12s 18/min \u26A0 0`). */\n private endpointLine(endpoint: ReadySummary['endpoints'][number], tagWidth: number, withHealthDot: boolean): string {\n const dot = withHealthDot ? this.healthDot(endpoint.healthy) : ''\n const status = this.statusFields(endpoint)\n const suffix = [dot, status].filter(Boolean).join(' ')\n\n return ` ${this.color(ANSI.teal, endpoint.tag.padEnd(tagWidth))} ${this.color(ANSI.blue, endpoint.url)}${\n suffix ? ` ${suffix}` : ''\n }`\n }\n\n /** One failed row (`client/api \u25CF failed <reason>`) \u2014 no URL, because there is nothing listening. */\n private failedLine(failed: FailedRow, tagWidth: number): string {\n return ` ${this.color(ANSI.teal, failed.tag.padEnd(tagWidth))} ${this.color(\n ANSI.red,\n '\u25CF failed',\n )} ${this.color(ANSI.dim, failed.reason)}`\n }\n\n /**\n * Shared header layout: blank, title line, blank, one endpoint row per backend, a reference row per\n * UI app, then the watch/log legend. `withHealthDot` is the ONLY difference between the static Ink\n * header (false \u2014 health is live, the footer owns it) and the ready/boot frame (true).\n */\n private formatLines(summary: ReadySummary, { withHealthDot }: { withHealthDot: boolean }): string[] {\n const tagWidth = this.tagWidth(summary)\n const lines: string[] = ['', this.titleLine(summary), '']\n\n for (const e of summary.endpoints) {\n lines.push(this.endpointLine(e, tagWidth, withHealthDot))\n }\n // Failures sit with the live rows, not in the scrollback above: the log line announcing the crash\n // is metres up the terminal by now, and the header is the only thing the user actually reads.\n for (const f of summary.failed ?? []) {\n lines.push(this.failedLine(f, tagWidth))\n }\n for (const u of summary.uiRefs) {\n lines.push(this.uiRefLine(u, tagWidth, u.errors))\n }\n\n lines.push('', ...this.legendLines(summary))\n\n return lines\n }\n\n /**\n * Static reference lines for the persistent Ink header, committed ONCE via `<Static>`: title,\n * endpoint URLs WITHOUT the health dot (health is live \u2192 the footer owns it), UI reference rows,\n * watch line, clickable log path, separator. Pure; colors follow `isTTY`.\n */\n formatHeaderLines(summary: ReadySummary): string[] {\n return this.formatLines(summary, { withHealthDot: false })\n }\n\n /**\n * The live status rows \u2014 THE PANEL. Re-rendered in place on every tick; never committed to `<Static>`.\n *\n * This is the only part of the screen that can change after `ready`, and that makes it the only place\n * live fields can live. The header is committed once through `<Static>`, so anything painted there is\n * a photograph: an uptime or an error count rendered into the header would be frozen at its boot value\n * for the whole session, looking live and being a lie. (It was: the live fields went into the shared\n * endpoint line first, the header picked them up, the footer kept printing a bare health dot, and a\n * real run showed a panel with no uptime, no req/min and no error count at all. No unit test saw it \u2014\n * only the rendered terminal did.)\n *\n * Every row is rendered, including an endpoint that was never probed and a UI with no backend at all:\n * with no log tail on screen this panel is the entire signal, and a row that is absent cannot report\n * that its service is broken.\n */\n formatFooterLines(summary: ReadySummary): string[] {\n const tagWidth = this.tagWidth(summary)\n const rows = summary.endpoints.map((e) => {\n const dot = this.healthDot(e.healthy)\n const status = this.statusFields(e)\n const cells = [dot, status].filter(Boolean).join(' ')\n\n return ` ${this.color(ANSI.teal, e.tag.padEnd(tagWidth))} ${cells}`\n })\n\n // A UI whose port infra-kit could not claim has no endpoint row \u2014 but its errors still have to land\n // somewhere the user can see, and it is precisely the app most likely to be misconfigured.\n for (const ref of summary.uiRefs) {\n if (ref.errors == null) continue\n rows.push(` ${this.color(ANSI.teal, ref.tag.padEnd(tagWidth))} ${this.errorCount(ref.errors)}`)\n }\n\n // The heartbeat. Without it a UI-only session \u2014 whose rows carry no backend uptime and no req/min \u2014\n // would render an identical frame every tick, and Ink does not repaint an identical frame. The panel\n // would be genuinely, verifiably alive and look exactly like a hung process.\n if (summary.sessionUptimeMs != null) {\n const beat = `up ${formatUptime(summary.sessionUptimeMs)}`\n\n rows.push(` ${this.color(ANSI.dim, beat)}`)\n }\n\n return rows\n }\n\n /**\n * Build the ready-header lines with NO side effects (no terminal write, no tee), so both\n * {@link ready} (which writes + tees them) and the Ink boot UI (which commits them via `<Static>`\n * and tee-only's them) share one layout. Colors follow `isTTY` exactly like every other line.\n */\n formatReadyLines(summary: ReadySummary): string[] {\n return this.formatLines(summary, { withHealthDot: true })\n }\n\n // ---- the live tail ------------------------------------------------------\n\n /**\n * One tagged, timestamped tail line: `14:02:11 client/api GET /api/v1/ping 200 12ms`. Arrives\n * strictly after {@link ready} (a request implies a running server), so it never interleaves the\n * header. Timestamp comes from the injected clock.\n */\n event(input: { tag: string; text: string }): void {\n const ts = formatClock(this.deps.now())\n const line = ` ${this.color(ANSI.dim, ts)} ${this.color(ANSI.teal, input.tag)} ${input.text}`\n\n this.emit(line)\n this.tee(`${input.tag} ${input.text}`, 'info')\n }\n}\n"],
|
|
5
|
+
"mappings": "AAeA,OAAOA,MAAa,eAqHpB,IAAMC,EAAiB,CAAC,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,QAAG,EAClEC,EAAsB,GAEtBC,EAAO,CACX,MAAO,UACP,IAAK,UACL,KAAM,UACN,KAAM,WACN,MAAO,WACP,KAAM,WACN,IAAK,UACP,EAGMC,EAAa,YAObC,EAAe,qCAORC,EAAaC,GACjBA,EAAE,QAAQF,EAAc,EAAE,EAI7BG,EAAQ,GACL,OAAO,CAAC,EAAE,SAAS,EAAG,GAAG,EAIrBC,EAAeC,GACnB,GAAGF,EAAKE,EAAE,SAAS,CAAC,CAAC,IAAIF,EAAKE,EAAE,WAAW,CAAC,CAAC,IAAIF,EAAKE,EAAE,WAAW,CAAC,CAAC,GAIjEC,EAAiBC,GACrB,IAAIA,EAAK,KAAM,QAAQ,CAAC,CAAC,IAUrBC,EAAgBD,GAAuB,CAClD,IAAME,EAAQ,KAAK,IAAI,EAAG,KAAK,MAAMF,EAAK,GAAI,CAAC,EACzCG,EAAQ,KAAK,MAAMD,EAAQ,IAAI,EAC/BE,EAAU,KAAK,MAAOF,EAAQ,KAAQ,EAAE,EACxCG,EAAUH,EAAQ,GAExB,OAAIC,EAAQ,EAAU,GA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K,IAAI,EAErD,MAAO,KAAK,KAAK,MAAMzC,EAAK,KAAMiC,EAAE,IAAI,OAAOc,CAAQ,CAAC,CAAC,KAAKS,CAAK,EACrE,CAAC,EAID,QAAWV,KAAOf,EAAQ,OACpBe,EAAI,QAAU,MAClBS,EAAK,KAAK,KAAK,KAAK,MAAMvD,EAAK,KAAM8C,EAAI,IAAI,OAAOC,CAAQ,CAAC,CAAC,KAAK,KAAK,WAAWD,EAAI,MAAM,CAAC,EAAE,EAMlG,GAAIf,EAAQ,iBAAmB,KAAM,CACnC,IAAM0B,EAAO,MAAM/C,EAAaqB,EAAQ,eAAe,CAAC,GAExDwB,EAAK,KAAK,KAAK,KAAK,MAAMvD,EAAK,IAAKyD,CAAI,CAAC,EAAE,CAC7C,CAEA,OAAOF,CACT,CAOA,iBAAiBxB,EAAiC,CAChD,OAAO,KAAK,YAAYA,EAAS,CAAE,cAAe,EAAK,CAAC,CAC1D,CASA,MAAMf,EAA4C,CAChD,IAAM0C,EAAKpD,EAAY,KAAK,KAAK,IAAI,CAAC,EAChCoB,EAAO,KAAK,KAAK,MAAM1B,EAAK,IAAK0D,CAAE,CAAC,KAAK,KAAK,MAAM1D,EAAK,KAAMgB,EAAM,GAAG,CAAC,KAAKA,EAAM,IAAI,GAE9F,KAAK,KAAKU,CAAI,EACd,KAAK,IAAI,GAAGV,EAAM,GAAG,IAAIA,EAAM,IAAI,GAAI,MAAM,CAC/C,CACF",
|
|
6
|
+
"names": ["process", "SPINNER_FRAMES", "SPINNER_INTERVAL_MS", "ANSI", "CLEAR_LINE", "ANSI_PATTERN", "stripAnsi", "s", "pad2", "formatClock", "d", "formatElapsed", "ms", "formatUptime", "total", "hours", "minutes", "seconds", "resolveEndpointUrl", "input", "DevRenderer", "deps", "text", "code", "href", "label", "c", "message", "level", "line", "frame", "phase", "errors", "healthy", "summary", "lines", "e", "u", "f", "w", "t", "meta", "failedCount", "elapsed", "status", "watchText", "logLink", "watchLine", "rule", "ref", "tagWidth", "errText", "endpoint", "parts", "withHealthDot", "dot", "suffix", "failed", "rows", "cells", "beat", "ts"]
|
|
7
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import a from"node:process";var i="\x1B[3J",S=n=>typeof n=="string"?n.split(i).join(""):n,w=n=>new Proxy(n,{get(e,t,o){if(t==="write")return(s,...u)=>e.write(S(s),...u);let r=Reflect.get(e,t,o);return typeof r=="function"?r.bind(e):r}}),f=()=>w(a.stderr);export{w as a,f as b};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-TPVXMJ7N.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as
|
|
3
|
-
`),
|
|
4
|
-
`);for(let i of t){let
|
|
5
|
-
`;var O=(e,t=!0)=>({line:e,reproducible:t});import M from"node:fs";import uo from"node:os";import fo from"node:path";import wt from"node:process";var j="INFRA_KIT_SESSION_REPORT",se=null,ht=!1,yt=[],Rt=(e=wt.env)=>{ht||(se=e[j]??null,ht=!0,delete e[j])};var Et=(e,t)=>{if(!se)return;let o=e.summary??(yt.length>0?[...yt]:void 0),r={...e,...o?{summary:o}:{}},a=t?.write??((n,i)=>{M.writeFileSync(n,i)});try{a(se,JSON.stringify(r))}catch{}},St=0,xt=e=>{let t=e?.tmpdir?.()??uo.tmpdir(),o=e?.pid??wt.pid;return St+=1,fo.join(t,`infra-kit-session-${o}-${St}.json`)},Ct=(e,t)=>{if(!(t?.exists??(i=>M.existsSync(i)))(e))return null;let r=t?.read??(i=>M.readFileSync(i,"utf-8")),a=t?.unlink??(i=>M.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{a(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var vo=(e,t)=>[...t,e],ce=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,Pt=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&Y.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${Y.join(", ")}.`)}},ho=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=>{m(await $e({all:t.all,confirmedCommand:t.yes}))}),yo=e=>e.description("List all release branches").action(async()=>{m(await Ve())}),So=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".',vo,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(qe),a=r.length>0?r:void 0;m(await Ke({releases:a,confirmedCommand:t.yes}))}),wo=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=>{m(await Je({version:t.version,description:t.description,confirmedCommand:t.yes}))}),Ro=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=>{m(await Fe({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),Eo=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=>{m(await Ge({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),xo=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=>{m(await Ue({version:t.version,confirmedCommand:t.yes}))}),Co=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await tt({confirmedCommand:t.yes}))}),Po=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=Pt(t.ide,"--ide")??Pt(t.cursor,"--cursor");m(await Xe({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),To=e=>e.description("List all git worktrees with detailed information").action(async()=>{m(await Qe())}),ko=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=>{m(await et({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Ao=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{m(await Ze())}),bo=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=>{m(await ae({init:t.init}))}),Io=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ye();m(t),t.structuredContent.ok||(b.exitCode=1)}),Lo=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 Be({repos:ce(t.repos)});m(o),o.structuredContent.ok||(b.exitCode=1)}),No=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{m(await X())}),_o=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{m(await Q())}),Do=new Set(["init","doctor","version","dev","self-update","mcp"]),Oo=e=>e.startsWith("env-")||Do.has(e),Mo=new Set(["env-autoload","mcp","version","self-update"]),$=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},le=()=>{let e=new go,t=e.command("release").description("Release management commands");ho(t.command("merge-dev")),yo(t.command("list")),So(t.command("create")),wo(t.command("desc-edit")),Ro(t.command("deploy-all")),Eo(t.command("deploy-selected")),xo(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");Po(o.command("add")),To(o.command("list")),ko(o.command("remove")),Co(o.command("sync")),Ao(o.command("reload"));let r=e.command("config").description("Manage infra-kit configuration files");No(r.command("path")),_o(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 he({all:n.all,root:n.root});m(i),i.structuredContent.allPassed||(b.exitCode=1)});let a=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return Io(a.command("check")),a.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=>{m(await He({confirmedCommand:n.yes,repos:ce(n.repos)}))}),a.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=>{m(await We({confirmedCommand:!0,repos:ce(n.repos)}))}),Lo(a.command("diff")),bo(a.command("config")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{m(await Le())}),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=>{re({dryRun:!!n.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{te()}),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)").action(async(n,i)=>{let{runDevServerCli:c}=await import("./dev-server.js"),s=!!(b.stdout.isTTY&&b.stdin.isTTY);await c({...i,preset:n},s,N.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{m(await ze())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{m(await Me())}),e.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{m(await _e())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{m(await V())}),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=>{m(await Oe({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=>{m(await Ne({purge:!!n.purge}))}),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 ee({projectDir:n.projectDir})}),e.commands.forEach(je),e.hook("preAction",async(n,i)=>{K.start($(i)),N.enabled=!!i.optsWithGlobals().json,N.enabled&&(l.level="warn"),Mo.has($(i))||await Re(),Oo(i.name())||await A({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let c=$(i);if(it(c))return;let d=K.snapshot()?.formattedOptions??"",f=d?` ${d}`:"",g=`infra-kit ${c}${f}`;Et({equivalent:O(g,!0)})}),e};var me=(e,t=" ")=>{let o=e.reduce((r,[a])=>Math.max(r,a.length),0);return e.map(([r,a])=>`${r.padEnd(o)}${t}${a}`)};import{spawn as Fo}from"node:child_process";import h from"node:process";var v={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."},Tt={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},kt=e=>`${v.reproPrefix}${e}`,jo=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,$o=(e,t)=>e==="findings"?t!=null?`${t} ${v.findingsSuffix}`:v.findingsPlain:{ok:v.ok,failed:v.failed,cancelled:v.cancelled}[e],At=e=>{let t=e.equivalent.reproducible?v.reproPrefix:v.nonReproPrefix,o=e.ascii===!0?Tt[e.outcome].ascii:Tt[e.outcome].unicode,a=[$o(e.outcome,e.findingsCount),jo(e.durationMs)],n=e.summary?.[0];n!=null&&n.length>0&&a.push(n);let i=[`${o} ${a.join(v.sep)}`];return e.showEquivalent!==!1&&i.unshift(`${t}${e.equivalent.line}`),e.envNotice===!0&&i.push(v.envNotice),i.join(`
|
|
6
|
-
`)
|
|
2
|
+
import{$ as At,A as ot,B as rt,C as nt,D as it,E as at,F as st,G as te,H as ct,I as M,J as m,K as lt,L as mt,M as dt,N as pt,O as ut,P as ft,Q as gt,R as ht,S as vt,T as yt,U as wt,V as St,W as kt,X as Rt,Y as oe,Z as Et,_ as xt,a as N,aa as Tt,b as Ne,ba as Ct,c as Le,ca as Pt,d as _e,da as bt,e as De,f as Oe,fa as It,g as _,ga as Nt,h as x,ha as Dt,i as h,j as O,k as qe,l as Ve,m as Je,n as F,o as Ke,p as Be,q as We,r as Ye,s as He,t as Xe,u as Qe,v as Ze,w as Z,x as et,y as tt,z as ee}from"./chunk-RLZ5IB2E.js";import{r as re}from"./chunk-NC2TIQ3M.js";import{a as Lt,b as j,c as _t,d as T,e as ne,f as ie,g as ae}from"./chunk-E2SEBLGJ.js";import{a as ze}from"./chunk-E2NWNNC6.js";import{a as $}from"./chunk-6FU2TRU5.js";import{a as A}from"./chunk-4MRYIYJP.js";import{P as X,Q as L,S as Ie,m as be,v as c}from"./chunk-KZP2SY37.js";import{a as D,b as Fe,d as $e,f as Me,g as je,j as Q,k as Ue,n as v,q as Ge}from"./chunk-CHETBZ6M.js";import jr,{Separator as fo}from"@inquirer/select";import{realpathSync as Ur}from"node:fs";import g from"node:process";import{fileURLToPath as ho}from"node:url";var yo=(e,t)=>{let o=e,r;for(let a of t){if(r=o.find(n=>n.name()===a),!r)return;o=r.commands}return r},Ot=e=>Pt.flatMap(({key:t,label:o})=>It(t).flatMap(r=>{let a=yo(e,r.groupPath);return a?[{name:r.groupPath.join(" "),description:a.description(),group:o}]:[]}));import{Command as tr}from"commander";import I from"node:process";import Ft from"node:process";import{$ as wo}from"zx";var se=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 x(i.path)}))),o=t.at(-1)?.exists===!0,r=await ot(e.userProject,o),a=o?rt(r):"";c.info(`Project name: ${e.projectName}
|
|
3
|
+
`),c.info(`Config merge chain (later overrides earlier):
|
|
4
|
+
`);for(let i of t){let l=i.exists?" [\u2713]":" [ ]",s=i.path===e.userProject&&a!==""?` ${a}`:"";c.info(`${l} ${i.label.padEnd(22)} ${h(i.path)}${s}`)}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=Ft.env.EDITOR||Ft.env.VISUAL||"vi",o=await Xe(e);o.createdConfig&&c.info(Qe(o)),c.info(`Opening ${h(e.userProject)} in ${t}`),await wo({stdio:"inherit"})`${t} ${e.userProject}`,Ie();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}},U=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 P from"node:process";var So="autoload-warn-misconfig.flag",ko="autoload-warn-fail.flag",Mt="autoload-warn-auth-fail.flag",me="autoload-fail.flag",de="autoload-auth-fail.json",Ro=3e4,jt=async(e=!0)=>{let t;try{t=await L()}catch{return null}let o=t.envAutoLoad;return o?t.environments.includes(o.config)?{trigger:o.trigger,config:o.config,project:t.envManagement.config.name}:(e&&G(`infra-kit: envAutoLoad.config "${o.config}" is not one of environments [${t.environments.join(", ")}] \u2014 env auto-load disabled.`,So),null):null},Ut=e=>{let{trigger:t,expectedTrigger:o,targetConfig:r,targetProject:a,env:n,force:i}=e;return t!==o||!n.session||n.cleared||n.currentConfig&&!n.autoLoadedMarker||!i&&n.autoLoadedMarker&&n.currentConfig===r&&n.currentProject===a?"skip":"load"},b=async({expectedTrigger:e,projectDir:t,force:o,isAuthFailure:r=Le})=>{let a=e==="cli-invocation";a&&q();let n=null;try{if(n=await jt(a),!n||Ut({trigger:n.trigger,expectedTrigger:e,targetConfig:n.config,targetProject:n.project,env:To(),force:o})==="skip"||$t()||bo())return null;let l=Co(),s=await Ke({config:n.config,autoLoaded:!0,projectDir:t,beforeWrite:()=>!$t()&&!Po(l)});return s?(No(),Ao(),s.filePath):null}catch(i){let l=i.message,s=r(i);return Io(),s&&n&&xo({config:n.config,reason:l,at:Date.now()}),a&&s&&n?(G(U(n.config),Mt),c.debug(`env auto-load auth failure: ${l}`)):a?G(`infra-kit: env auto-load failed \u2014 ${l} (will retry later)`,ko):c.debug(`env auto-load skipped: ${l}`),null}},q=()=>{let e=Eo();e&&(G(U(e.config),Mt),c.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},Eo=()=>{try{let e=p.readFileSync(y.join(v(),de),"utf-8");return le(JSON.parse(e))}catch{return null}},xo=e=>{try{let t=v();p.mkdirSync(t,{recursive:!0,mode:448}),Ge(y.join(t,de),JSON.stringify(e),384)}catch{}},Ao=()=>{try{p.rmSync(y.join(v(),de),{force:!0})}catch{}},To=()=>({session:P.env[$e],cleared:P.env[Ue],currentConfig:P.env[Me],currentProject:P.env[je],autoLoadedMarker:P.env[Q]}),Co=()=>{try{return p.statSync(y.join(v(),D)).mtimeMs}catch{return null}},Po=e=>{try{let t=y.join(v(),D);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}},$t=()=>{try{let e=v(),t=y.join(e,Fe);if(!p.existsSync(t))return!1;let o=y.join(e,D);return p.existsSync(o)?p.statSync(t).mtimeMs>=p.statSync(o).mtimeMs:!0}catch{return!1}},bo=()=>{try{let e=y.join(v(),me);return p.existsSync(e)?Date.now()-p.statSync(e).mtimeMs<Ro:!1}catch{return!1}},Io=()=>{try{let e=v();p.mkdirSync(e,{recursive:!0,mode:448}),p.writeFileSync(y.join(e,me),"",{mode:384})}catch{}},No=()=>{try{p.rmSync(y.join(v(),me),{force:!0})}catch{}},G=(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{}c.warn(e)};var pe=async({projectDir:e}={})=>{await b({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var Gt="https://dashboard.doppler.com/workplace/projects",Lo=(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}"): ${Gt}/${e}`],ue=async({env:e})=>{let o=!!(await qe())?.envs[e];await Je(e);let r=await F(),a=await _(),n=await O();o?c.info(`Removed the "${e}" service token from ${h(n)}.`):c.info(`No "${e}" service token was stored in ${h(n)} \u2014 nothing to remove.`),r.length>0&&c.info(`Purged ${r.length} warm cache(s) across this repo's worktrees.`);for(let l of Lo(a,e))c.warn(l);let i={env:e,removed:o,storePath:n,warmCachesPurged:r.length,revokeUrl:`${Gt}/${a}`};return{content:N(JSON.stringify(i,null,2)),structuredContent:i}};import _o from"@inquirer/password";import J from"node:process";import{$ as V}from"zx";var Do=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Oo(),source:"stdin"};if(t){let r=J.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 _o({message:"Paste the Doppler service token (input is hidden)",mask:!0},{output:J.stderr})).trim(),source:"prompt"}},Oo=async()=>{let e=[];J.stdin.setEncoding("utf8");for await(let t of J.stdin)e.push(t);return e.join("").trim()},fe="DOPPLER_CONFIG",Fo=3e4,$o=async(e,t,o)=>{let r=V.quiet;V.quiet=!0;let a;try{a=(await V({env:We(e)})`doppler secrets download --no-file --format json --project ${t} --config ${o}`.timeout(Fo)).stdout}catch(n){throw Mo(n,o)}finally{V.quiet=r}return He(a)},Mo=(e,t)=>{let o=Oe(e)??(e instanceof Error?e.message:String(e));if(_e(o)!=="auth")return e instanceof Error?e:new Error(String(e));let r=De(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
|
+
`))},jo=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${fe}.`,"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
|
+
`),ge=async({env:e,stdin:t,fromEnv:o,force:r})=>{let{environments:a}=await L();if(!a.includes(e))throw new Error(`Unknown environment "${e}". infra-kit.json \u2192 environments declares: ${a.join(", ")}.`);let n=await _(),{token:i,source:l}=await Do({stdin:t,fromEnv:o});if(!i)throw new Error("No token provided \u2014 nothing was written.");let s=await $o(i,n,e);Ye(s,e);let d=s.some(([k])=>k===fe);if(!d&&!r)throw new Error(jo(e));await Ve(e,i);let u=await F(),f=await O();c.info(`Stored the "${e}" service token (${te(i)}) in ${h(f)} (mode 0600).`),d||c.warn(`Scope was NOT verified (no ${fe} in the payload) \u2014 written because --force was given.`),u.length>0&&c.info(`Purged ${u.length} warm cache(s) so the next shell cannot serve secrets fetched with an old token.`);let E={env:e,source:l,redactedToken:te(i),storePath:f,scopeVerified:d,warmCachesPurged:u.length};return A.print(),{content:N(JSON.stringify(E,null,2)),structuredContent:E}};import{spawn as Uo}from"node:child_process";import K from"node:process";import{fileURLToPath as Go}from"node:url";var qo=["SIGINT","SIGTERM"],qt=()=>Go(new URL("./mcp.js",import.meta.url)),he=(e={})=>{let t=e.spawn??Uo,o=e.exit??(i=>K.exit(i)),r=e.env??K.env,a=e.onError??(i=>c.error(i)),n=t(K.execPath,[qt()],{stdio:"inherit",env:$(r)});n.on("error",i=>{a(`failed to launch the MCP server: ${i.message}`),o(1)}),qo.forEach(i=>{K.on(i,()=>{n.kill(i)})}),n.on("exit",(i,l)=>{o(l?1:i??1)})};import{spawnSync as Vo}from"node:child_process";import{realpathSync as Jo}from"node:fs";import ve from"node:process";import{fileURLToPath as Ko}from"node:url";var Bo=()=>Jo(Ko(import.meta.url)),Wo=(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),ye=({dryRun:e},t={})=>{let o=t.spawnSync??Vo,r=t.print??(k=>c.info(k)),a=t.exit??(k=>ve.exit(k)),n=t.env??ve.env,i=t.selfRealPath??Bo(),l=t.lazyNpmRoot??_t,{manager:s,updateCommand:d,canSelfSpawn:u}=Lt({selfRealPath:i,env:n,realpath:T,lazyNpmRoot:l}),f=d.join(" ");if(e){r(`Detected install manager: ${s}`),r(`Would run: ${f}`);return}if(!u){r(`Detected install manager: ${s}`),r(`Run this yourself: ${f}`),r(s==="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 E=o(d[0],d.slice(1),{stdio:"inherit",shell:ve.platform==="win32",env:$(n)});Wo(E,s,r,a)};import{VENDOR_CONFIG_FILE as Jt}from"@slip-stream-kit/config/internal";import we from"node:fs/promises";import Se from"node:path";import Vt from"node:process";import{pathToFileURL as Yo}from"node:url";var Kt="~/projects",ke=async(e={})=>{if(e.init){await zo(e.cwd);return}await Ho()},Ho=async()=>{let e=Z(),t=await x(e);if(c.info(`Factory config: ${h(e)} ${t?"[\u2713]":"[ ]"}`),!t){c.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Vt.exitCode=1;return}let{workspaceDir:o,targets:r}=await tt(),a=et(o),n=await x(a);c.info(`workspaceDir: ${o} (resolved: ${a}) ${n?"[\u2713 exists]":"[ ] not found"}`),c.info("Targets:");let i=n;for(let l of r){let s=Se.join(a,l),d=await x(s);d||(i=!1);let u=d?"[\u2713]":"[ ]",f=d?"":" (not found \u2014 clone or remove)";c.info(` ${u} ${l} ${h(s)}${f}`)}i||(Vt.exitCode=1)},zo=async e=>{let t=Z();if(await x(t)){c.info(`Factory config already exists at ${h(t)} \u2014 leaving it untouched.`);return}let o=e??await be(),r=await Xo(o);await we.mkdir(Se.dirname(t),{recursive:!0}),await we.writeFile(t,Qo(r),"utf-8"),c.info(`\u2713 Created ${h(t)}`),r.length>0&&c.info(` Seeded ${r.length} target(s) from the source ${Jt}.`),c.info(` Edit \`workspaceDir\` (placeholder: ${Kt}) to point at where your repos live.`),r.length===0&&c.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},Xo=async e=>{try{let t=Se.join(e,Jt),o=await we.stat(t),n=(await import(`${Yo(t).href}?mtime=${Number(o.mtimeMs)}`)).default,i=typeof n=="function"?await n():n;if(i&&typeof i=="object"&&"targets"in i){let l=i.targets;if(Array.isArray(l)&&l.every(s=>typeof s=="string"))return l}}catch{}return[]},Qo=e=>`${JSON.stringify({workspaceDir:Kt,targets:e},null,2)}
|
|
7
|
+
`;var B=(e,t=!0)=>({line:e,reproducible:t});import W from"node:fs";import Zo from"node:os";import er from"node:path";import Ht from"node:process";var Y="INFRA_KIT_SESSION_REPORT",Re=null,Bt=!1,Wt=[],zt=(e=Ht.env)=>{Bt||(Re=e[Y]??null,Bt=!0,delete e[Y])};var Xt=(e,t)=>{if(!Re)return;let o=e.summary??(Wt.length>0?[...Wt]:void 0),r={...e,...o?{summary:o}:{}},a=t?.write??((n,i)=>{W.writeFileSync(n,i)});try{a(Re,JSON.stringify(r))}catch{}},Yt=0,Qt=e=>{let t=e?.tmpdir?.()??Zo.tmpdir(),o=e?.pid??Ht.pid;return Yt+=1,er.join(t,`infra-kit-session-${o}-${Yt}.json`)},Zt=(e,t)=>{if(!(t?.exists??(i=>W.existsSync(i)))(e))return null;let r=t?.read??(i=>W.readFileSync(i,"utf-8")),a=t?.unlink??(i=>W.unlinkSync(i)),n;try{n=r(e)}catch{return null}finally{try{a(e)}catch{}}try{return JSON.parse(n)}catch{return null}};var or=(e,t)=>[...t,e],Ee=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,eo=(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(", ")}.`)}},rr=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=>{m(await mt({all:t.all,confirmedCommand:t.yes}))}),nr=e=>e.description("List all release branches").action(async()=>{m(await ft())}),ir=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".',or,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let r=t.release.map(gt),a=r.length>0?r:void 0;m(await ht({releases:a,confirmedCommand:t.yes}))}),ar=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=>{m(await vt({version:t.version,description:t.description,confirmedCommand:t.yes}))}),sr=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=>{m(await pt({version:t.version,env:t.env,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),cr=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=>{m(await ut({version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,confirmedCommand:t.yes}))}),lr=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=>{m(await dt({version:t.version,confirmedCommand:t.yes}))}),mr=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{m(await Ct({confirmedCommand:t.yes}))}),dr=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=eo(t.ide,"--ide")??eo(t.cursor,"--cursor");m(await Et({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:o,githubDesktop:t.githubDesktop,cmux:t.cmux}))}),pr=e=>e.description("List all git worktrees with detailed information").action(async()=>{m(await xt())}),ur=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=>{m(await Tt({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),fr=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{m(await At())}),gr=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=>{m(await ke({init:t.init}))}),hr=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await yt();m(t),t.structuredContent.ok||(I.exitCode=1)}),vr=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 wt({repos:Ee(t.repos)});m(o),o.structuredContent.ok||(I.exitCode=1)}),yr=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{m(await se())}),wr=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{m(await ce())}),Sr=new Set(["init","doctor","version","dev","self-update","mcp"]),kr=e=>e.startsWith("env-")||Sr.has(e),Rr=new Set(["env-autoload","mcp","version","self-update"]),H=e=>{let t=[];for(let o=e;o&&o.parent;o=o.parent)t.unshift(o.name());return t.join(" ")},xe=()=>{let e=new tr,t=e.command("release").description("Release management commands");rr(t.command("merge-dev")),nr(t.command("list")),ir(t.command("create")),ar(t.command("desc-edit")),sr(t.command("deploy-all")),cr(t.command("deploy-selected")),lr(t.command("deliver"));let o=e.command("worktrees").description("Git worktree management commands");dr(o.command("add")),pr(o.command("list")),ur(o.command("remove")),mr(o.command("sync")),fr(o.command("reload"));let r=e.command("config").description("Manage infra-kit configuration files");yr(r.command("path")),wr(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 Ne({all:n.all,root:n.root});m(i),i.structuredContent.allPassed||(I.exitCode=1)});let a=e.command("vendor").description("Verify and sync the mirrored vendor/ tree");return hr(a.command("check")),a.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=>{m(await kt({confirmedCommand:n.yes,repos:Ee(n.repos)}))}),a.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=>{m(await St({confirmedCommand:!0,repos:Ee(n.repos)}))}),vr(a.command("diff")),gr(a.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=>{m(await nt({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=>{ye({dryRun:!!n.dryRun})}),e.command("mcp").description("Run the infra-kit MCP server (stdio transport)").action(()=>{he()}),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)").action(async(n,i)=>{let{runDevServerCli:l}=await import("./dev-server.js"),s=!!(I.stdout.isTTY&&I.stdin.isTTY);await l({...i,preset:n},s,M.enabled)}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{m(await Rt())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{m(await st())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{m(await at())}),e.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{m(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=>{m(await Be({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=>{m(await it({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)=>{m(await ge({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=>{m(await ct({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=>{m(await ue({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(lt),e.hook("preAction",async(n,i)=>{A.start(H(i)),M.enabled=!!i.optsWithGlobals().json,M.enabled&&(c.level="warn"),Rr.has(H(i))||await Ze(),q(),kr(i.name())||await b({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(n,i)=>{let l=H(i);if(Nt(l))return;let d=A.snapshot()?.formattedOptions??"",u=d?` ${d}`:"",f=`infra-kit ${l}${u}`;Xt({equivalent:B(f,!0)})}),e};var Ae=(e,t=" ")=>{let o=e.reduce((r,[a])=>Math.max(r,a.length),0);return e.map(([r,a])=>`${r.padEnd(o)}${t}${a}`)};import{spawn as Tr}from"node:child_process";import S from"node:process";var 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."},to={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},oo=e=>`${w.reproPrefix}${e}`,Er=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,xr=(e,t)=>e==="findings"?t!=null?`${t} ${w.findingsSuffix}`:w.findingsPlain:{ok:w.ok,failed:w.failed,cancelled:w.cancelled}[e],ro=e=>{let t=e.equivalent.reproducible?w.reproPrefix:w.nonReproPrefix,o=e.ascii===!0?to[e.outcome].ascii:to[e.outcome].unicode,a=[xr(e.outcome,e.findingsCount),Er(e.durationMs)],n=e.summary?.[0];n!=null&&n.length>0&&a.push(n);let i=[`${o} ${a.join(w.sep)}`];return e.showEquivalent!==!1&&i.unshift(`${t}${e.equivalent.line}`),e.envNotice===!0&&i.push(w.envNotice),i.join(`
|
|
8
|
+
`)};var Ar=new Set([130,143]),no=(e,t,o,r=!1)=>o?t!=null||e===0?"ok":"findings":r&&e!=null&&Ar.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import io from"node:process";var R={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},ao=(e,t)=>{let o=t?.write??(n=>{io.stderr.write(n)}),r=t?.stdin??io.stdin,a=[R.saveCursor,R.scrollRegion,R.restoreCursor,R.column,R.sgr,R.cursor,R.wrap];e.entersAltScreen===!0&&a.push(R.primaryBuffer),o(a.join("")),r.isTTY===!0&&r.isRaw===!0&&r.setRawMode?.(!1)};var so=e=>`infra-kit ${e.groupPath.join(" ")}`,Cr=e=>new Promise(t=>{e.on("exit",(o,r)=>{t({code:o,signal:r})}),e.on("error",()=>{t({code:1,signal:null})})}),Pr=async(e,t,o)=>{let r=Qt(),a={...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:a});i=await Cr(f)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let l=Zt(r),s=no(i.code,i.signal,l!=null,e.longRunning),d=so(e),u=l?.equivalent??B(d,!0);return ro({equivalent:u,outcome:s,durationMs:t.now()-n,summary:l?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,showEquivalent:!(u.reproducible&&u.line===d)})},br=(e,t)=>{let o=!1,r=!1,a=()=>{if(e()){o=!0;return}t.exit(0)},n=()=>{if(!e()){t.exit(0);return}o||(r=!0)},i=()=>{t.exit(129)},l=()=>{e()&&t.raise("SIGSTOP")};return t.register("SIGINT",a),t.register("SIGTERM",n),t.register("SIGHUP",i),t.register("SIGTSTP",l),{dispose:()=>{t.unregister("SIGINT",a),t.unregister("SIGTERM",n),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",l)},childStarted:()=>{o=!1},quitRequested:()=>r}},co=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),lo=async(e,t)=>{let o={spawn:t.spawn??Tr,now:t.now??(()=>Date.now()),env:t.env??S.env,cliPath:t.cliPath,ascii:t.ascii??!(S.stdout.isTTY&&S.env.TERM!=="dumb"),resetTerminal:t.resetTerminal??(s=>{ao(s)})},r=t.write??(s=>S.stderr.write(s)),a=t.signals??{register:(s,d)=>{S.on(s,d)},unregister:(s,d)=>{S.off(s,d)},exit:s=>{S.exit(s)},raise:s=>{S.kill(S.pid,s)}},n=!1,i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},l=t.installSignals===!1?i:br(()=>n,a);try{for(;;){if(l.quitRequested())return;n=!1;let s=await t.renderPalette(e);if(s==null)return;let d=t.resolveCommand(s);if(!d)continue;let u=oo(so(d));r(`
|
|
9
|
+
${u}
|
|
10
|
+
`),l.childStarted();let f=await Pr(d,o,()=>{n=!0});r(`
|
|
7
11
|
${f}
|
|
8
|
-
`),c.
|
|
9
|
-
${g}
|
|
10
|
-
`),c.quitRequested())return}}finally{c.dispose()}};import{spawn as Yo}from"node:child_process";import Mt from"node:fs";import T from"node:process";import{fileURLToPath as jt}from"node:url";var Ot=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Ko=new Set(["mcp","self-update"]),Jo=e=>e[2]!=null&&Ko.has(e[2]),de=e=>{let{argv:t,env:o,isTty:r,selfRealPath:a,cwd:n,realpath:i}=e;return Ot.some(s=>{let d=o[s];return d!=null&&d!==""})?"opt-out":t.includes("--json")?"json":Jo(t)?"own-command":r?_(a,n,i)?"local-install":null:"not-a-tty"};var Bo=e=>{Yo(T.execPath,[e,"--parent-pid",String(T.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Wo=()=>jt(new URL("./update-check.js",import.meta.url)),Ho=()=>Mt.realpathSync(jt(new URL("./cli.js",import.meta.url))),zo=/^[\w@./+-]+$/i,Xo=e=>zo.test(e),Qo=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||W(e.latestVersion,t)&&e.updateCommand.every(Xo)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},pe=(e,t={})=>{try{let o=t.argv??T.argv,r=t.env??T.env,a=t.isTty??!!T.stdout.isTTY,n=t.cwd??T.cwd(),i=t.nowMs??Date.now(),c=t.selfRealPath??Ho(),s=t.readCache??H,d=t.spawnChild??Bo,f=t.fileExists??(U=>Mt.existsSync(U)),g=t.notify??(U=>{l.info(U)});if(de({argv:o,env:r,isTty:a,selfRealPath:c,cwd:n,realpath:P})!==null)return;let x=s();if(Qo(x,e,g),!z(x,i))return;let C=t.childPath??Wo();if(!f(C))return;d(C)}catch{}};Rt();var ue=le(),Ut=async e=>{try{e?await ue.parseAsync(e):await ue.parseAsync()}catch(t){B(t)&&(l.info("Operation cancelled."),u.exit(0));let o=t instanceof Error?t.message:String(t);l.error(o),u.exit(1)}},tr=()=>{try{if(u.env.INFRA_KIT_NO_LOCATION_WARN||u.argv.includes("--json")||u.argv[2]==="mcp")return;_(er(Ft(import.meta.url)),u.cwd(),P)&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};tr();pe(ye.version);var Gt=()=>ct(ue.commands),or=async()=>{let e=Gt(),t=null;try{if(u.stdout.isTTY&&u.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-YCABHUPP.js");t=await o(e)}else{let o=me(e.map(a=>[a.name,a.description])),r=e.flatMap((a,n)=>[...e[n-1]?.group===a.group?[]:[new $t(" "),new $t(`\u2014 ${a.group} \u2014`)],{name:o[n]??a.name,value:a.name}]);t=await Zo({message:"Select a command to run",choices:r},{output:u.stderr})}}catch(o){if(!B(o))throw o}return t},rr=async()=>{let{runCommandPalette:e}=await import("./boot-YCABHUPP.js"),t=Ft(import.meta.url),o=new Map(rt.map(r=>[r.groupPath.join(" "),r]));await Dt(Gt(),{renderPalette:e,resolveCommand:r=>{let a=o.get(r);return a?{groupPath:a.groupPath,entersAltScreen:a.entersAltScreen,sessionEnvNotice:a.sessionEnvNotice,longRunning:a.longRunning}:void 0},cliPath:t})};if(u.argv.length<=2){let e={stdoutIsTTY:!!u.stdout.isTTY,stdinIsTTY:!!u.stdin.isTTY,stderrIsTTY:!!u.stderr.isTTY};if(_t(u.env,e))await rr();else{let t=await or();t&&await Ut(["node","infra-kit",...t.split(" ")])}}else await Ut();
|
|
12
|
+
`)}}finally{l.dispose()}};import{spawn as Lr}from"node:child_process";import po from"node:fs";import C from"node:process";import{fileURLToPath as uo}from"node:url";var mo=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Ir=new Set(["mcp","self-update"]),Nr=e=>e[2]!=null&&Ir.has(e[2]),Te=e=>{let{argv:t,env:o,isTty:r,selfRealPath:a,cwd:n,realpath:i}=e;return mo.some(s=>{let d=o[s];return d!=null&&d!==""})?"opt-out":t.includes("--json")?"json":Nr(t)?"own-command":r?j(a,n,i)?"local-install":null:"not-a-tty"};var _r=e=>{Lr(C.execPath,[e,"--parent-pid",String(C.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Dr=()=>uo(new URL("./update-check.js",import.meta.url)),Or=()=>po.realpathSync(uo(new URL("./cli.js",import.meta.url))),Fr=/^[\w@./+-]+$/i,$r=e=>Fr.test(e),Mr=(e,t,o)=>{!e?.latestVersion||!e.updateCommand||ne(e.latestVersion,t)&&e.updateCommand.every($r)&&o(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${e.updateCommand.join(" ")}`)},Ce=(e,t={})=>{try{let o=t.argv??C.argv,r=t.env??C.env,a=t.isTty??!!C.stdout.isTTY,n=t.cwd??C.cwd(),i=t.nowMs??Date.now(),l=t.selfRealPath??Or(),s=t.readCache??ie,d=t.spawnChild??_r,u=t.fileExists??(z=>po.existsSync(z)),f=t.notify??(z=>{c.info(z)});if(Te({argv:o,env:r,isTty:a,selfRealPath:l,cwd:n,realpath:T})!==null)return;let E=s();if(Mr(E,e,f),!ae(E,i))return;let k=t.childPath??Dr();if(!u(k))return;d(k)}catch{}};Dt();zt();var Pe=xe(),go=async e=>{try{e?await Pe.parseAsync(e):await Pe.parseAsync()}catch(t){re(t)&&(c.info("Operation cancelled."),g.exit(0));let o=t instanceof Error?t.message:String(t);c.error(o),g.exit(1)}},Gr=()=>{try{if(g.env.INFRA_KIT_NO_LOCATION_WARN||g.argv.includes("--json")||g.argv[2]==="mcp")return;j(Ur(ho(import.meta.url)),g.cwd(),T)&&c.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};Gr();Ce(ze.version);var vo=()=>Ot(Pe.commands),qr=async()=>{let e=vo(),t=null;try{if(g.stdout.isTTY&&g.stdin.isTTY){let{runCommandPalette:o}=await import("./boot-MTVHM4N7.js");t=await o(e)}else{let o=Ae(e.map(a=>[a.name,a.description])),r=e.flatMap((a,n)=>[...e[n-1]?.group===a.group?[]:[new fo(" "),new fo(`\u2014 ${a.group} \u2014`)],{name:o[n]??a.name,value:a.name}]);t=await jr({message:"Select a command to run",choices:r},{output:g.stderr})}}catch(o){if(!re(o))throw o}return t},Vr=async()=>{let{runCommandPalette:e}=await import("./boot-MTVHM4N7.js"),t=ho(import.meta.url),o=new Map(bt.map(r=>[r.groupPath.join(" "),r]));await lo(vo(),{renderPalette:e,resolveCommand:r=>{let a=o.get(r);return a?{groupPath:a.groupPath,entersAltScreen:a.entersAltScreen,sessionEnvNotice:a.sessionEnvNotice,longRunning:a.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(co(g.env,e))await Vr();else{let t=await qr();t&&await go(["node","infra-kit",...t.split(" ")])}}else await go();
|
|
11
13
|
//# sourceMappingURL=cli.js.map
|