infra-kit 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/boot-EEEVHAMO.js +2 -0
  2. package/dist/boot-EEEVHAMO.js.map +7 -0
  3. package/dist/{chunk-NC2TIQ3M.js → chunk-7F5YKMWK.js} +2 -2
  4. package/dist/chunk-7F5YKMWK.js.map +7 -0
  5. package/dist/chunk-A7FAXZGI.js +2 -0
  6. package/dist/chunk-A7FAXZGI.js.map +7 -0
  7. package/dist/chunk-AJW5M44V.js +231 -0
  8. package/dist/chunk-AJW5M44V.js.map +7 -0
  9. package/dist/{chunk-E2NWNNC6.js → chunk-FTCM2766.js} +2 -2
  10. package/dist/{chunk-E2NWNNC6.js.map → chunk-FTCM2766.js.map} +1 -1
  11. package/dist/chunk-IPF7ILCB.js +7 -0
  12. package/dist/chunk-IPF7ILCB.js.map +7 -0
  13. package/dist/{chunk-KZP2SY37.js → chunk-KHEUED4B.js} +2 -2
  14. package/dist/chunk-KHEUED4B.js.map +7 -0
  15. package/dist/chunk-NLOLELZ5.js +6 -0
  16. package/dist/chunk-NLOLELZ5.js.map +7 -0
  17. package/dist/chunk-UO3FYLPX.js +2 -0
  18. package/dist/chunk-UO3FYLPX.js.map +7 -0
  19. package/dist/cli.js +10 -9
  20. package/dist/cli.js.map +3 -3
  21. package/dist/dev-server.js +39 -27
  22. package/dist/dev-server.js.map +4 -4
  23. package/dist/dev-wizard-run-5NOQIMR5.js +2 -0
  24. package/dist/dev-wizard-run-5NOQIMR5.js.map +7 -0
  25. package/dist/mcp.js +1 -1
  26. package/dist/mcp.js.map +3 -3
  27. package/dist/persistent-ink-dev-ui-TLUJJC2D.js +2 -0
  28. package/dist/persistent-ink-dev-ui-TLUJJC2D.js.map +7 -0
  29. package/dist/update-check.js +1 -1
  30. package/package.json +2 -2
  31. package/dist/boot-MTVHM4N7.js +0 -2
  32. package/dist/boot-MTVHM4N7.js.map +0 -7
  33. package/dist/chunk-4MRYIYJP.js +0 -4
  34. package/dist/chunk-4MRYIYJP.js.map +0 -7
  35. package/dist/chunk-6FU2TRU5.js +0 -2
  36. package/dist/chunk-6FU2TRU5.js.map +0 -7
  37. package/dist/chunk-E2SEBLGJ.js +0 -2
  38. package/dist/chunk-E2SEBLGJ.js.map +0 -7
  39. package/dist/chunk-KZP2SY37.js.map +0 -7
  40. package/dist/chunk-NC2TIQ3M.js.map +0 -7
  41. package/dist/chunk-RLZ5IB2E.js +0 -238
  42. package/dist/chunk-RLZ5IB2E.js.map +0 -7
  43. package/dist/chunk-TI33V5G2.js +0 -6
  44. package/dist/chunk-TI33V5G2.js.map +0 -7
  45. package/dist/dev-wizard-run-5HQOGE3R.js +0 -2
  46. package/dist/dev-wizard-run-5HQOGE3R.js.map +0 -7
  47. package/dist/persistent-ink-dev-ui-KOI44ZVT.js +0 -2
  48. package/dist/persistent-ink-dev-ui-KOI44ZVT.js.map +0 -7
@@ -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/**\n * Per-call options for {@link DevRenderer.log}.\n *\n * `tee: false` exists for exactly one caller: `DevServerRunner.reportFault`, which files the fault into the\n * sink ITSELF (at `error` level \u2014 that is what turns the panel row red) and then prints it. Without this\n * opt-out the print tees a SECOND copy into the same `runner.log`, so every fault is filed twice \u2014 a\n * literal 2\u00D7 amplifier sitting at the centre of the loop that wrote 455 GB.\n */\nexport interface LogOptions {\n /** Also append the line to the log file. Default `true`; `false` prints without filing. */\n tee?: boolean\n}\n\n/**\n * A row's liveness, as the runner's probe state machine resolved it.\n *\n * Five arms, not a boolean, because a probe has three outcomes and a row has a history. The two that\n * are neither `ok` nor `down` are the honest ones: a UI that has never answered yet is `starting`\n * (vite is spawned after the ready frame, so red would be a lie for the first seconds), and a port that\n * answers something OTHER than vite's ping is `unverified` \u2014 a squatter, a shadowing proxy, or a future\n * vite that dropped the endpoint are all consistent with that, and only one of them is broken. Red must\n * stay a PROOF of failure, so `unverified` renders a question mark and never a red dot.\n */\nexport type HealthState = 'ok' | 'down' | 'starting' | 'unverified' | 'unknown'\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, as {@link HealthState} defines it; `unknown` renders no dot at all (nothing to probe). */\n health: HealthState\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/**\n * A route that wanted a local backend and is falling back to cloud because that backend failed to start.\n *\n * It gets a row of its own \u2014 not a footnote on the failed backend's row \u2014 because the two facts land on\n * different people. `client/api \u25CF failed` says a server is down, which reads as \"that half is broken\".\n * It does NOT say the frontend beside it came up healthy and is now sending every `/api` request to the\n * shared cloud backend. That second fact is the one that gets you writing to the cloud dev database\n * while you believe you are on localhost, and it is invisible everywhere else on the screen: the vite\n * proxy resolved cleanly, so nothing else has anything to complain about.\n *\n * Only rendered under `--watch` \u2014 without it the run is refused outright (see `local-pairing.ts`).\n */\nexport interface DegradedRow {\n /** Route path (e.g. `/api`). */\n route: string\n /** Stream tag of the frontend serving it, e.g. `client/ui`. */\n tag: string\n /**\n * Where the route ACTUALLY resolves now. Not always `cloud`: the helper falls back to\n * `route.default ?? route.from[0]`, so a single-source `from: ['local']` route with no `default` falls\n * back to `local` \u2014 at an alias nothing registered, i.e. a 502 on every request. The row must name the\n * real destination, or it is doing the same lying-by-omission it exists to prevent.\n */\n fallback: 'local' | 'cloud'\n /** The cloud origin it now resolves to. Only ever set when `fallback` is `cloud` and it is knowable. */\n target?: 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 /**\n * Routes silently demoted from local to cloud by a backend that failed to start. Recomputed on every\n * repaint, so a route CLEARS from the panel the moment `--watch` gets its backend up (see\n * {@link DegradedRow}).\n */\n degraded?: DegradedRow[]\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', options: LogOptions = {}): void {\n if (level !== 'debug' || this.deps.verbose) {\n this.emit(message)\n }\n if (options.tee !== false) {\n this.tee(message, level)\n }\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.\n *\n * Non-zero is BOLD red, and that is not decoration. A frontend that fails to compile still serves and\n * still answers vite's ping, so its dot stays green \u2014 the dot is liveness, and the app IS alive. This\n * counter is the only thing on the screen that says the app is nevertheless broken, so it has to win a\n * glance against a green dot sitting two columns away.\n */\n private errorCount(errors: number): string {\n const text = `\u26A0 ${errors}`\n\n return errors > 0 ? this.color(`${ANSI.bold}${ANSI.red}`, text) : this.color(ANSI.dim, text)\n }\n\n /**\n * The padded tag gutter for a PANEL row \u2014 red once the row has declared an error, teal otherwise.\n *\n * Footer only, never {@link formatHeaderLines}. The header is committed once through Ink's `<Static>`,\n * so a tag reddened there would be a photograph of the boot: it could never turn red later, and \u2014 far\n * worse \u2014 could never turn back. The panel repaints, so the color tracks the fact.\n */\n private tagCell(tag: string, tagWidth: number, errors: number | undefined): string {\n return this.color((errors ?? 0) > 0 ? ANSI.red : ANSI.teal, tag.padEnd(tagWidth))\n }\n\n /** Format the health dot for an endpoint row \u2014 one arm per {@link HealthState}; `unknown` prints nothing. */\n private healthDot(health: HealthState): string {\n switch (health) {\n case 'ok':\n return this.color(ANSI.green, '\u25CF ok')\n case 'down':\n return this.color(ANSI.red, '\u25CF down')\n case 'starting':\n return this.color(ANSI.dim, '\u25CC starting')\n // Answering, but not with vite's ping. Dim, never red: a non-204 is equally consistent with a\n // broken squatter and a perfectly healthy vite behind something that shadows the ping, and a red\n // dot on a coin-flip is how a dot stops being read at all.\n case 'unverified':\n return this.color(ANSI.dim, '\u25CD ?')\n default:\n return ''\n }\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 // A degraded row's gutter is `<tag> <route>`, which is wider than any bare tag \u2014 measure the label\n // it actually prints or its `\u25CF cloud \u2026` cell would sit out of column with every row above it.\n ...(summary.degraded ?? []).map((d) => {\n return `${d.tag} ${d.route}`\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.health) : ''\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 * One degraded-route row (`\u26A0 /api \u25CF cloud (local backend failed) https://dev.hulyo.co.il`).\n *\n * Tagged by ROUTE, not by app, and deliberately so: the app rows above already say what is up and what\n * is down, and neither of them can say \"the frontend that came up healthy is talking to cloud\". The\n * route is the thing that got redirected, so the route is what the row is about.\n */\n private degradedLine(row: DegradedRow, tagWidth: number): string {\n const label = `${row.tag} ${row.route}`\n // A `local` fallback is not a cloud proxy \u2014 it is a dead alias that 502s. Saying \"cloud\" there would\n // name a destination the traffic never reaches.\n const state = row.fallback === 'cloud' ? '\u25CF cloud (local backend down)' : '\u25CF dead alias (local backend down)'\n const target = row.target ? ` ${this.color(ANSI.dim, row.target)}` : ''\n\n return ` ${this.color(ANSI.red, '\u26A0')} ${this.color(ANSI.teal, label.padEnd(tagWidth))} ${this.color(\n ANSI.red,\n state,\n )}${target}`\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 // Below the app rows, because it is a consequence of one of them \u2014 a `\u25CF failed` backend is WHY a\n // route went to cloud, and the two read as cause and effect only in that order.\n for (const d of summary.degraded ?? []) {\n lines.push(this.degradedLine(d, tagWidth))\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.health)\n const status = this.statusFields(e)\n const cells = [dot, status].filter(Boolean).join(' ')\n\n return ` ${this.tagCell(e.tag, tagWidth, e.errors)} ${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.tagCell(ref.tag, tagWidth, ref.errors)} ${this.errorCount(ref.errors)}`)\n }\n\n // Degraded routes live in the PANEL, not only in the header. The header is committed once through\n // `<Static>` \u2014 a photograph \u2014 so a degraded row painted only there would still be on screen after\n // `--watch` brought the backend back and the route went local again: a permanent warning about a\n // condition that has been fixed, which trains the user to ignore it. The caller re-derives this list\n // from the running set on every tick, so the row survives exactly as long as the problem does.\n for (const d of summary.degraded ?? []) {\n rows.push(this.degradedLine(d, tagWidth))\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,eAgLpB,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,EAAQC,GACL,OAAOA,CAAC,EAAE,SAAS,EAAG,GAAG,EAIrBC,EAAeC,GACnB,GAAGH,EA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"formatElapsed", "ms", "formatUptime", "total", "hours", "minutes", "seconds", "resolveEndpointUrl", "input", "DevRenderer", "deps", "text", "code", "href", "label", "c", "message", "level", "line", "options", "frame", "phase", "errors", "tag", "tagWidth", "health", "summary", "lines", "e", "u", "f", "w", "t", "meta", "failedCount", "elapsed", "status", "watchText", "logLink", "watchLine", "rule", "ref", "errText", "endpoint", "parts", "withHealthDot", "dot", "suffix", "failed", "row", "state", "target", "rows", "cells", "beat", "ts"]
7
+ }
@@ -0,0 +1,2 @@
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
@@ -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 = (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,I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G,GALAT,EAAW,CAAE,YAAaH,EAAO,cAAAY,EAAe,cAAe,IAAK,CAAC,EAKjE,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", "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
+ }
package/dist/cli.js CHANGED
@@ -1,13 +1,14 @@
1
1
  #!/usr/bin/env node
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(`
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-AJW5M44V.js";import{r as re}from"./chunk-7F5YKMWK.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-FTCM2766.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-IPF7ILCB.js";import{P as X,Q as Le,S as _e,m as Ne,v as l}from"./chunk-KHEUED4B.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}
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(`
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
+ `),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(`
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
10
  ${u}
10
- `),l.childStarted();let f=await Pr(d,o,()=>{n=!0});r(`
11
+ `),c.childStarted();let f=await Vr(m,o,()=>{n=!0});r(`
11
12
  ${f}
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();
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
14
  //# sourceMappingURL=cli.js.map