infra-kit 0.1.130 → 0.1.131

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 (61) hide show
  1. package/dist/boot-5GFZBDKL.js +2 -0
  2. package/dist/boot-5GFZBDKL.js.map +7 -0
  3. package/dist/chunk-4UUVKJYG.js +2 -0
  4. package/dist/chunk-4UUVKJYG.js.map +7 -0
  5. package/dist/chunk-52WL2IQX.js +4 -0
  6. package/dist/chunk-52WL2IQX.js.map +7 -0
  7. package/dist/chunk-6FU2TRU5.js +2 -0
  8. package/dist/chunk-6FU2TRU5.js.map +7 -0
  9. package/dist/{chunk-Q36WX5RP.js → chunk-6YAKVQZN.js} +3 -3
  10. package/dist/{chunk-Q36WX5RP.js.map → chunk-6YAKVQZN.js.map} +2 -2
  11. package/dist/chunk-C2HRONYA.js +6 -0
  12. package/dist/chunk-C2HRONYA.js.map +7 -0
  13. package/dist/chunk-CHETBZ6M.js +3 -0
  14. package/dist/{chunk-V375VXOL.js.map → chunk-CHETBZ6M.js.map} +4 -4
  15. package/dist/chunk-F6VCGS3D.js +2 -0
  16. package/dist/chunk-F6VCGS3D.js.map +7 -0
  17. package/dist/chunk-LENH44GY.js +215 -0
  18. package/dist/chunk-LENH44GY.js.map +7 -0
  19. package/dist/chunk-LTKR3F4N.js +2 -0
  20. package/dist/chunk-LTKR3F4N.js.map +7 -0
  21. package/dist/chunk-O3YJM6IR.js +2 -0
  22. package/dist/chunk-O3YJM6IR.js.map +7 -0
  23. package/dist/chunk-SR2GFEY7.js +2 -0
  24. package/dist/chunk-SR2GFEY7.js.map +7 -0
  25. package/dist/chunk-TKZINCST.js +2 -0
  26. package/dist/chunk-TKZINCST.js.map +7 -0
  27. package/dist/chunk-VJPLVBRA.js +5 -0
  28. package/dist/chunk-VJPLVBRA.js.map +7 -0
  29. package/dist/chunk-X2L4F2VM.js +3 -0
  30. package/dist/chunk-X2L4F2VM.js.map +7 -0
  31. package/dist/cli.js +4 -19
  32. package/dist/cli.js.map +4 -4
  33. package/dist/dev-server.js +20 -11
  34. package/dist/dev-server.js.map +4 -4
  35. package/dist/dev-wizard-run-7HEKSAS2.js +2 -0
  36. package/dist/dev-wizard-run-7HEKSAS2.js.map +7 -0
  37. package/dist/lib/release-slug/release-slug.d.ts +26 -2
  38. package/dist/lib/vite/vite.d.ts +17 -4
  39. package/dist/mcp.js +1 -1
  40. package/dist/mcp.js.map +3 -3
  41. package/dist/persistent-ink-dev-ui-4U4B2B7C.js +8 -0
  42. package/dist/persistent-ink-dev-ui-4U4B2B7C.js.map +7 -0
  43. package/dist/program.js +2 -0
  44. package/dist/program.js.map +7 -0
  45. package/dist/update-check.js +2 -0
  46. package/dist/update-check.js.map +7 -0
  47. package/dist/vite.js +1 -1
  48. package/package.json +5 -2
  49. package/dist/boot-SGM5RVLJ.js +0 -2
  50. package/dist/boot-SGM5RVLJ.js.map +0 -7
  51. package/dist/chunk-2PZRQHWF.js +0 -2
  52. package/dist/chunk-2PZRQHWF.js.map +0 -7
  53. package/dist/chunk-4YU4TAGX.js +0 -3
  54. package/dist/chunk-4YU4TAGX.js.map +0 -7
  55. package/dist/chunk-AP63Y7KE.js +0 -159
  56. package/dist/chunk-AP63Y7KE.js.map +0 -7
  57. package/dist/chunk-V375VXOL.js +0 -5
  58. package/dist/chunk-YGCVOVNX.js +0 -2
  59. package/dist/chunk-YGCVOVNX.js.map +0 -7
  60. package/dist/dev-wizard-run-LYNLPQMV.js +0 -2
  61. package/dist/dev-wizard-run-LYNLPQMV.js.map +0 -7
@@ -0,0 +1,2 @@
1
+ import{render as ae}from"ink";import U from"node:process";import{Box as k,Text as w,useApp as X,useInput as Y}from"ink";import{useEffect as Z,useState as D}from"react";import{useMemo as O,useState as G}from"react";var M=(t,e)=>{let[n,h]=G(""),[x,g]=G(0),m=O(()=>{let p=n.trim().toLowerCase();return p?t.filter(i=>e(i).toLowerCase().includes(p)):t},[t,n,e]),a=Math.min(x,Math.max(0,m.length-1));return{filtered:m,activeIndex:a,query:n,handleNavigation:(p,i)=>{let c=m.length;return i.upArrow?(c>0&&g((a-1+c)%c),!0):i.downArrow?(c>0&&g((a+1)%c),!0):i.backspace||i.delete?(h(n.slice(0,-1)),g(0),!0):p&&!i.ctrl&&!i.meta?(h(n+p),g(0),!0):!1}}};import{jsx as y,jsxs as $}from"react/jsx-runtime";var Q=t=>{let{items:e,onSubmit:n,onCancel:h,required:x=!0,allowSelectAll:g=!0}=t,m={hint:"Select branches \u2014 type to filter, \u2191\u2193 to move, Space to toggle, Ctrl-A all, Enter to submit, Esc to cancel",prompt:"\u276F ",empty:"No matching branches",requiredHint:"select at least one"},a=e.reduce((s,f)=>Math.max(s,f.label.length),0),{exit:b}=X(),{filtered:p,activeIndex:i,query:c,handleNavigation:v}=M(e,_),[o,u]=D(()=>new Set),[P,A]=D(!1),[B,l]=D(!1);Z(()=>{B&&b()},[B,b]);let r=s=>{u(f=>{let d=new Set(f);return d.has(s)?d.delete(s):d.add(s),d})},C=()=>{u(s=>e.every(d=>s.has(d.value))?new Set:new Set(e.map(d=>d.value)))},E=()=>{if(x&&o.size===0){A(!0);return}n([...o]),l(!0)};return Y((s,f)=>{if(!B){if(f.escape||f.ctrl&&s==="c"){h(),l(!0);return}if(f.ctrl&&s==="a"){g&&C();return}if(s===" "){let d=p[i];d&&r(d.value);return}if(f.return){E();return}v(s,f)}}),B?null:$(k,{flexDirection:"column",children:[y(w,{dimColor:!0,children:m.hint}),$(k,{children:[y(w,{color:"cyan",children:m.prompt}),y(w,{children:c})]}),y(k,{flexDirection:"column",marginTop:1,children:p.length===0?y(w,{dimColor:!0,children:m.empty}):p.map((s,f)=>{let d=f===i,V=o.has(s.value);return $(w,{color:d?"green":void 0,children:[d?"\u203A ":" ",V?"[x] ":"[ ] ",s.label.padEnd(a)," ",y(w,{dimColor:!0,children:s.description??""})]},s.value)})}),P?y(w,{dimColor:!0,children:m.requiredHint}):null]})};function _(t){return`${t.label} ${t.description??""}`}import{Box as F,Text as I,useApp as j,useInput as ee}from"ink";import{useEffect as te,useState as re}from"react";import{jsx as q,jsxs as H}from"react/jsx-runtime";var z=t=>{let{items:e,onSelect:n,onCancel:h}=t,x={hint:"Select a branch \u2014 type to filter, \u2191\u2193 to move, Enter to select, Esc to cancel",prompt:"\u276F ",empty:"No matching branches"},g=e.reduce((o,u)=>Math.max(o,u.label.length),0),{exit:m}=j(),{filtered:a,activeIndex:b,query:p,handleNavigation:i}=M(e,oe),[c,v]=re(!1);return te(()=>{c&&m()},[c,m]),ee((o,u)=>{if(!c){if(u.escape||u.ctrl&&o==="c"){h(),v(!0);return}if(u.return){let P=a[b];P&&(n(P.value),v(!0));return}i(o,u)}}),c?null:H(F,{flexDirection:"column",children:[q(I,{dimColor:!0,children:x.hint}),H(F,{children:[q(I,{color:"cyan",children:x.prompt}),q(I,{children:p})]}),q(F,{flexDirection:"column",marginTop:1,children:a.length===0?q(I,{dimColor:!0,children:x.empty}):a.map((o,u)=>{let P=u===b;return H(I,{color:ne(o.type,P),children:[P?"\u203A ":" ",o.label.padEnd(g)," ",q(I,{dimColor:!0,children:o.description??""})]},o.value)})})]})};function ne(t,e){return t==="hotfix"?"red":e?"green":void 0}function oe(t){return`${t.label} ${t.description??""}`}import{Box as L,Text as S,useApp as ie,useInput as le}from"ink";import{useEffect as ce,useMemo as se,useState as R}from"react";import{jsx as T,jsxs as N}from"react/jsx-runtime";var J=t=>{let{items:e,onSelect:n,onCancel:h}=t,x={hint:"Select a command \u2014 type to filter, \u2191\u2193 to move, Enter to run, Esc to cancel",prompt:"\u276F ",empty:"No matching commands"},g=24,{exit:m}=ie(),[a,b]=R(""),[p,i]=R(0),[c,v]=R(!1);ce(()=>{c&&m()},[c,m]);let o=se(()=>{let l=a.trim().toLowerCase();return l?e.filter(r=>`${r.name} ${r.description}`.toLowerCase().includes(l)):e},[e,a]),u=Math.min(p,Math.max(0,o.length-1)),P=()=>{h(),v(!0)},A=l=>{let r=o.length;r>0&&i((u+l+r)%r)};if(le((l,r)=>{if(!c){if(r.ctrl&&l==="c"){P();return}if(r.escape&&a){b(""),i(0);return}if(r.escape){P();return}if(r.return){let C=o[u];C&&(n(C.name),v(!0));return}if(r.upArrow){A(-1);return}if(r.downArrow){A(1);return}if(r.backspace||r.delete){b(a.slice(0,-1)),i(0);return}l&&!r.ctrl&&!r.meta&&(b(a+l),i(0))}}),c)return null;let B="";return N(L,{flexDirection:"column",children:[T(S,{dimColor:!0,children:x.hint}),N(L,{children:[T(S,{color:"cyan",children:x.prompt}),T(S,{children:a})]}),T(L,{flexDirection:"column",marginTop:1,children:o.length===0?T(S,{dimColor:!0,children:x.empty}):o.map((l,r)=>{let C=r===u,E=l.group!==B;return B=l.group,N(L,{flexDirection:"column",children:[E&&r>0?T(S,{children:" "}):null,E?T(S,{color:"yellow",children:`\u2014 ${l.group} \u2014`}):null,N(S,{color:C?"green":void 0,children:[C?"\u203A ":" ",l.name.padEnd(g)," ",T(S,{dimColor:!0,children:l.description})]})]},l.name)})})]})};import{jsx as K}from"react/jsx-runtime";var W=async t=>{let{waitUntilExit:e}=ae(t,{stdout:U.stderr});try{await e()}catch{}finally{U.stdin.ref()}},Me=async t=>{let e=null;return await W(K(J,{items:t,onSelect:n=>{e=n},onCancel:()=>{e=null}})),e},Le=async t=>{let e=null;return await W(K(z,{items:t,onSelect:n=>{e=n},onCancel:()=>{e=null}})),e},Ne=async(t,e)=>{let n=null;return await W(K(Q,{items:t,required:e?.required,allowSelectAll:e?.allowSelectAll,onSubmit:h=>{n=h},onCancel:()=>{n=null}})),n};export{Ne as runBranchMultiPicker,Le as runBranchPicker,Me as runCommandPalette};
2
+ //# sourceMappingURL=boot-5GFZBDKL.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/tui/boot.tsx", "../src/tui/screens/branch-multi-picker.tsx", "../src/tui/hooks/use-list-filter.ts", "../src/tui/screens/branch-picker.tsx", "../src/tui/screens/command-palette.tsx"],
4
+ "sourcesContent": ["import { render } from 'ink'\nimport process from 'node:process'\nimport type { ReactElement } from 'react'\n\nimport type { BranchPickerItem } from 'src/lib/prompts/types'\n\nimport { BranchMultiPicker } from './screens/branch-multi-picker'\nimport { BranchPicker } from './screens/branch-picker'\nimport { CommandPalette } from './screens/command-palette'\nimport type { PaletteItem } from './types'\n\n/**\n * Entry point for the Ink TUI. This module (and everything under `src/tui/`) is\n * the ONLY place allowed to import `ink`/`react`; it is reached exclusively via a\n * dynamic `await import('src/tui/boot')` from the TTY branch of entry/cli.ts, so\n * React never loads on the MCP / `--json` / non-TTY paths. Build splitting keeps\n * it in a separate lazy chunk (see scripts/build.js).\n */\n\n/**\n * Render an Ink element to stderr and resolve once it tears down. Frames are\n * written to stderr so stdout stays clean for the command that runs afterwards\n * (mirrors the previous Inquirer menu).\n *\n * Ink `unref()`s process.stdin when it tears down raw mode on exit. That ref is\n * process-wide and never restored, so the next consumer of stdin \u2014 the Inquirer\n * prompt the selected command opens (e.g. the worktrees-remove checkbox), or a\n * SECOND Ink render in the same process (the bare-menu palette \u2192 picker hop) \u2014\n * reads from an unref'd handle that no longer keeps the event loop alive. Once\n * the command's git/gh subprocesses settle, the loop drains mid-prompt, Node\n * flags entry/cli.ts's top-level await as unsettled, and the process exits with\n * code 13 (the prompt dies on arrival). Re-ref stdin on BOTH the resolve and the\n * reject path so it holds the loop while the next prompt is reading; an idle\n * ref'd stdin does not block exit, so non-interactive follow-up commands still\n * terminate normally. Every render must go through here so the re-ref is never\n * skipped.\n */\nconst renderToStderr = async (element: ReactElement): Promise<void> => {\n const { waitUntilExit } = render(element, {\n stdout: process.stderr as unknown as NodeJS.WriteStream,\n })\n\n try {\n await waitUntilExit()\n } catch {\n // Swallow a teardown rejection: the caller reports cancellation via its own\n // captured sentinel (which stays at its initial value), not via a throw.\n } finally {\n process.stdin.ref()\n }\n}\n\n/**\n * Render the command palette and resolve to the chosen command name, or `null`\n * if the user cancels.\n */\nexport const runCommandPalette = async (items: PaletteItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <CommandPalette\n items={items}\n onSelect={(name) => {\n selected = name\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable single-select branch picker and resolve to the chosen\n * value, or `null` if the user cancels.\n */\nexport const runBranchPicker = async (items: BranchPickerItem[]): Promise<string | null> => {\n let selected: string | null = null\n\n await renderToStderr(\n <BranchPicker\n items={items}\n onSelect={(value) => {\n selected = value\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n\n/**\n * Render the searchable multi-select branch picker and resolve to the chosen\n * values, or `null` if the user cancels. The captured variable starts as `null`\n * and is only assigned an array in `onSubmit`, so a cancel is distinguishable\n * from an empty submit.\n */\nexport const runBranchMultiPicker = async (\n items: BranchPickerItem[],\n opts?: { required?: boolean; allowSelectAll?: boolean },\n): Promise<string[] | null> => {\n let selected: string[] | null = null\n\n await renderToStderr(\n <BranchMultiPicker\n items={items}\n required={opts?.required}\n allowSelectAll={opts?.allowSelectAll}\n onSubmit={(values) => {\n selected = values\n }}\n onCancel={() => {\n selected = null\n }}\n />,\n )\n\n return selected\n}\n", "import { Box, Text, useApp, useInput } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\n\ninterface BranchMultiPickerProps {\n items: BranchPickerItem[]\n /** Called with the selected item values; the app then exits. */\n onSubmit: (values: string[]) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n /** When true (default), Enter with an empty selection is ignored. */\n required?: boolean\n /** When true (default), Ctrl-A toggles select-all across all items. */\n allowSelectAll?: boolean\n}\n\n/**\n * Searchable multi-select branch picker rendered with Ink. Same filter/move/cancel\n * behaviour as `BranchPicker`, plus a selection `Set` keyed by item *value* so the\n * selection survives filter changes. Space toggles the active row; Ctrl-A toggles\n * select-all across all items; Enter submits the selected values.\n */\nexport const BranchMultiPicker = (props: BranchMultiPickerProps) => {\n const { items, onSubmit, onCancel, required = true, allowSelectAll = true } = props\n\n const T = {\n hint: 'Select branches \u2014 type to filter, \u2191\u2193 to move, Space to toggle, Ctrl-A all, Enter to submit, Esc to cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n requiredHint: 'select at least one',\n }\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { filtered, activeIndex, query, handleNavigation } = useListFilter(items, filterText)\n // Selection keyed by value so it persists across filter changes.\n const [selected, setSelected] = useState<Set<string>>(() => {\n return new Set()\n })\n const [showRequiredHint, setShowRequiredHint] = useState(false)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const toggleValue = (value: string) => {\n setSelected((prev) => {\n const next = new Set(prev)\n\n if (next.has(value)) {\n next.delete(value)\n } else {\n next.add(value)\n }\n\n return next\n })\n }\n\n const toggleSelectAll = () => {\n setSelected((prev) => {\n // Clear only when every item (all, not just filtered) is already selected.\n const allSelected = items.every((item) => {\n return prev.has(item.value)\n })\n\n if (allSelected) {\n return new Set()\n }\n\n return new Set(\n items.map((item) => {\n return item.value\n }),\n )\n })\n }\n\n const submit = () => {\n if (required && selected.size === 0) {\n setShowRequiredHint(true)\n\n return\n }\n\n onSubmit([...selected])\n setSubmitted(true)\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.escape || (key.ctrl && input === 'c')) {\n onCancel()\n setSubmitted(true)\n\n return\n }\n\n if (key.ctrl && input === 'a') {\n if (allowSelectAll) {\n toggleSelectAll()\n }\n\n return\n }\n\n if (input === ' ') {\n const active = filtered[activeIndex]\n\n if (active) {\n toggleValue(active.value)\n }\n\n return\n }\n\n if (key.return) {\n submit()\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n return (\n <Box flexDirection=\"column\">\n <Text dimColor>{T.hint}</Text>\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n <Text>{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={1}>\n {filtered.length === 0 ? (\n <Text dimColor>{T.empty}</Text>\n ) : (\n filtered.map((item, position) => {\n const isActive = position === activeIndex\n const isChecked = selected.has(item.value)\n\n return (\n <Text color={isActive ? 'green' : undefined} key={item.value}>\n {isActive ? '\u203A ' : ' '}\n {isChecked ? '[x] ' : '[ ] '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })\n )}\n </Box>\n {showRequiredHint ? <Text dimColor>{T.requiredHint}</Text> : null}\n </Box>\n )\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n", "import type { Key } from 'ink'\nimport { useMemo, useState } from 'react'\n\ninterface ListFilter<T> {\n /** Items matching the current query (all items when the query is empty). */\n filtered: T[]\n /** Active row index, always clamped into `filtered`'s bounds. */\n activeIndex: number\n /** Current filter query. */\n query: string\n /**\n * Handle the shared navigation/filter keys (\u2191\u2193 wrap-around, backspace/delete,\n * printable chars). Returns true when the key was consumed so the caller can\n * `return` early; false leaves the key for the component's own handlers.\n */\n handleNavigation: (input: string, key: Key) => boolean\n}\n\n/**\n * Shared list-filter state for the branch pickers: substring filtering,\n * wrap-around \u2191\u2193 movement, and query editing. Extracted so each `useInput`\n * handler stays under the sonarjs cognitive-complexity \u226415 gate.\n */\nexport const useListFilter = <T>(items: T[], toText: (item: T) => string): ListFilter<T> => {\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return toText(item).toLowerCase().includes(q)\n })\n }, [items, query, toText])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n const handleNavigation = (input: string, key: Key): boolean => {\n const n = filtered.length\n\n if (key.upArrow) {\n // `+ n` sidesteps JS negative modulo (e.g. -1 % 5 === -1, not 4).\n if (n > 0) {\n setIndex((activeIndex - 1 + n) % n)\n }\n\n return true\n }\n\n if (key.downArrow) {\n if (n > 0) {\n setIndex((activeIndex + 1) % n)\n }\n\n return true\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return true\n }\n\n // Printable character: append to the filter and reset to the first row.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n\n return true\n }\n\n return false\n }\n\n return { filtered, activeIndex, query, handleNavigation }\n}\n", "import { Box, Text, useApp, useInput } from 'ink'\nimport { useEffect, useState } from 'react'\n\nimport type { BranchPickerItem } from '../../lib/prompts/types'\nimport { useListFilter } from '../hooks/use-list-filter'\n\ninterface BranchPickerProps {\n items: BranchPickerItem[]\n /** Called with the chosen item's value; the app then exits. */\n onSelect: (value: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n}\n\n/**\n * Searchable single-select branch picker rendered with Ink. Mirrors\n * `CommandPalette` minus the group headers: type-to-filter over label +\n * description, \u2191\u2193 wrap-around, Enter selects the active item's *value*.\n */\nexport const BranchPicker = (props: BranchPickerProps) => {\n const { items, onSelect, onCancel } = props\n\n const T = {\n hint: 'Select a branch \u2014 type to filter, \u2191\u2193 to move, Enter to select, Esc to cancel',\n prompt: '\u276F ',\n empty: 'No matching branches',\n }\n const labelWidth = items.reduce((max, item) => {\n return Math.max(max, item.label.length)\n }, 0)\n\n const { exit } = useApp()\n const { filtered, activeIndex, query, handleNavigation } = useListFilter(items, filterText)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame.\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n if (key.escape || (key.ctrl && input === 'c')) {\n onCancel()\n setSubmitted(true)\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.value)\n setSubmitted(true)\n }\n\n return\n }\n\n handleNavigation(input, key)\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n return (\n <Box flexDirection=\"column\">\n <Text dimColor>{T.hint}</Text>\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n <Text>{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={1}>\n {filtered.length === 0 ? (\n <Text dimColor>{T.empty}</Text>\n ) : (\n filtered.map((item, position) => {\n const isActive = position === activeIndex\n\n return (\n <Text color={labelColor(item.type, isActive)} key={item.value}>\n {isActive ? '\u203A ' : ' '}\n {item.label.padEnd(labelWidth)} <Text dimColor>{item.description ?? ''}</Text>\n </Text>\n )\n })\n )}\n </Box>\n </Box>\n )\n}\n\n/**\n * Colour for a row's label, derived from the release type. Kept a plain lookup so\n * an unknown/absent type simply falls through to the default (green when active).\n */\nfunction labelColor(type: string | undefined, isActive: boolean): string | undefined {\n if (type === 'hotfix') {\n return 'red'\n }\n\n return isActive ? 'green' : undefined\n}\n\nfunction filterText(item: BranchPickerItem): string {\n return `${item.label} ${item.description ?? ''}`\n}\n", "import { Box, Text, useApp, useInput } from 'ink'\nimport { useEffect, useMemo, useState } from 'react'\n\nimport type { PaletteItem } from '../types'\n\ninterface CommandPaletteProps {\n items: PaletteItem[]\n /** Called with the chosen command name; the app then exits. */\n onSelect: (name: string) => void\n /** Called when the user cancels (Esc / Ctrl-C); the app then exits. */\n onCancel: () => void\n}\n\n/**\n * Fuzzy-ish command picker rendered with Ink. Pure presentation: it receives a\n * flat list of commands (already grouped/ordered by the catalog) and returns the\n * selected name. It never executes anything \u2014 the caller runs the command via\n * the existing Commander path.\n */\nexport const CommandPalette = (props: CommandPaletteProps) => {\n const { items, onSelect, onCancel } = props\n\n const T = {\n hint: 'Select a command \u2014 type to filter, \u2191\u2193 to move, Enter to run, Esc to cancel',\n prompt: '\u276F ',\n empty: 'No matching commands',\n }\n const nameWidth = 24\n\n const { exit } = useApp()\n const [query, setQuery] = useState('')\n const [index, setIndex] = useState(0)\n // When set, the component renders `null` for one frame so Ink erases the list\n // before unmount commits its final frame (Ink's `log.done()` would otherwise\n // freeze the last drawn frame \u2014 the command list \u2014 into the scrollback).\n const [submitted, setSubmitted] = useState(false)\n\n // Exit only after the empty frame has committed, so the list is wiped first.\n useEffect(() => {\n if (submitted) {\n exit()\n }\n }, [submitted, exit])\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase()\n\n if (!q) {\n return items\n }\n\n return items.filter((item) => {\n return `${item.name} ${item.description}`.toLowerCase().includes(q)\n })\n }, [items, query])\n\n const activeIndex = Math.min(index, Math.max(0, filtered.length - 1))\n\n // Back out with nothing picked (Ctrl-C, or Esc on an empty filter).\n const quit = () => {\n onCancel()\n setSubmitted(true)\n }\n\n // Move the active row by `delta`, wrapping. The `+ n` sidesteps JS negative modulo\n // (e.g. -1 % 5 === -1, not 4). No-op on an empty list.\n const step = (delta: number) => {\n const n = filtered.length\n\n if (n > 0) {\n setIndex((activeIndex + delta + n) % n)\n }\n }\n\n useInput((input, key) => {\n if (submitted) {\n return\n }\n\n // Ctrl-C always quits; Esc clears a non-empty filter first, and only quits on an empty filter \u2014\n // the standard REPL/palette split, so the session shell keeps running while the user narrows.\n if (key.ctrl && input === 'c') {\n quit()\n\n return\n }\n\n if (key.escape && query) {\n setQuery('')\n setIndex(0)\n\n return\n }\n\n if (key.escape) {\n quit()\n\n return\n }\n\n if (key.return) {\n const selected = filtered[activeIndex]\n\n if (selected) {\n onSelect(selected.name)\n setSubmitted(true)\n }\n\n return\n }\n\n if (key.upArrow) {\n step(-1)\n\n return\n }\n\n if (key.downArrow) {\n step(1)\n\n return\n }\n\n if (key.backspace || key.delete) {\n setQuery(query.slice(0, -1))\n setIndex(0)\n\n return\n }\n\n // Printable character: append to the filter.\n if (input && !key.ctrl && !key.meta) {\n setQuery(query + input)\n setIndex(0)\n }\n })\n\n // Final frame: render nothing so Ink erases the list on its way out.\n if (submitted) {\n return null\n }\n\n let lastGroup = ''\n\n return (\n <Box flexDirection=\"column\">\n <Text dimColor>{T.hint}</Text>\n <Box>\n <Text color=\"cyan\">{T.prompt}</Text>\n <Text>{query}</Text>\n </Box>\n <Box flexDirection=\"column\" marginTop={1}>\n {filtered.length === 0 ? (\n <Text dimColor>{T.empty}</Text>\n ) : (\n filtered.map((item, position) => {\n const isActive = position === activeIndex\n const showGroup = item.group !== lastGroup\n\n lastGroup = item.group\n\n return (\n <Box flexDirection=\"column\" key={item.name}>\n {/* Blank line between groups (not before the very first group). */}\n {showGroup && position > 0 ? <Text> </Text> : null}\n {showGroup ? <Text color=\"yellow\">{`\u2014 ${item.group} \u2014`}</Text> : null}\n <Text color={isActive ? 'green' : undefined}>\n {isActive ? '\u203A ' : ' '}\n {item.name.padEnd(nameWidth)} <Text dimColor>{item.description}</Text>\n </Text>\n </Box>\n )\n })\n )}\n </Box>\n </Box>\n )\n}\n"],
5
+ "mappings": "AAAA,OAAS,UAAAA,OAAc,MACvB,OAAOC,MAAa,eCDpB,OAAS,OAAAC,EAAK,QAAAC,EAAM,UAAAC,EAAQ,YAAAC,MAAgB,MAC5C,OAAS,aAAAC,EAAW,YAAAC,MAAgB,QCApC,OAAS,WAAAC,EAAS,YAAAC,MAAgB,QAsB3B,IAAMC,EAAgB,CAAIC,EAAYC,IAA+C,CAC1F,GAAM,CAACC,EAAOC,CAAQ,EAAIL,EAAS,EAAE,EAC/B,CAACM,EAAOC,CAAQ,EAAIP,EAAS,CAAC,EAE9BQ,EAAWT,EAAQ,IAAM,CAC7B,IAAMU,EAAIL,EAAM,KAAK,EAAE,YAAY,EAEnC,OAAKK,EAIEP,EAAM,OAAQQ,GACZP,EAAOO,CAAI,EAAE,YAAY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"process", "Box", "Text", "useApp", "useInput", "useEffect", "useState", "useMemo", "useState", "useListFilter", "items", "toText", "query", "setQuery", "index", "setIndex", "filtered", "q", "item", "activeIndex", "input", "key", "n", "jsx", "jsxs", "BranchMultiPicker", "props", "items", "onSubmit", "onCancel", "required", "allowSelectAll", "T", "labelWidth", "max", "item", "exit", "useApp", "filtered", "activeIndex", "query", "handleNavigation", "useListFilter", "filterText", "selected", "setSelected", "useState", "showRequiredHint", "setShowRequiredHint", "submitted", "setSubmitted", "useEffect", "toggleValue", "value", "prev", "next", "toggleSelectAll", "submit", "useInput", "input", "key", "active", "Box", "Text", "position", "isActive", "isChecked", "Box", "Text", "useApp", "useInput", "useEffect", "useState", "jsx", "jsxs", "BranchPicker", "props", "items", "onSelect", "onCancel", "T", "labelWidth", "max", "item", "exit", "useApp", "filtered", "activeIndex", "query", "handleNavigation", "useListFilter", "filterText", "submitted", "setSubmitted", "useState", "useEffect", "useInput", "input", "key", "selected", "Box", "Text", "position", "isActive", "labelColor", "type", "Box", "Text", "useApp", "useInput", "useEffect", "useMemo", "useState", "jsx", "jsxs", "CommandPalette", "props", "items", "onSelect", "onCancel", "T", "nameWidth", "exit", "query", "setQuery", "index", "setIndex", "submitted", "setSubmitted", "filtered", "q", "item", "activeIndex", "quit", "step", "delta", "n", "input", "key", "selected", "lastGroup", "position", "isActive", "showGroup", "jsx", "renderToStderr", "element", "waitUntilExit", "render", "process", "runCommandPalette", "items", "selected", "CommandPalette", "name", "runBranchPicker", "BranchPicker", "value", "runBranchMultiPicker", "opts", "BranchMultiPicker", "values"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{a as v,b as P,c as y}from"./chunk-LTKR3F4N.js";import{Buffer as w}from"node:buffer";import{execFileSync as A}from"node:child_process";import f from"node:fs";import E from"node:net";import u from"node:path";import g from"node:process";import{pathToFileURL as K}from"node:url";import{z as l}from"zod";import{z as i}from"zod";var k=i.strictObject({requiredScripts:i.array(i.string().min(1)).optional(),requiredFiles:i.array(i.string().min(1)).optional(),turbo:i.strictObject({requiredTasks:i.array(i.string().min(1)).optional()}).optional(),dev:i.strictObject({proxy:i.strictObject({templates:i.strictObject({local:i.string().min(1),cloud:i.string().min(1)}),routes:i.record(i.string().min(1),i.strictObject({packageName:i.string().min(1),from:i.array(i.enum(["local","cloud"])).min(1),default:i.enum(["local","cloud"]).optional()}).refine(e=>e.from.length<=1||e.default!==void 0,{message:"default is required when `from` has more than one source"}).refine(e=>e.default===void 0||e.from.includes(e.default),{message:"default must be listed in `from`"}))}).optional()}).optional()});var R="INFRA_KIT_ENV",h="infra-kit.config.ts",D=u.join(".infra-kit","dev-context"),N=u.join(".infra-kit","dev-context.json"),_=l.object({package:l.string(),port:l.number(),pid:l.number().optional(),writtenAt:l.number().optional(),release:l.string().optional(),alias:l.string().optional(),proxyPort:l.number().optional()}),L=(e,t)=>{let r=t?.username??e.E2E__BASIC_AUTH_USERNAME,n=t?.password??e.E2E__BASIC_AUTH_PASSWORD;return!r||!n?void 0:`Basic ${w.from(`${r}:${n}`).toString("base64")}`};var S=(e,t)=>e.replaceAll("<release>",t.release).replaceAll("<packageName>",t.packageName).replaceAll("<env>",t.env),O=80,T="127.0.0.1",j=(e,t)=>{if(t==null||t===O)return e;let r;try{r=new URL(e)}catch{throw new Error(`infra-kit/vite: dev.proxy templates.local resolved to "${e}", which is not a valid URL, so the proxy port ${t} cannot be applied.`)}if(r.port!=="")return e;r.port=String(t);let n=r.toString();return!e.endsWith("/")&&n.endsWith("/")?n.slice(0,-1):n},F=e=>{let{route:t,templates:r,env:n,getRelease:o,info:a}=e,s=S(r.local,{release:a?.release??o(),packageName:v(t.packageName),env:n??""});return j(s,a?.proxyPort)},C=(e,t)=>{let r=e.default??e.from[0];return e.from.includes("local")&&t.has(e.packageName)?"local":r},U=({routePath:e,route:t,templates:r,localSet:n,env:o,getRelease:a,localInfo:s})=>{if(C(t,n)==="local")return{target:F({route:t,templates:r,env:o,getRelease:a,info:s?.get(t.packageName)}),changeOrigin:!0};if(!o)throw new Error(`infra-kit/vite: proxy route "${e}" resolves to a cloud backend but ${R} is not set. Source an environment from Doppler first (e.g. \`infra-kit env-load -c dev\`).`);return{target:S(r.cloud,{release:"",packageName:t.packageName,env:o}),changeOrigin:!0,secure:!1,cookieDomainRewrite:"localhost"}},V=({proxy:e,localSet:t,env:r,getRelease:n,authHeader:o,localInfo:a})=>{let s={},c=o?{Authorization:o}:void 0;for(let[d,p]of Object.entries(e.routes)){let m=U({routePath:d,route:p,templates:e.templates,localSet:t,env:r,getRelease:n,localInfo:a});s[d]=c?{...m,headers:c}:m}return s},$=e=>{let t;return()=>(t??={value:e()},t.value)},B=async e=>{let t=u.join(e,h);if(!f.existsSync(t))return;let r=f.statSync(t),a=(await import(`${K(t).href}?mtime=${Number(r.mtimeMs)}`)).default;if(a===void 0)return;let s=typeof a=="function"?await a():a,c=k.safeParse(s);if(!c.success)throw new Error(`infra-kit/vite: invalid ${h} at ${t}: ${l.prettifyError(c.error)}`);return c.data.dev},M=e=>{if(Array.isArray(e))return e.filter(t=>typeof t=="string");if(e!==null&&typeof e=="object"){let t=e.packages??e.localPackages;if(Array.isArray(t))return t.filter(r=>typeof r=="string")}return[]},I=(e,t)=>{let r=u.resolve(e);for(;;){let n=u.join(r,t);if(f.existsSync(n))return n;let o=u.dirname(r);if(o===r)return;r=o}},x=()=>({packages:new Set,info:new Map}),H=e=>{if(e==null)return!0;try{return g.kill(e,0),!0}catch(t){return t.code==="EPERM"}},J=e=>{let t;try{t=f.readdirSync(e)}catch{return x()}let r=new Set,n=new Map;for(let o of t)if(o.endsWith(".json"))try{let a=_.safeParse(JSON.parse(f.readFileSync(u.join(e,o),"utf-8")));if(!a.success||!H(a.data.pid))continue;r.add(a.data.package),n.set(a.data.package,{port:a.data.port,release:a.data.release,alias:a.data.alias,proxyPort:a.data.proxyPort})}catch{continue}return{packages:r,info:n}},W=e=>{let t=I(e,D);if(t)return J(t);let r=I(e,N);if(!r)return x();try{return{packages:new Set(M(JSON.parse(f.readFileSync(r,"utf-8")))),info:new Map}}catch{return x()}};var q=e=>A("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf-8"}).trim(),G=()=>new Promise((e,t)=>{let r=E.createServer();r.unref(),r.on("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),o=typeof n=="object"&&n!==null?n.port:0;r.close(()=>e(o))})}),z="INFRA_KIT_UI_PORTS",X=e=>{try{let t=JSON.parse(f.readFileSync(u.join(e,"package.json"),"utf-8"));return typeof t.name=="string"?t.name:null}catch{return null}},Q=e=>{let t=g.env[z];if(t==null||t==="")return null;let r=X(e);if(r==null)return null;try{let o=JSON.parse(t)[r];return typeof o=="number"?o:null}catch{return null}},Y=async(e={})=>{let t=e.cwd??g.cwd();if(e.command==="build")return{proxy:{}};let r=e.port==null?Q(t):null,n=e.port??r??await G(),o=r!=null,a=e.host??T,s=await B(t);if(!s?.proxy)return{port:n,host:a,...o?{strictPort:o}:{},proxy:{}};let{packages:c,info:d}=W(t),p=g.env[R],m=L(g.env,e.basicAuth),b=$(()=>{try{return P(q(t))||y}catch{return y}});return{port:n,host:a,...o?{strictPort:o}:{},proxy:V({proxy:s.proxy,localSet:c,env:p,getRelease:b,authHeader:m,localInfo:d})}},fe=async(e={})=>(await Y(e)).proxy;export{k as a,V as b,B as c,Y as d,fe as e};
2
+ //# sourceMappingURL=chunk-4UUVKJYG.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/vite/vite.ts", "../src/lib/package-config/package-config-schema.ts"],
4
+ "sourcesContent": ["import { Buffer } from 'node:buffer'\nimport { execFileSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport net from 'node:net'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { pathToFileURL } from 'node:url'\nimport { z } from 'zod'\n\nimport type {\n InfraKitDev,\n InfraKitDevProxy,\n InfraKitDevProxyRoute,\n InfraKitDevProxySource,\n} from '../package-config/package-config'\nimport { packageConfigSchema } from '../package-config/package-config-schema'\nimport { DEFAULT_RELEASE_SLUG, slugifyHostLabel, slugifyRelease } from '../release-slug/release-slug'\n\n/**\n * Env-name handle read at vite-config time to fill the `<env>` placeholder in a\n * cloud proxy target. Inlined (not imported from `src/lib/constants`) to keep the\n * `infra-kit/vite` bundle's import graph tiny \u2014 see the module header. Kept\n * byte-identical to `INFRA_KIT_ENV_VAR` in `src/lib/constants/constants.ts`.\n */\nconst INFRA_KIT_ENV = 'INFRA_KIT_ENV'\n\n/** Per-package config filename, mirrored from the CLI's `PACKAGE_CONFIG_FILE`. */\nconst PACKAGE_CONFIG_FILE = 'infra-kit.config.ts'\n\n/**\n * Repo-relative dev-context fragment DIRECTORY, searched upward from cwd. Each\n * runner (single-process or cmux pane) writes its OWN `<app>.json` fragment here\n * recording its real bound port + release; the helper merges them (see\n * {@link readLocalContext}). This is the current source of truth.\n */\nconst DEV_CONTEXT_DIR = path.join('.infra-kit', 'dev-context')\n\n/**\n * Legacy single-file dev-context manifest, searched upward from cwd. Read only as\n * a transitional back-compat path when {@link DEV_CONTEXT_DIR} is absent (the\n * directory wins per-package when both exist).\n */\nconst DEV_CONTEXT_FILE = path.join('.infra-kit', 'dev-context.json')\n\n/**\n * One `.infra-kit/dev-context/<app>.json` fragment. `package` is the load-bearing\n * field the helper reads (\u2192 localSet); `release` lets the helper prefer the\n * runner-recorded slug over its own git derivation, and `proxyPort` is the port the\n * alias resolves on \u2014 see {@link resolveRoute}. `alias` is recorded for provenance;\n * the target is rebuilt from the template, not read from it. `port` is no longer a\n * proxy target (the direct `127.0.0.1:<port>` branch is gone) \u2014 it survives as\n * diagnostic provenance. `pid` is the staleness guard: {@link readFragmentDir} drops a\n * fragment whose writer is no longer alive, so a crashed runner cannot keep a package\n * pinned `local` at a dead alias. `writtenAt` is provenance only. Kept lenient (not\n * `.strict()`) so extra writer fields never reject a valid fragment.\n */\nconst devContextFragmentSchema = z.object({\n package: z.string(),\n port: z.number(),\n pid: z.number().optional(),\n writtenAt: z.number().optional(),\n release: z.string().optional(),\n alias: z.string().optional(),\n proxyPort: z.number().optional(),\n})\n\n/**\n * A single Vite `server.proxy` entry. `changeOrigin` is always set; the\n * cloud-only pair (`secure: false` + `cookieDomainRewrite: 'localhost'`) makes a\n * local FE talk to an HTTPS cloud BE without cert/cookie-domain breakage.\n * `headers` is present only when HTTP Basic Auth is injected (see\n * {@link buildBasicAuthHeader}) \u2014 it carries the `Authorization` header applied\n * uniformly to every route so upstream environments behind auth (e2e/staging)\n * stay reachable.\n */\nexport interface InfraKitViteProxyEntry {\n target: string\n changeOrigin: true\n secure?: false\n cookieDomainRewrite?: 'localhost'\n headers?: Record<string, string>\n}\n\n/** A Vite `server.proxy`-shaped map: path-prefix \u2192 proxy entry. */\nexport type InfraKitViteProxy = Record<string, InfraKitViteProxyEntry>\n\n/** Explicit HTTP Basic Auth credentials, overriding the `E2E__BASIC_AUTH_*` env vars. */\nexport interface InfraKitBasicAuth {\n username: string\n password: string\n}\n\nexport interface InfraKitDevOptions {\n /** Package dir whose `infra-kit.config.ts` is loaded. Defaults to `process.cwd()`. */\n cwd?: string\n /**\n * Explicit HTTP Basic Auth credentials injected into every proxy route as an\n * `Authorization` header. Takes precedence over the `E2E__BASIC_AUTH_USERNAME`\n * / `E2E__BASIC_AUTH_PASSWORD` env vars. Omit to use the env-based default.\n */\n basicAuth?: InfraKitBasicAuth\n /**\n * Vite's `command`. Pass it (`defineConfig(async ({ command }) => ({ server: await infraKitDev({ command }) }))`)\n * so `build` is a no-op: `server` is irrelevant to a build and proxy resolution would otherwise\n * fail-fast on a cloud route with no sourced env. Omit (or `'serve'`) for the dev-server config.\n */\n command?: 'build' | 'serve'\n /**\n * Explicit dev-server port. Omit for a **per-worktree dynamic** free port (a fresh OS-assigned\n * port) so N simultaneous git worktrees never collide on Vite's default `5173`; Vite prints the\n * chosen URL. Pass a fixed number only when an external contract pins the port.\n */\n port?: number\n /**\n * Interface the dev server binds. Defaults to {@link LOOPBACK_V4} so a portless alias can reach it\n * (Vite's own `localhost` default binds `[::1]` only, which the proxy cannot dial). Override when\n * the dev server must be reachable off the loopback \u2014 `'0.0.0.0'` or `true` inside a container, on\n * a LAN, or for an e2e runner on another host.\n */\n host?: string | boolean\n}\n\n/**\n * Build the `Authorization: Basic <base64(user:pass)>` header value. Credentials\n * come from `override` when given, else from `E2E__BASIC_AUTH_USERNAME` /\n * `E2E__BASIC_AUTH_PASSWORD` (NOTE: double underscore). Returns `undefined` when\n * either half is missing, so callers add no `headers` key at all.\n */\nconst buildBasicAuthHeader = (env: NodeJS.ProcessEnv, override?: InfraKitBasicAuth): string | undefined => {\n const username = override?.username ?? env.E2E__BASIC_AUTH_USERNAME\n const password = override?.password ?? env.E2E__BASIC_AUTH_PASSWORD\n\n if (!username || !password) return undefined\n\n const encoded = Buffer.from(`${username}:${password}`).toString('base64')\n\n return `Basic ${encoded}`\n}\n\n/**\n * Re-exported from the shared, dependency-light `lib/release-slug` module so the\n * published `infra-kit/vite` surface (`entry/vite.ts:7`) is unchanged while the\n * dev-server's fragment writer derives `<release>` from the SAME implementation\n * (no slug drift). See {@link slugifyRelease}.\n */\nexport { slugifyRelease }\n\n/** Fill the `<release>`/`<packageName>`/`<env>` placeholders in a URL template. */\nconst interpolate = (template: string, values: { release: string; packageName: string; env: string }): string => {\n return template\n .replaceAll('<release>', values.release)\n .replaceAll('<packageName>', values.packageName)\n .replaceAll('<env>', values.env)\n}\n\n/** The port a bare `http://` target implies, and the proxy's default \u2014 never spelled out in a URL. */\nconst DEFAULT_HTTP_PORT = 80\n\n/**\n * The interface the vite dev server binds. Pinned to IPv4 loopback because portless dials its routes\n * on `127.0.0.1`, while vite's default `host: 'localhost'` combined with its\n * `dns.setDefaultResultOrder('verbatim')` binds `[::1]` ONLY \u2014 the alias then resolves, the proxy\n * connects, and the connection is refused, surfacing as a 502 on every UI request. Backends never hit\n * this because `ServerlessLocalRun` already binds `127.0.0.1`. Still loopback-only: this narrows the\n * address family, it does not expose the dev server to the network.\n */\nconst LOOPBACK_V4 = '127.0.0.1'\n\n/**\n * Graft the proxy's listen port onto an interpolated local target. The `dev.proxy` local template is\n * written port-free (`http://<release>.<packageName>.localhost`) because the proxy defaults to `:80`.\n * A consumer who trades the clean URL for a zero-sudo unprivileged port still needs the frontend to\n * reach it, so the runner records the port it actually bound and we append it here. A template that\n * already pins its own port keeps it.\n */\nconst withProxyPort = (target: string, proxyPort: number | undefined): string => {\n if (proxyPort == null || proxyPort === DEFAULT_HTTP_PORT) return target\n\n let url: URL\n\n try {\n url = new URL(target)\n } catch {\n throw new Error(\n `infra-kit/vite: dev.proxy templates.local resolved to \"${target}\", which is not a valid URL, so the proxy port ${proxyPort} cannot be applied.`,\n )\n }\n\n if (url.port !== '') return target\n url.port = String(proxyPort)\n\n // `URL.toString()` synthesizes a `/` pathname for an authority-only URL, so the common port-free\n // template would come back as `\u2026localhost:1355/`. Strip that ONLY when the template had no trailing\n // slash of its own \u2014 a template ending in `/` (e.g. `\u2026localhost/base/`) means it, and silently\n // trimming it would change the path the frontend proxies to.\n const grafted = url.toString()\n\n return !target.endsWith('/') && grafted.endsWith('/') ? grafted.slice(0, -1) : grafted\n}\n\n/**\n * The proxy target for a route resolved to `local`: always the interpolated template, i.e. the portless\n * hostname the runner aliased. `infra-kit dev` refuses to start an app it could not alias, so membership\n * in the local set now also proves the package is reachable BY NAME \u2014 there is no direct-port target.\n *\n * The target proxies to a stable HOSTNAME, and the runner re-points that alias at the freshly-bound port\n * on every `--watch` restart, so it self-heals without Vite reloading its config.\n */\nconst resolveLocalTarget = (args: {\n route: InfraKitDevProxyRoute\n templates: InfraKitDevProxy['templates']\n env: string | undefined\n getRelease: () => string\n info: LocalPackageInfo | undefined\n}): string => {\n const { route, templates, env, getRelease, info } = args\n\n const target = interpolate(templates.local, {\n // Prefer THIS package's runner-recorded release slug (R4) over the single global git derivation,\n // so cross-branch FE/BE pairings don't drift the emitted `<release>` from the segment the runner\n // aliased. Fall back to the global git slug only when the fragment carried no release.\n release: info?.release ?? getRelease(),\n // The local template resolves to a `<release>.<packageName>.localhost` alias the dev-server\n // registered with portless \u2014 which slugifies the package name to a legal DNS label. Slugify\n // identically here or a scoped name (`@hulyo/client-ui`) emits a target that no alias backs.\n packageName: slugifyHostLabel(route.packageName),\n env: env ?? '',\n })\n\n return withProxyPort(target, info?.proxyPort)\n}\n\n/**\n * Pick the effective source for a route: `local` when the route lists `local` as\n * a capability AND its packageName is in the local dev set; otherwise the fallback\n * \u2014 the declared `default` for a multi-source route, or the sole `from` entry for\n * a single-source one. Always resolves (the schema guarantees a usable fallback).\n */\nconst pickSource = (route: InfraKitDevProxyRoute, localSet: ReadonlySet<string>): InfraKitDevProxySource => {\n // `from` is guaranteed non-empty by the schema, so `from[0]` is always present.\n const fallback = route.default ?? route.from[0]!\n\n return route.from.includes('local') && localSet.has(route.packageName) ? 'local' : fallback\n}\n\ninterface ResolveRouteArgs {\n routePath: string\n route: InfraKitDevProxyRoute\n templates: InfraKitDevProxy['templates']\n localSet: ReadonlySet<string>\n env: string | undefined\n getRelease: () => string\n /** Per-package runtime data (recorded release/port) from the dev-context merge. */\n localInfo?: ReadonlyMap<string, LocalPackageInfo>\n}\n\n/** Resolve one route into a Vite proxy entry (or throw an actionable error). */\nconst resolveRoute = ({\n routePath,\n route,\n templates,\n localSet,\n env,\n getRelease,\n localInfo,\n}: ResolveRouteArgs): InfraKitViteProxyEntry => {\n const source = pickSource(route, localSet)\n\n if (source === 'local') {\n const target = resolveLocalTarget({ route, templates, env, getRelease, info: localInfo?.get(route.packageName) })\n\n return { target, changeOrigin: true }\n }\n\n if (!env) {\n throw new Error(\n `infra-kit/vite: proxy route \"${routePath}\" resolves to a cloud backend but ${INFRA_KIT_ENV} is not set. Source an environment from Doppler first (e.g. \\`infra-kit env-load -c dev\\`).`,\n )\n }\n\n const target = interpolate(templates.cloud, { release: '', packageName: route.packageName, env })\n\n return { target, changeOrigin: true, secure: false, cookieDomainRewrite: 'localhost' }\n}\n\ninterface ResolveProxyArgs {\n proxy: InfraKitDevProxy\n localSet: ReadonlySet<string>\n env: string | undefined\n getRelease: () => string\n /** Pre-computed `Authorization` header value applied uniformly to every route. */\n authHeader?: string\n /** Per-package runtime data (recorded release/port) from the dev-context merge. */\n localInfo?: ReadonlyMap<string, LocalPackageInfo>\n}\n\n/**\n * Pure resolver: turn a `dev.proxy` config + resolved inputs (local set, env,\n * lazy release) into a Vite `server.proxy` map. Side-effect-free so the\n * resolution shape is fully unit-testable. When `authHeader` is set, every route\n * entry gets a matching `headers.Authorization`; otherwise no `headers` key.\n */\nexport const resolveProxyConfig = ({\n proxy,\n localSet,\n env,\n getRelease,\n authHeader,\n localInfo,\n}: ResolveProxyArgs): InfraKitViteProxy => {\n const result: InfraKitViteProxy = {}\n const headers = authHeader ? { Authorization: authHeader } : undefined\n\n for (const [routePath, route] of Object.entries(proxy.routes)) {\n const entry = resolveRoute({ routePath, route, templates: proxy.templates, localSet, env, getRelease, localInfo })\n\n result[routePath] = headers ? { ...entry, headers } : entry\n }\n\n return result\n}\n\n/** Memoize a zero-arg thunk so `<release>` git resolution runs at most once. */\nconst once = <T>(fn: () => T): (() => T) => {\n let cached: { value: T } | undefined\n\n return () => {\n cached ??= { value: fn() }\n\n return cached.value\n }\n}\n\n/**\n * Load a package's `infra-kit.config.ts` and return its `dev` block, or\n * `undefined` when the config or the `dev` key is absent. The `.ts` config is\n * evaluated via Node's native type stripping (Node >= 24) \u2014 the same mechanism\n * the CLI's config loader uses. Cache-busted by mtime so repeated dev-server\n * reloads pick up edits.\n */\nexport const loadDev = async (cwd: string): Promise<InfraKitDev | undefined> => {\n const configPath = path.join(cwd, PACKAGE_CONFIG_FILE)\n\n if (!fs.existsSync(configPath)) return undefined\n\n const stat = fs.statSync(configPath)\n const moduleUrl = `${pathToFileURL(configPath).href}?mtime=${Number(stat.mtimeMs)}`\n\n const imported = (await import(moduleUrl)) as { default?: unknown }\n const rawExport = imported.default\n\n if (rawExport === undefined) return undefined\n\n const resolved = typeof rawExport === 'function' ? await (rawExport as () => unknown)() : rawExport\n\n const parsed = packageConfigSchema.safeParse(resolved)\n\n if (!parsed.success) {\n throw new Error(`infra-kit/vite: invalid ${PACKAGE_CONFIG_FILE} at ${configPath}: ${z.prettifyError(parsed.error)}`)\n }\n\n return parsed.data.dev\n}\n\n/** Coerce a parsed dev-context.json into the set of locally-running package names. */\nconst extractPackages = (parsed: unknown): string[] => {\n if (Array.isArray(parsed)) {\n return parsed.filter((v): v is string => {\n return typeof v === 'string'\n })\n }\n\n if (parsed !== null && typeof parsed === 'object') {\n const candidate = (parsed as Record<string, unknown>).packages ?? (parsed as Record<string, unknown>).localPackages\n\n if (Array.isArray(candidate)) {\n return candidate.filter((v): v is string => {\n return typeof v === 'string'\n })\n }\n }\n\n return []\n}\n\n/** Search upward from `start` for `relative`, returning the first hit or undefined. */\nconst findUp = (start: string, relative: string): string | undefined => {\n let dir = path.resolve(start)\n\n for (;;) {\n const candidate = path.join(dir, relative)\n\n if (fs.existsSync(candidate)) return candidate\n\n const parent = path.dirname(dir)\n\n if (parent === dir) return undefined\n\n dir = parent\n }\n}\n\n/** Per-package runtime data merged from the dev-context fragment directory. */\nexport interface LocalPackageInfo {\n /** The real bound port the runner recorded. Provenance only \u2014 the proxy target is the alias host. */\n port: number\n /** The runner-recorded release slug, preferred over the helper's git derivation. */\n release?: string\n /** `<release>.<packageName>.localhost`, present only when a portless alias was registered. */\n alias?: string\n /** The port {@link alias} resolves on. `80` (the default) is implicit in the template. */\n proxyPort?: number\n}\n\n/**\n * The locally-running package set plus a `package \u2192 { port, release }` map merged\n * from the dev-context fragments. `packages` feeds `pickSource`; `info` lets a\n * `local` route emit the per-package recorded release (see {@link resolveRoute}).\n */\nexport interface LocalContext {\n packages: ReadonlySet<string>\n info: ReadonlyMap<string, LocalPackageInfo>\n}\n\n/** An empty {@link LocalContext} (frontend-only / dev-context absent). */\nconst emptyLocalContext = (): LocalContext => {\n return { packages: new Set(), info: new Map() }\n}\n\n/**\n * Is the runner that wrote a fragment still alive? Signal `0` performs the permission and existence\n * checks without delivering anything. `ESRCH` is the one answer that means \"gone\"; `EPERM` means the\n * pid exists under another uid, which is still a live process. A fragment with no `pid` predates the\n * field and is trusted (back-compat) rather than dropped.\n */\nconst isFragmentWriterAlive = (pid: number | undefined): boolean => {\n if (pid == null) return true\n\n try {\n process.kill(pid, 0)\n\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/**\n * Merge every `<app>.json` fragment in the dev-context directory into a\n * {@link LocalContext}. Two DISTINCT failure branches (do NOT collapse them into\n * one directory-wide catch):\n * - `readdir`-ENOENT (directory vanished mid-race) \u2192 empty context, matching the\n * dir-absent back-compat behaviour.\n * - a single corrupt/truncated/invalid `<app>.json` \u2192 that ONE fragment is\n * SKIPPED (per-fragment `safeParse` isolation); the rest still merge, so one bad\n * fragment never collapses the whole localSet to empty (which would silently\n * drop a started package to cloud).\n */\nconst readFragmentDir = (dir: string): LocalContext => {\n let entries: string[]\n\n try {\n entries = fs.readdirSync(dir)\n } catch {\n return emptyLocalContext()\n }\n\n const packages = new Set<string>()\n const info = new Map<string, LocalPackageInfo>()\n\n for (const name of entries) {\n if (!name.endsWith('.json')) continue\n\n try {\n const parsed = devContextFragmentSchema.safeParse(JSON.parse(fs.readFileSync(path.join(dir, name), 'utf-8')))\n\n if (!parsed.success) continue\n\n // A runner killed with SIGKILL (or crashed) leaves its fragment AND its portless alias behind.\n // Trusting it would route this package's `/api` at an alias nothing serves \u2014 a silent 502 with\n // no diagnostic. The writer already stamps its pid; honour it.\n if (!isFragmentWriterAlive(parsed.data.pid)) continue\n\n packages.add(parsed.data.package)\n info.set(parsed.data.package, {\n port: parsed.data.port,\n release: parsed.data.release,\n alias: parsed.data.alias,\n proxyPort: parsed.data.proxyPort,\n })\n } catch {\n // Corrupt/truncated fragment (JSON.parse / read failure): skip ONLY this one.\n continue\n }\n }\n\n return { packages, info }\n}\n\n/**\n * Read the locally-running package context, searched upward from `cwd`. Prefers\n * the `.infra-kit/dev-context/` fragment DIRECTORY (merged via\n * {@link readFragmentDir}); when it is absent, falls back to the legacy single\n * `.infra-kit/dev-context.json` file (read as before \u2014 no per-package release);\n * when neither exists \u2192 empty context (frontend-only, every route resolves cloud).\n */\nexport const readLocalContext = (cwd: string): LocalContext => {\n const dir = findUp(cwd, DEV_CONTEXT_DIR)\n\n if (dir) return readFragmentDir(dir)\n\n const legacy = findUp(cwd, DEV_CONTEXT_FILE)\n\n if (!legacy) return emptyLocalContext()\n\n try {\n return { packages: new Set(extractPackages(JSON.parse(fs.readFileSync(legacy, 'utf-8')))), info: new Map() }\n } catch {\n return emptyLocalContext()\n }\n}\n\n/**\n * Read the set of locally-running packages (searched upward from `cwd`). Thin\n * wrapper over {@link readLocalContext} preserving the historical `Set`-returning\n * contract. Absent dev-context \u2192 empty set (frontend-only cloud resolution).\n */\nexport const readLocalSet = (cwd: string): ReadonlySet<string> => {\n return readLocalContext(cwd).packages\n}\n\n/** Current git branch of `cwd` (raw, un-slugified). */\nconst readGitBranch = (cwd: string): string => {\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n return execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd, encoding: 'utf-8' }).trim()\n}\n\n/**\n * An OS-assigned free TCP port on 127.0.0.1 \u2014 the per-worktree dev-server port (mirrors the\n * backend's `listen(0)`). This probes then releases the port, so there is a small TOCTOU window\n * before Vite binds it; Vite's default `strictPort: false` absorbs a lost race by stepping to the\n * next free port. Only a consumer that sets `strictPort: true` would hard-fail on the rare collision.\n */\nconst getFreePort = (): Promise<number> => {\n return new Promise((resolve, reject) => {\n const srv = net.createServer()\n\n srv.unref()\n srv.on('error', reject)\n srv.listen(0, '127.0.0.1', () => {\n const address = srv.address()\n const port = typeof address === 'object' && address !== null ? address.port : 0\n\n srv.close(() => {\n return resolve(port)\n })\n })\n })\n}\n\n/** Env var carrying the runner-assigned `{ \"<ui-package>\": <port> }` map (Layer B). */\nconst UI_PORTS_ENV = 'INFRA_KIT_UI_PORTS'\n\n/** This package's `package.json` `name`, or `null` (unreadable / nameless). */\nconst readPackageName = (cwd: string): string | null => {\n try {\n const parsed = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf-8')) as { name?: unknown }\n\n return typeof parsed.name === 'string' ? parsed.name : null\n } catch {\n return null\n }\n}\n\n/**\n * The port `infra-kit dev` assigned THIS UI via `INFRA_KIT_UI_PORTS` (Layer B), or `null` when the map\n * is absent / this package isn't in it / it's malformed. Present \u2192 the helper binds it with\n * `strictPort` so vite lands on exactly the port the runner already aliased. Absent (portless off, or a\n * standalone `vite dev`) \u2192 the caller falls back to a free port, byte-identical to today.\n */\nconst resolveManagedUiPort = (cwd: string): number | null => {\n const raw = process.env[UI_PORTS_ENV]\n\n if (raw == null || raw === '') return null\n\n const name = readPackageName(cwd)\n\n if (name == null) return null\n\n try {\n const map = JSON.parse(raw) as Record<string, unknown>\n const port = map[name]\n\n return typeof port === 'number' ? port : null\n } catch {\n return null\n }\n}\n\n/**\n * Resolve a package's `dev` block into a ready-made Vite `server` config: a per-worktree dev-server\n * `port` plus the `proxy` map. Loads the package's `infra-kit.config.ts`, merges the local dev set\n * from the `.infra-kit/dev-context/` fragment directory, and interpolates the local/cloud templates.\n * `<env>` comes from `INFRA_KIT_ENV`; `<release>` from each package's runner-recorded fragment when\n * present, else the slugified git branch (computed lazily, only when a local route needs it).\n *\n * `port` defaults to a fresh OS-assigned free port so simultaneous git worktrees never collide on\n * Vite's `5173` (override via `options.port`). `host` defaults to {@link LOOPBACK_V4} so the portless\n * alias can actually reach it (override via `options.host` for containers/LAN). Pass `command` so\n * `build` is a no-op (empty proxy, no port) \u2014 a build ignores `server` and proxy resolution would\n * otherwise fail-fast on a cloud route with no sourced env.\n *\n * @example\n * // vite.config.ts \u2014 the whole `server` field is the helper's output\n * import { infraKitDev } from 'infra-kit/vite'\n * export default defineConfig(async ({ command }) => ({ server: await infraKitDev({ command }) }))\n */\nexport const infraKitDev = async (\n options: InfraKitDevOptions = {},\n): Promise<{ port?: number; host?: string | boolean; strictPort?: boolean; proxy: InfraKitViteProxy }> => {\n const cwd = options.cwd ?? process.cwd()\n\n // A build ignores `server`; skip the port + proxy work (proxy resolution would fail-fast on a\n // cloud route with no sourced env).\n if (options.command === 'build') return { proxy: {} }\n\n // Port precedence: explicit `options.port` > the runner-assigned Layer-B port (bound `strictPort` so\n // vite lands on exactly the aliased port) > a fresh free port (today's default; the portless-off path).\n const managedPort = options.port == null ? resolveManagedUiPort(cwd) : null\n const port = options.port ?? managedPort ?? (await getFreePort())\n const strictPort = managedPort != null\n const host = options.host ?? LOOPBACK_V4\n const dev = await loadDev(cwd)\n\n if (!dev?.proxy) return { port, host, ...(strictPort ? { strictPort } : {}), proxy: {} }\n\n const { packages: localSet, info: localInfo } = readLocalContext(cwd)\n const env = process.env[INFRA_KIT_ENV]\n const authHeader = buildBasicAuthHeader(process.env, options.basicAuth)\n const getRelease = once(() => {\n // Mirrors the dev-server's `readAppRelease`: outside a git repo both sides must land on the SAME\n // label, or this target names a host the runner never aliased.\n try {\n return slugifyRelease(readGitBranch(cwd)) || DEFAULT_RELEASE_SLUG\n } catch {\n return DEFAULT_RELEASE_SLUG\n }\n })\n\n return {\n port,\n host,\n ...(strictPort ? { strictPort } : {}),\n proxy: resolveProxyConfig({ proxy: dev.proxy, localSet, env, getRelease, authHeader, localInfo }),\n }\n}\n\n/**\n * Convenience wrapper returning just the proxy map (for spreading into\n * `server.proxy` directly). Equivalent to `(await infraKitDev(options)).proxy`.\n */\nexport const infraKitProxy = async (options: InfraKitDevOptions = {}): Promise<InfraKitViteProxy> => {\n return (await infraKitDev(options)).proxy\n}\n", "import { z } from 'zod'\n\n/**\n * Schema for the resolved (post-factory) package config object. `strictObject`\n * rejects unknown keys so typos in `infra-kit.config.ts` surface as validation\n * errors instead of being silently ignored.\n *\n * Kept in its own module \u2014 separate from the public `defineConfig`/types entry \u2014\n * so the published `infra-kit` type surface stays free of a `zod` import.\n */\nexport const packageConfigSchema = z.strictObject({\n requiredScripts: z.array(z.string().min(1)).optional(),\n requiredFiles: z.array(z.string().min(1)).optional(),\n turbo: z\n .strictObject({\n requiredTasks: z.array(z.string().min(1)).optional(),\n })\n .optional(),\n dev: z\n .strictObject({\n proxy: z\n .strictObject({\n templates: z.strictObject({\n local: z.string().min(1),\n cloud: z.string().min(1),\n }),\n routes: z.record(\n z.string().min(1),\n z\n .strictObject({\n packageName: z.string().min(1),\n from: z.array(z.enum(['local', 'cloud'])).min(1),\n default: z.enum(['local', 'cloud']).optional(),\n })\n .refine(\n (route) => {\n return route.from.length <= 1 || route.default !== undefined\n },\n {\n message: 'default is required when `from` has more than one source',\n },\n )\n .refine(\n (route) => {\n return route.default === undefined || route.from.includes(route.default)\n },\n {\n message: 'default must be listed in `from`',\n },\n ),\n ),\n })\n .optional(),\n })\n .optional(),\n})\n"],
5
+ "mappings": "sDAAA,OAAS,UAAAA,MAAc,cACvB,OAAS,gBAAAC,MAAoB,qBAC7B,OAAOC,MAAQ,UACf,OAAOC,MAAS,WAChB,OAAOC,MAAU,YACjB,OAAOC,MAAa,eACpB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,KAAAC,MAAS,MCPlB,OAAS,KAAAC,MAAS,MAUX,IAAMC,EAAsBD,EAAE,aAAa,CAChD,gBAAiBA,EAAE,MAAMA,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS,EACrD,cAAeA,EAAE,MAAMA,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS,EACnD,MAAOA,EACJ,aAAa,CACZ,cAAeA,EAAE,MAAMA,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS,CACrD,CAAC,EACA,SAAS,EACZ,IAAKA,EACF,aAAa,CACZ,MAAOA,EACJ,aAAa,CACZ,UAAWA,EAAE,aAAa,CACxB,MAAOA,EAAE,OAAO,EAAE,IAAI,CAAC,EACvB,MAAOA,EAAE,OAAO,EAAE,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EAC9D6B,EAAMb,EAAQ,IAAIc,CAAa,EAC/BC,EAAaC,EAAqBhB,EAAQ,IAAKG,EAAQ,SAAS,EAChEc,EAAaC,EAAK,IAAM,CAG5B,GAAI,CACF,OAAOC,EAAepC,EAAcC,CAAG,CAAC,GAAKoC,CAC/C,MAAQ,CACN,OAAOA,CACT,CACF,CAAC,EAED,MAAO,CACL,KAAA5B,EACA,KAAAc,EACA,GAAID,EAAa,CAAE,WAAAA,CAAW,EAAI,CAAC,EACnC,MAAOgB,EAAmB,CAAE,MAAOb,EAAI,MAAO,SAAAE,EAAU,IAAAG,EAAK,WAAAI,EAAY,WAAAF,EAAY,UAAAJ,CAAU,CAAC,CAClG,CACF,EAMaW,GAAgB,MAAOnB,EAA8B,CAAC,KACzD,MAAMD,EAAYC,CAAO,GAAG",
6
+ "names": ["Buffer", "execFileSync", "fs", "net", "path", "process", "pathToFileURL", "z", "z", "packageConfigSchema", "route", "INFRA_KIT_ENV", "PACKAGE_CONFIG_FILE", "DEV_CONTEXT_DIR", "path", "DEV_CONTEXT_FILE", "devContextFragmentSchema", "z", "buildBasicAuthHeader", "env", "override", "username", "password", "Buffer", "interpolate", "template", "values", "DEFAULT_HTTP_PORT", "LOOPBACK_V4", "withProxyPort", "target", "proxyPort", "url", "grafted", "resolveLocalTarget", "args", "route", "templates", "env", "getRelease", "info", "slugifyHostLabel", "pickSource", "localSet", "fallback", "resolveRoute", "routePath", "localInfo", "INFRA_KIT_ENV", "resolveProxyConfig", "proxy", "authHeader", "result", "headers", "entry", "once", "fn", "cached", "loadDev", "cwd", "configPath", "path", "PACKAGE_CONFIG_FILE", "fs", "stat", "rawExport", "pathToFileURL", "resolved", "parsed", "packageConfigSchema", "z", "extractPackages", "v", "candidate", "findUp", "start", "relative", "dir", "parent", "emptyLocalContext", "isFragmentWriterAlive", "pid", "process", "error", "readFragmentDir", "entries", "packages", "name", "devContextFragmentSchema", "readLocalContext", "DEV_CONTEXT_DIR", "legacy", "DEV_CONTEXT_FILE", "readGitBranch", "cwd", "execFileSync", "getFreePort", "resolve", "reject", "srv", "net", "address", "port", "UI_PORTS_ENV", "readPackageName", "parsed", "fs", "path", "resolveManagedUiPort", "raw", "process", "name", "infraKitDev", "options", "managedPort", "strictPort", "host", "LOOPBACK_V4", "dev", "loadDev", "localSet", "localInfo", "readLocalContext", "env", "INFRA_KIT_ENV", "authHeader", "buildBasicAuthHeader", "getRelease", "once", "slugifyRelease", "DEFAULT_RELEASE_SLUG", "resolveProxyConfig", "infraKitProxy"]
7
+ }
@@ -0,0 +1,4 @@
1
+ import{v as e}from"./chunk-X2L4F2VM.js";var s=()=>{let n="",r=[],o=!1;return{start(t){n=t,r=[],o=!1},setInteractive(){o=!0},addOption(t,a){r.push({flag:t,value:a})},formatOptions(){return r.map(t=>typeof t.value=="boolean"?t.value?t.flag:"":Array.isArray(t.value)?`${t.flag} "${t.value.join(", ")}"`:`${t.flag} "${t.value}"`).filter(Boolean).join(" ")},snapshot(){return r.length===0?null:{formattedOptions:this.formatOptions()}},print(){!o||r.length===0||e.info(`\u{1F4DF} Equivalent command:
2
+ pnpm exec infra-kit ${n} ${this.formatOptions()}
3
+ `)},reset(){n="",r=[],o=!1}}},i=s();import m from"@inquirer/confirm";import f from"node:process";var l=async(n,r)=>{let o=n?!0:await m({message:r});n||i.setInteractive(),o||(e.info("Operation cancelled. Exiting..."),f.exit(0))};export{i as a,l as b};
4
+ //# sourceMappingURL=chunk-52WL2IQX.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/command-echo/command-echo.ts", "../src/lib/command-echo/confirm-or-exit.ts"],
4
+ "sourcesContent": ["import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let commandName = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Initialize command echo for a new command\n */\n start(name: string): void {\n commandName = name\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Format the tracked options into a replayable flag string (empty when none).\n */\n formatOptions(): string {\n return options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n },\n\n /**\n * The recorded interactive flags for the session shell's report side channel, so the transcript's\n * equivalent line carries the resolved options (`--versions \"1.2.5\"`), not just the bare command.\n * `null` when nothing was recorded \u2014 the caller then falls back to the bare spawned argv.\n */\n snapshot(): { formattedOptions: string } | null {\n if (options.length === 0) {\n return null\n }\n\n return { formattedOptions: this.formatOptions() }\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input\n */\n print(): void {\n if (!isInteractive || options.length === 0) {\n return\n }\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${commandName} ${this.formatOptions()}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n commandName = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n", "import confirm from '@inquirer/confirm'\nimport process from 'node:process'\n\nimport { logger } from 'src/lib/logger'\n\nimport { commandEcho } from './command-echo'\n\n/**\n * Shared interactive-confirmation gate for mutating commands.\n *\n * When `confirmedCommand` is truthy (CLI `--yes` or an MCP call, which always\n * injects `confirmedCommand: true`) the prompt is skipped and execution\n * proceeds. Otherwise it prompts the user, marks the echo as interactive, and\n * exits cleanly if the user declines.\n *\n * The `process.exit(0)` only runs on the interactive-decline path, which is\n * unreachable under MCP \u2014 so this stays safe for the long-lived MCP server.\n *\n * Callers remain responsible for their own `commandEcho.addOption('--yes', \u2026)`\n * bookkeeping, which varies between commands.\n */\nexport const confirmOrExit = async (confirmedCommand: boolean | undefined, message: string): Promise<void> => {\n const answer = confirmedCommand ? true : await confirm({ message })\n\n if (!confirmedCommand) {\n commandEcho.setInteractive()\n }\n\n if (!answer) {\n logger.info('Operation cancelled. Exiting...')\n process.exit(0)\n }\n}\n"],
5
+ "mappings": "wCAOA,IAAMA,EAAoB,IAAM,CAC9B,IAAIC,EAAc,GACdC,EAA2B,CAAC,EAC5BC,EAAgB,GAEpB,MAAO,CAIL,MAAMC,EAAoB,CACxBH,EAAcG,EACdF,EAAU,CAAC,EACXC,EAAgB,EAClB,EAMA,gBAAuB,CACrBA,EAAgB,EAClB,EAOA,UAAUE,EAAcC,EAA0C,CAChEJ,EAAQ,KAAK,CAAE,KAAAG,EAAM,MAAAC,CAAM,CAAC,CAC9B,EAKA,eAAwB,CACtB,OAAOJ,EACJ,IAAKK,GACA,OAAOA,EAAI,OAAU,UAChBA,EAAI,MAAQA,EAAI,KAAO,GAG5B,MAAM,QAAQA,EAAI,KAAK,EAClB,GAAGA,EAAI,IAAI,KAAKA,EAAI,MAAM,KAAK,IAAI,CAAC,IAGtC,GAAGA,EAAI,IAAI,KAAKA,EAAI,KAAK,GACjC,EACA,OAAO,OAAO,EACd,KAAK,GAAG,CACb,EAOA,UAAgD,CAC9C,OAAIL,EAAQ,SAAW,EACd,KAGF,CAAE,iBAAkB,KAAK,cAAc,CAAE,CAClD,EAKA,OAAc,CACR,CAACC,GAAiBD,EAAQ,SAAW,GAIzCM,EAAO,KAAK;AAAA,sBAAgDP,CAAW,IAAI,KAAK,cAAc,CAAC;AAAA,CAAI,CACrG,EAKA,OAAc,CACZA,EAAc,GACdC,EAAU,CAAC,EACXC,EAAgB,EAClB,CACF,CACF,EAGaM,EAAcT,EAAkB,EC/F7C,OAAOU,MAAa,oBACpB,OAAOC,MAAa,eAoBb,IAAMC,EAAgB,MAAOC,EAAuCC,IAAmC,CAC5G,IAAMC,EAASF,EAAmB,GAAO,MAAMG,EAAQ,CAAE,QAAAF,CAAQ,CAAC,EAE7DD,GACHI,EAAY,eAAe,EAGxBF,IACHG,EAAO,KAAK,iCAAiC,EAC7CC,EAAQ,KAAK,CAAC,EAElB",
6
+ "names": ["createCommandEcho", "commandName", "options", "isInteractive", "name", "flag", "value", "opt", "logger", "commandEcho", "confirm", "process", "confirmOrExit", "confirmedCommand", "message", "answer", "confirm", "commandEcho", "logger", "process"]
7
+ }
@@ -0,0 +1,2 @@
1
+ var r=t=>Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("npm_")&&e!=="PNPM_SCRIPT_SRC_DIR"));export{r as a};
2
+ //# sourceMappingURL=chunk-6FU2TRU5.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/pm-env/pm-env.ts"],
4
+ "sourcesContent": ["/**\n * `env` minus every package-manager marker a spawned child could mistake for a throwaway install.\n *\n * Any child we launch through `node <bin>` (the portless driver, self-update, the mcp launcher) inherits\n * our env, and a tool that sniffs those markers will conclude it was run via `npx`/`pnpm dlx` and refuse\n * to work. portless is the motivating case; its guard (cli.js `main()`) is:\n *\n * isNpx = npm_command === 'exec' && !npm_lifecycle_event\n * isPnpmDlx = !!PNPM_SCRIPT_SRC_DIR && !npm_lifecycle_event\n * if ((isNpx || isPnpmDlx) && !isLocallyInstalled()) \u2192 abort\n *\n * `isLocallyInstalled()` walks up from the CHILD's cwd, so in a consumer repo (where portless is a\n * transitive dep of infra-kit, absent from the root `node_modules`) it is false and the guard is live.\n * `pnpm exec infra-kit dev` exports `npm_command=exec` with no lifecycle event \u2192 `isNpx` \u2192 every\n * portless call exits 1 \u2192 `isAvailable()` is false \u2192 `ensureProxy` aborts the whole dev boot with\n * \"portless is not installed\", on a machine where it plainly is.\n *\n * `PNPM_SCRIPT_SRC_DIR` must be dropped ALONGSIDE the `npm_*` block, not left behind: it is set by\n * `pnpm run <script>`, where `npm_lifecycle_event` is what suppresses `isPnpmDlx`. Stripping only\n * `npm_*` removes that suppressor and *creates* an abort for the script-style invocation that\n * previously worked. Both markers go, or neither is safe.\n *\n * The result makes the child look exactly like a direct `node <pkg>/dist/cli.js` run \u2014 which it is.\n */\nexport const withoutPackageManagerEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv => {\n return Object.fromEntries(\n Object.entries(env).filter(([key]) => {\n return !key.startsWith('npm_') && key !== 'PNPM_SCRIPT_SRC_DIR'\n }),\n )\n}\n"],
5
+ "mappings": "AAwBO,IAAMA,EAA4BC,GAChC,OAAO,YACZ,OAAO,QAAQA,CAAG,EAAE,OAAO,CAAC,CAACC,CAAG,IACvB,CAACA,EAAI,WAAW,MAAM,GAAKA,IAAQ,qBAC3C,CACH",
6
+ "names": ["withoutPackageManagerEnv", "env", "key"]
7
+ }
@@ -1,4 +1,4 @@
1
- import{L as w,N as x,c as l,i as f,v as n}from"./chunk-4YU4TAGX.js";import g from"node:process";import{$ as p}from"zx";var C=async()=>{try{return await p`cmux --version`.quiet(),!0}catch{return!1}},y=async t=>{let{cwd:e,title:r,layout:s}=t,o=JSON.stringify(s),i=(await p({env:{...g.env,CMUX_QUIET:"1"}})`cmux new-workspace --name ${r} --cwd ${e} --focus false --layout ${o}`).stdout;return W(i)},h=async t=>{try{await p`cmux close-workspace --workspace ${t}`.quiet()}catch(e){n.debug({error:e,ref:t},"cmux: skipped closing dev workspace")}},W=t=>{let e=t.match(/workspace:\d+/);if(!e)throw new Error("cmux: could not locate workspace ref in new-workspace output");return e[0]};var $=/\bv(\d+\.\d+\.\d+)\b/g,a=t=>t.trim().replace(/\s+/g," ").replace($,"$1");import{$ as d}from"zx";var T=async t=>{try{let e=(await d`cmux list-workspaces`.quiet()).stdout,r=b(e,t);if(!r)return;await d`cmux close-workspace --workspace ${r}`.quiet()}catch(e){n.debug({error:e,title:t},"cmux: skipped closing workspace")}},b=(t,e)=>{let r=a(e);for(let s of t.split(`
1
+ import{Q as w,S as x,c as l,i as f,v as n}from"./chunk-X2L4F2VM.js";import g from"node:process";import{$ as p}from"zx";var C=async()=>{try{return await p`cmux --version`.quiet(),!0}catch{return!1}},y=async t=>{let{cwd:e,title:r,layout:s}=t,o=JSON.stringify(s),i=(await p({env:{...g.env,CMUX_QUIET:"1"}})`cmux new-workspace --name ${r} --cwd ${e} --focus false --layout ${o}`).stdout;return W(i)},h=async t=>{try{await p`cmux close-workspace --workspace ${t}`.quiet()}catch(e){n.debug({error:e,ref:t},"cmux: skipped closing dev workspace")}},W=t=>{let e=t.match(/workspace:\d+/);if(!e)throw new Error("cmux: could not locate workspace ref in new-workspace output");return e[0]};var $=/\bv(\d+\.\d+\.\d+)\b/g,a=t=>t.trim().replace(/\s+/g," ").replace($,"$1");import{$ as d}from"zx";var T=async t=>{try{let e=(await d`cmux list-workspaces`.quiet()).stdout,r=b(e,t);if(!r)return;await d`cmux close-workspace --workspace ${r}`.quiet()}catch(e){n.debug({error:e,title:t},"cmux: skipped closing workspace")}},b=(t,e)=>{let r=a(e);for(let s of t.split(`
2
2
  `)){let o=s.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let c=o[1],i=o[2]?.trim()??"";if(a(i)===r)return c}};import{$ as v}from"zx";var E=async()=>{try{let t=(await v`cmux list-workspaces`.quiet()).stdout,e=new Set;for(let r of t.split(`
3
- `)){let s=r.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!s)continue;let o=s[1]?.trim();o&&e.add(a(o))}return e}catch(t){return n.debug({error:t},"cmux: skipped listing workspace titles"),new Set}};import{$ as u}from"zx";var A=async t=>{let{cwd:e,title:r}=t,s=w(await x()),o=(await u`cmux workspace create --cwd ${e}`).stdout,c=O(o),i=(await u`cmux list-pane-surfaces --workspace ${c}`).stdout,m=N(i);await u`cmux new-split right --workspace ${c} --surface ${m}`,s==="three-pane"&&await u`cmux new-split down --workspace ${c} --surface ${m}`,r&&await u`cmux workspace rename --workspace ${c} --title ${r}`},N=t=>{let e=t.match(/surface:\d+/);if(!e)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return e[0]},O=t=>{let e=t.match(/workspace:\d+/);if(!e)throw new Error("cmux: could not locate workspace ref in workspace create output");return e[0]};var R=t=>{let{repoName:e,branch:r}=t,s=l(r),o=s?f(s):r;return`${e} ${o}`};var L=new Set(["ExitPromptError","AbortPromptError"]),k=t=>t instanceof Error&&L.has(t.name),st=t=>{if(k(t))return!0;let e=t?.cause;return k(e)};export{a,T as b,E as c,C as d,y as e,h as f,A as g,R as h,st as i};
4
- //# sourceMappingURL=chunk-Q36WX5RP.js.map
3
+ `)){let s=r.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!s)continue;let o=s[1]?.trim();o&&e.add(a(o))}return e}catch(t){return n.debug({error:t},"cmux: skipped listing workspace titles"),new Set}};import{$ as u}from"zx";var A=async t=>{let{cwd:e,title:r}=t,s=w(await x()),o=(await u`cmux workspace create --cwd ${e}`).stdout,c=O(o),i=(await u`cmux list-pane-surfaces --workspace ${c}`).stdout,m=N(i);await u`cmux new-split right --workspace ${c} --surface ${m}`,s==="three-pane"&&await u`cmux new-split down --workspace ${c} --surface ${m}`,r&&await u`cmux workspace rename --workspace ${c} --title ${r}`},N=t=>{let e=t.match(/surface:\d+/);if(!e)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return e[0]},O=t=>{let e=t.match(/workspace:\d+/);if(!e)throw new Error("cmux: could not locate workspace ref in workspace create output");return e[0]};var R=t=>{let{repoName:e,branch:r}=t,s=l(r),o=s?f(s):r;return`${e} ${o}`};var L=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),k=t=>t instanceof Error&&L.has(t.name),st=t=>{if(k(t))return!0;let e=t?.cause;return k(e)};export{a,T as b,E as c,C as d,y as e,h as f,A as g,R as h,st as i};
4
+ //# sourceMappingURL=chunk-6YAKVQZN.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/integrations/cmux/open-dev-workspace.ts", "../src/integrations/cmux/canonicalize-cmux-title.ts", "../src/integrations/cmux/close-workspace-by-title.ts", "../src/integrations/cmux/list-workspace-titles.ts", "../src/integrations/cmux/open-workspace-with-layout.ts", "../src/integrations/cmux/workspace-title.ts", "../src/lib/errors/is-prompt-cancellation.ts"],
4
- "sourcesContent": ["import process from 'node:process'\nimport { $ } from 'zx'\n\nimport type { CmuxLayoutNode } from 'src/dev/cmux-layout'\nimport { logger } from 'src/lib/logger'\n\n/** Args for {@link openCmuxDevWorkspace}: the workspace root, title, and pane layout tree. */\ninterface OpenCmuxDevWorkspaceArgs {\n cwd: string\n title: string\n layout: CmuxLayoutNode\n}\n\n/**\n * True iff the `cmux` CLI is invokable (i.e. `cmux --version` resolves). Used to\n * gate `--cmux` mode and fall back to single-process dev when cmux is absent.\n */\nexport const isCmuxAvailable = async (): Promise<boolean> => {\n try {\n await $`cmux --version`.quiet()\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Open ONE cmux workspace rooted at `cwd`, laid out per `layout` (one pane per\n * command). Runs in a `CMUX_QUIET=1` scoped env to suppress cmux's one-time compat\n * notice, then parses and returns the `workspace:<id>` ref from stdout.\n */\nexport const openCmuxDevWorkspace = async (args: OpenCmuxDevWorkspaceArgs): Promise<string> => {\n const { cwd, title, layout } = args\n const layoutJson = JSON.stringify(layout)\n\n const $cmux = $({ env: { ...process.env, CMUX_QUIET: '1' } })\n const output = (await $cmux`cmux new-workspace --name ${title} --cwd ${cwd} --focus false --layout ${layoutJson}`)\n .stdout\n\n return parseWorkspaceRef(output)\n}\n\n/**\n * Best-effort close of the cmux workspace `ref`, tearing down the workspace and\n * every pane process. Silently no-ops (debug-logged) if cmux isn't running or the\n * close fails, mirroring {@link file://./close-workspace-by-title.ts}.\n */\nexport const closeCmuxDevWorkspace = async (ref: string): Promise<void> => {\n try {\n await $`cmux close-workspace --workspace ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, ref }, 'cmux: skipped closing dev workspace')\n }\n}\n\n/**\n * Extract the `workspace:<id>` ref from `cmux new-workspace` output (e.g.\n * `OK workspace:5`). Throws a clear error when no ref is present.\n *\n * @example\n * parseWorkspaceRef('OK workspace:5\\n') // => 'workspace:5'\n */\nconst parseWorkspaceRef = (output: string): string => {\n const match = output.match(/workspace:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate workspace ref in new-workspace output')\n }\n\n return match[0]\n}\n", "/** Matches a `v`-prefixed semver token (e.g. `v1.48.0`) anchored on shape. */\nconst V_SEMVER_TOKEN_RE = /\\bv(\\d+\\.\\d+\\.\\d+)\\b/g\n\n/**\n * Canonicalizes a cmux workspace title into a stable dedup/close key.\n *\n * cmux workspace titles are human display strings built by\n * `buildCmuxWorkspaceTitle`, so the value stored when a workspace is created can\n * drift from the value rebuilt later \u2014 across whitespace and across CLI versions\n * (an older build titled version releases `v1.48.0`; the current build titles\n * them `1.48.0`). Keying dedup or close on the raw title silently creates\n * duplicate / unclosable workspaces whenever that drift occurs.\n *\n * Canonicalization collapses the known drift axes so both sides round-trip to an\n * equal key:\n * - trims and collapses internal whitespace to single spaces;\n * - normalizes a `v`-prefixed semver token to its bare form\n * (`v1.48.0` \u2192 `1.48.0`), anchored on semver shape so named releases that\n * merely start with `v` (e.g. `vega-redesign`) are left untouched.\n *\n * Non-release fallback titles (which may contain `/`, e.g. `feature/foo`) are\n * preserved as-is apart from whitespace normalization.\n *\n * @example\n * canonicalizeCmuxTitle('hulyo-monorepo v1.48.0') // => 'hulyo-monorepo 1.48.0'\n * canonicalizeCmuxTitle('hulyo-monorepo 1.48.0') // => 'hulyo-monorepo 1.48.0'\n * canonicalizeCmuxTitle('hulyo-monorepo vega-redesign') // => 'hulyo-monorepo vega-redesign'\n */\nexport const canonicalizeCmuxTitle = (raw: string): string => {\n return raw.trim().replace(/\\s+/g, ' ').replace(V_SEMVER_TOKEN_RE, '$1')\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\nimport { canonicalizeCmuxTitle } from './canonicalize-cmux-title'\n\n/**\n * Best-effort close of the cmux workspace whose title matches `title` (compared\n * via {@link canonicalizeCmuxTitle}, so a drifted stored title still resolves).\n * Silently no-ops if cmux isn't running, the workspace isn't found, or close fails.\n */\nexport const closeCmuxWorkspaceByTitle = async (title: string): Promise<void> => {\n try {\n const listOutput = (await $`cmux list-workspaces`.quiet()).stdout\n\n const ref = findWorkspaceRefByTitle(listOutput, title)\n\n if (!ref) {\n return\n }\n\n await $`cmux close-workspace --workspace ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, title }, 'cmux: skipped closing workspace')\n }\n}\n\n/**\n * Parses `cmux list-workspaces` output and returns the workspace ref whose\n * title matches `title`, or undefined if no match. Both sides are compared via\n * {@link canonicalizeCmuxTitle} so a workspace stored under a drifted title\n * (whitespace, or an older CLI's `v`-prefixed semver) is still found \u2014 keeping\n * close symmetric with the cmux open dedup in `worktrees-reload`.\n *\n * Each line looks like:\n * \" workspace:8 hulyo-monorepo 1.48.0\"\n * \"* workspace:6 obsidian-workspace [selected]\"\n */\nconst findWorkspaceRefByTitle = (output: string, title: string): string | undefined => {\n const target = canonicalizeCmuxTitle(title)\n\n for (const rawLine of output.split('\\n')) {\n // eslint-disable-next-line sonarjs/super-linear-regex, regexp/no-super-linear-backtracking\n const match = rawLine.match(/^[* ]\\s*(workspace:\\d+)\\s+(.+?)(?:\\s+\\[selected\\])?\\s*$/)\n\n if (!match) {\n continue\n }\n\n const ref = match[1]\n const lineTitle = match[2]?.trim() ?? ''\n\n if (canonicalizeCmuxTitle(lineTitle) === target) {\n return ref\n }\n }\n\n return undefined\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\nimport { canonicalizeCmuxTitle } from './canonicalize-cmux-title'\n\n/**\n * Returns the set of **canonical** titles for all currently-open cmux\n * workspaces (see {@link canonicalizeCmuxTitle}). Keying on the canonical form\n * lets callers match a workspace even when its stored title drifted from the\n * title they rebuild (whitespace, or an older CLI's `v`-prefixed semver).\n * Returns an empty set if cmux isn't running, the call fails, or the output\n * can't be parsed \u2014 callers should treat \"empty\" as \"unknown, proceed as if\n * nothing is open\".\n *\n * Each line of `cmux list-workspaces` looks like:\n * \" workspace:8 hulyo-monorepo 1.48.0\"\n * \"* workspace:6 obsidian-workspace [selected]\"\n */\nexport const listCmuxWorkspaceTitles = async (): Promise<Set<string>> => {\n try {\n const output = (await $`cmux list-workspaces`.quiet()).stdout\n\n const titles = new Set<string>()\n\n for (const rawLine of output.split('\\n')) {\n // eslint-disable-next-line sonarjs/super-linear-regex, regexp/no-super-linear-backtracking\n const match = rawLine.match(/^[* ]\\s*workspace:\\d+\\s+(.+?)(?:\\s+\\[selected\\])?\\s*$/)\n\n if (!match) {\n continue\n }\n\n const title = match[1]?.trim()\n\n if (title) {\n titles.add(canonicalizeCmuxTitle(title))\n }\n }\n\n return titles\n } catch (error) {\n logger.debug({ error }, 'cmux: skipped listing workspace titles')\n\n return new Set()\n }\n}\n", "import { $ } from 'zx'\n\nimport { getInfraKitConfig, resolveCmuxLayout } from 'src/lib/infra-kit-config'\n\ninterface OpenCmuxWorkspaceArgs {\n cwd: string\n title?: string\n}\n\n/**\n * Opens a new cmux workspace rooted at `cwd`, with panes arranged per the\n * configured `worktrees.cmux.layout` (resolved via {@link resolveCmuxLayout},\n * default `two-columns`):\n * two-columns \u2014 left | right, both full-height (two panes)\n * three-pane \u2014 left-top / left-bottom | full-height right (three panes)\n * All panes inherit `cwd` from the workspace.\n */\nexport const openCmuxWorkspaceWithLayout = async (args: OpenCmuxWorkspaceArgs): Promise<void> => {\n const { cwd, title } = args\n\n const layout = resolveCmuxLayout(await getInfraKitConfig())\n\n const newWorkspaceOutput = (await $`cmux workspace create --cwd ${cwd}`).stdout\n\n const workspaceRef = parseWorkspaceRef(newWorkspaceOutput)\n\n const surfacesOutput = (await $`cmux list-pane-surfaces --workspace ${workspaceRef}`).stdout\n\n const leftTopRef = parseFirstSurfaceRef(surfacesOutput)\n\n // Both layouts share the vertical split into left | right columns; only the\n // legacy three-pane layout additionally splits the left column top/bottom.\n await $`cmux new-split right --workspace ${workspaceRef} --surface ${leftTopRef}`\n\n if (layout === 'three-pane') {\n await $`cmux new-split down --workspace ${workspaceRef} --surface ${leftTopRef}`\n }\n\n if (title) {\n await $`cmux workspace rename --workspace ${workspaceRef} --title ${title}`\n }\n}\n\n/**\n * Extracts the first `surface:<id>` reference from the output of\n * `cmux list-pane-surfaces`. Used to locate the initial (primary) pane\n * surface so subsequent splits can be anchored relative to it.\n *\n * @example\n * const output = 'surface:12 (active)\\nsurface:13\\n'\n * parseFirstSurfaceRef(output) // => 'surface:12'\n */\nconst parseFirstSurfaceRef = (output: string): string => {\n const match = output.match(/surface:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate initial surface in list-pane-surfaces output')\n }\n\n return match[0]\n}\n\n/**\n * Extracts the `workspace:<id>` reference from the output of\n * `cmux workspace create`. The returned ref is used to target the newly\n * created workspace in follow-up `cmux` commands (splits, rename, etc.).\n *\n * @example\n * const output = 'created workspace:7\\n'\n * parseWorkspaceRef(output) // => 'workspace:7'\n */\nconst parseWorkspaceRef = (output: string): string => {\n const match = output.match(/workspace:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate workspace ref in workspace create output')\n }\n\n return match[0]\n}\n", "import { displayLabel, parseBranchName } from 'src/lib/release-id'\n\ninterface BuildCmuxWorkspaceTitleArgs {\n repoName: string\n branch: string\n}\n\n/**\n * Builds the cmux workspace title used by `worktrees-add` and looked up by\n * `worktrees-remove`. Release branches are rendered via their release-id\n * display label so the title reads e.g. `\"hulyo-monorepo 1.48.0\"` for\n * `\"release/v1.48.0\"` and `\"hulyo-monorepo checkout-redesign\"` for\n * `\"release/checkout-redesign\"`. Non-release branches (cmux titles them too)\n * fall back to the raw branch string.\n */\nexport const buildCmuxWorkspaceTitle = (args: BuildCmuxWorkspaceTitleArgs): string => {\n const { repoName, branch } = args\n\n const id = parseBranchName(branch)\n const label = id ? displayLabel(id) : branch\n\n return `${repoName} ${label}`\n}\n", "/**\n * Names of the `@inquirer/core` error classes thrown when an interactive prompt\n * ends without a value: `ExitPromptError` (user pressed Ctrl-C / Esc) and\n * `AbortPromptError` (the prompt was aborted via an `AbortSignal`). Both are\n * intentional cancellations, not failures.\n */\nconst CANCELLATION_ERROR_NAMES = new Set(['ExitPromptError', 'AbortPromptError'])\n\nconst hasCancellationName = (value: unknown): boolean => {\n return value instanceof Error && CANCELLATION_ERROR_NAMES.has(value.name)\n}\n\n/**\n * True when `error` represents a user (or signal) cancellation of an\n * `@inquirer/*` prompt \u2014 i.e. pressing Ctrl-C / Esc in the branch picker or a\n * confirm step. Matched by `name` rather than `instanceof` so it stays correct\n * even when pnpm dedupes more than one copy of `@inquirer/core` into the tree\n * (an `instanceof` check fails across realms/duplicate classes).\n *\n * Also unwraps one level of `cause`, so a cancellation re-wrapped in an\n * {@link ./operation-error.OperationError} is still recognised at the top-level\n * error boundary.\n *\n * @example\n * try {\n * await checkbox({ message: 'Select release branches', choices })\n * } catch (err) {\n * if (isPromptCancellation(err)) process.exit(0) // clean back-out, not an error\n * throw err\n * }\n */\nexport const isPromptCancellation = (error: unknown): boolean => {\n if (hasCancellationName(error)) return true\n\n const cause = (error as { cause?: unknown } | null | undefined)?.cause\n\n return hasCancellationName(cause)\n}\n"],
5
- "mappings": "oEAAA,OAAOA,MAAa,eACpB,OAAS,KAAAC,MAAS,KAgBX,IAAMC,EAAkB,SAA8B,CAC3D,GAAI,CACF,aAAMC,kBAAkB,MAAM,EAEvB,EACT,MAAQ,CACN,MAAO,EACT,CACF,EAOaC,EAAuB,MAAOC,GAAoD,CAC7F,GAAM,CAAE,IAAAC,EAAK,MAAAC,EAAO,OAAAC,CAAO,EAAIH,EACzBI,EAAa,KAAK,UAAUD,CAAM,EAGlCE,GAAU,MADFP,EAAE,CAAE,IAAK,CAAE,GAAGQ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U,OAAAC,CAAO,EAAIF,EAEvBG,EAAKC,EAAgBF,CAAM,EAC3BG,EAAQF,EAAKG,EAAaH,CAAE,EAAID,EAEtC,MAAO,GAAGD,CAAQ,IAAII,CAAK,EAC7B,EChBA,IAAME,EAA2B,IAAI,IAAI,CAAC,kBAAmB,kBAAkB,CAAC,EAE1EC,EAAuBC,GACpBA,aAAiB,OAASF,EAAyB,IAAIE,EAAM,IAAI,EAsB7DC,GAAwBC,GAA4B,CAC/D,GAAIH,EAAoBG,CAAK,EAAG,MAAO,GAEvC,IAAMC,EAASD,GAAkD,MAEjE,OAAOH,EAAoBI,CAAK,CAClC",
4
+ "sourcesContent": ["import process from 'node:process'\nimport { $ } from 'zx'\n\nimport type { CmuxLayoutNode } from 'src/dev/cmux-layout'\nimport { logger } from 'src/lib/logger'\n\n/** Args for {@link openCmuxDevWorkspace}: the workspace root, title, and pane layout tree. */\ninterface OpenCmuxDevWorkspaceArgs {\n cwd: string\n title: string\n layout: CmuxLayoutNode\n}\n\n/**\n * True iff the `cmux` CLI is invokable (i.e. `cmux --version` resolves). Used to\n * gate `--cmux` mode and fall back to single-process dev when cmux is absent.\n */\nexport const isCmuxAvailable = async (): Promise<boolean> => {\n try {\n await $`cmux --version`.quiet()\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Open ONE cmux workspace rooted at `cwd`, laid out per `layout` (one pane per\n * command). Runs in a `CMUX_QUIET=1` scoped env to suppress cmux's one-time compat\n * notice, then parses and returns the `workspace:<id>` ref from stdout.\n */\nexport const openCmuxDevWorkspace = async (args: OpenCmuxDevWorkspaceArgs): Promise<string> => {\n const { cwd, title, layout } = args\n const layoutJson = JSON.stringify(layout)\n\n const $cmux = $({ env: { ...process.env, CMUX_QUIET: '1' } })\n const output = (await $cmux`cmux new-workspace --name ${title} --cwd ${cwd} --focus false --layout ${layoutJson}`)\n .stdout\n\n return parseWorkspaceRef(output)\n}\n\n/**\n * Best-effort close of the cmux workspace `ref`, tearing down the workspace and\n * every pane process. Silently no-ops (debug-logged) if cmux isn't running or the\n * close fails, mirroring {@link file://./close-workspace-by-title.ts}.\n */\nexport const closeCmuxDevWorkspace = async (ref: string): Promise<void> => {\n try {\n await $`cmux close-workspace --workspace ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, ref }, 'cmux: skipped closing dev workspace')\n }\n}\n\n/**\n * Extract the `workspace:<id>` ref from `cmux new-workspace` output (e.g.\n * `OK workspace:5`). Throws a clear error when no ref is present.\n *\n * @example\n * parseWorkspaceRef('OK workspace:5\\n') // => 'workspace:5'\n */\nconst parseWorkspaceRef = (output: string): string => {\n const match = output.match(/workspace:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate workspace ref in new-workspace output')\n }\n\n return match[0]\n}\n", "/** Matches a `v`-prefixed semver token (e.g. `v1.48.0`) anchored on shape. */\nconst V_SEMVER_TOKEN_RE = /\\bv(\\d+\\.\\d+\\.\\d+)\\b/g\n\n/**\n * Canonicalizes a cmux workspace title into a stable dedup/close key.\n *\n * cmux workspace titles are human display strings built by\n * `buildCmuxWorkspaceTitle`, so the value stored when a workspace is created can\n * drift from the value rebuilt later \u2014 across whitespace and across CLI versions\n * (an older build titled version releases `v1.48.0`; the current build titles\n * them `1.48.0`). Keying dedup or close on the raw title silently creates\n * duplicate / unclosable workspaces whenever that drift occurs.\n *\n * Canonicalization collapses the known drift axes so both sides round-trip to an\n * equal key:\n * - trims and collapses internal whitespace to single spaces;\n * - normalizes a `v`-prefixed semver token to its bare form\n * (`v1.48.0` \u2192 `1.48.0`), anchored on semver shape so named releases that\n * merely start with `v` (e.g. `vega-redesign`) are left untouched.\n *\n * Non-release fallback titles (which may contain `/`, e.g. `feature/foo`) are\n * preserved as-is apart from whitespace normalization.\n *\n * @example\n * canonicalizeCmuxTitle('hulyo-monorepo v1.48.0') // => 'hulyo-monorepo 1.48.0'\n * canonicalizeCmuxTitle('hulyo-monorepo 1.48.0') // => 'hulyo-monorepo 1.48.0'\n * canonicalizeCmuxTitle('hulyo-monorepo vega-redesign') // => 'hulyo-monorepo vega-redesign'\n */\nexport const canonicalizeCmuxTitle = (raw: string): string => {\n return raw.trim().replace(/\\s+/g, ' ').replace(V_SEMVER_TOKEN_RE, '$1')\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\nimport { canonicalizeCmuxTitle } from './canonicalize-cmux-title'\n\n/**\n * Best-effort close of the cmux workspace whose title matches `title` (compared\n * via {@link canonicalizeCmuxTitle}, so a drifted stored title still resolves).\n * Silently no-ops if cmux isn't running, the workspace isn't found, or close fails.\n */\nexport const closeCmuxWorkspaceByTitle = async (title: string): Promise<void> => {\n try {\n const listOutput = (await $`cmux list-workspaces`.quiet()).stdout\n\n const ref = findWorkspaceRefByTitle(listOutput, title)\n\n if (!ref) {\n return\n }\n\n await $`cmux close-workspace --workspace ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, title }, 'cmux: skipped closing workspace')\n }\n}\n\n/**\n * Parses `cmux list-workspaces` output and returns the workspace ref whose\n * title matches `title`, or undefined if no match. Both sides are compared via\n * {@link canonicalizeCmuxTitle} so a workspace stored under a drifted title\n * (whitespace, or an older CLI's `v`-prefixed semver) is still found \u2014 keeping\n * close symmetric with the cmux open dedup in `worktrees-reload`.\n *\n * Each line looks like:\n * \" workspace:8 hulyo-monorepo 1.48.0\"\n * \"* workspace:6 obsidian-workspace [selected]\"\n */\nconst findWorkspaceRefByTitle = (output: string, title: string): string | undefined => {\n const target = canonicalizeCmuxTitle(title)\n\n for (const rawLine of output.split('\\n')) {\n // eslint-disable-next-line sonarjs/super-linear-regex, regexp/no-super-linear-backtracking\n const match = rawLine.match(/^[* ]\\s*(workspace:\\d+)\\s+(.+?)(?:\\s+\\[selected\\])?\\s*$/)\n\n if (!match) {\n continue\n }\n\n const ref = match[1]\n const lineTitle = match[2]?.trim() ?? ''\n\n if (canonicalizeCmuxTitle(lineTitle) === target) {\n return ref\n }\n }\n\n return undefined\n}\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\nimport { canonicalizeCmuxTitle } from './canonicalize-cmux-title'\n\n/**\n * Returns the set of **canonical** titles for all currently-open cmux\n * workspaces (see {@link canonicalizeCmuxTitle}). Keying on the canonical form\n * lets callers match a workspace even when its stored title drifted from the\n * title they rebuild (whitespace, or an older CLI's `v`-prefixed semver).\n * Returns an empty set if cmux isn't running, the call fails, or the output\n * can't be parsed \u2014 callers should treat \"empty\" as \"unknown, proceed as if\n * nothing is open\".\n *\n * Each line of `cmux list-workspaces` looks like:\n * \" workspace:8 hulyo-monorepo 1.48.0\"\n * \"* workspace:6 obsidian-workspace [selected]\"\n */\nexport const listCmuxWorkspaceTitles = async (): Promise<Set<string>> => {\n try {\n const output = (await $`cmux list-workspaces`.quiet()).stdout\n\n const titles = new Set<string>()\n\n for (const rawLine of output.split('\\n')) {\n // eslint-disable-next-line sonarjs/super-linear-regex, regexp/no-super-linear-backtracking\n const match = rawLine.match(/^[* ]\\s*workspace:\\d+\\s+(.+?)(?:\\s+\\[selected\\])?\\s*$/)\n\n if (!match) {\n continue\n }\n\n const title = match[1]?.trim()\n\n if (title) {\n titles.add(canonicalizeCmuxTitle(title))\n }\n }\n\n return titles\n } catch (error) {\n logger.debug({ error }, 'cmux: skipped listing workspace titles')\n\n return new Set()\n }\n}\n", "import { $ } from 'zx'\n\nimport { getInfraKitConfig, resolveCmuxLayout } from 'src/lib/infra-kit-config'\n\ninterface OpenCmuxWorkspaceArgs {\n cwd: string\n title?: string\n}\n\n/**\n * Opens a new cmux workspace rooted at `cwd`, with panes arranged per the\n * configured `worktrees.cmux.layout` (resolved via {@link resolveCmuxLayout},\n * default `two-columns`):\n * two-columns \u2014 left | right, both full-height (two panes)\n * three-pane \u2014 left-top / left-bottom | full-height right (three panes)\n * All panes inherit `cwd` from the workspace.\n */\nexport const openCmuxWorkspaceWithLayout = async (args: OpenCmuxWorkspaceArgs): Promise<void> => {\n const { cwd, title } = args\n\n const layout = resolveCmuxLayout(await getInfraKitConfig())\n\n const newWorkspaceOutput = (await $`cmux workspace create --cwd ${cwd}`).stdout\n\n const workspaceRef = parseWorkspaceRef(newWorkspaceOutput)\n\n const surfacesOutput = (await $`cmux list-pane-surfaces --workspace ${workspaceRef}`).stdout\n\n const leftTopRef = parseFirstSurfaceRef(surfacesOutput)\n\n // Both layouts share the vertical split into left | right columns; only the\n // legacy three-pane layout additionally splits the left column top/bottom.\n await $`cmux new-split right --workspace ${workspaceRef} --surface ${leftTopRef}`\n\n if (layout === 'three-pane') {\n await $`cmux new-split down --workspace ${workspaceRef} --surface ${leftTopRef}`\n }\n\n if (title) {\n await $`cmux workspace rename --workspace ${workspaceRef} --title ${title}`\n }\n}\n\n/**\n * Extracts the first `surface:<id>` reference from the output of\n * `cmux list-pane-surfaces`. Used to locate the initial (primary) pane\n * surface so subsequent splits can be anchored relative to it.\n *\n * @example\n * const output = 'surface:12 (active)\\nsurface:13\\n'\n * parseFirstSurfaceRef(output) // => 'surface:12'\n */\nconst parseFirstSurfaceRef = (output: string): string => {\n const match = output.match(/surface:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate initial surface in list-pane-surfaces output')\n }\n\n return match[0]\n}\n\n/**\n * Extracts the `workspace:<id>` reference from the output of\n * `cmux workspace create`. The returned ref is used to target the newly\n * created workspace in follow-up `cmux` commands (splits, rename, etc.).\n *\n * @example\n * const output = 'created workspace:7\\n'\n * parseWorkspaceRef(output) // => 'workspace:7'\n */\nconst parseWorkspaceRef = (output: string): string => {\n const match = output.match(/workspace:\\d+/)\n\n if (!match) {\n throw new Error('cmux: could not locate workspace ref in workspace create output')\n }\n\n return match[0]\n}\n", "import { displayLabel, parseBranchName } from 'src/lib/release-id'\n\ninterface BuildCmuxWorkspaceTitleArgs {\n repoName: string\n branch: string\n}\n\n/**\n * Builds the cmux workspace title used by `worktrees-add` and looked up by\n * `worktrees-remove`. Release branches are rendered via their release-id\n * display label so the title reads e.g. `\"hulyo-monorepo 1.48.0\"` for\n * `\"release/v1.48.0\"` and `\"hulyo-monorepo checkout-redesign\"` for\n * `\"release/checkout-redesign\"`. Non-release branches (cmux titles them too)\n * fall back to the raw branch string.\n */\nexport const buildCmuxWorkspaceTitle = (args: BuildCmuxWorkspaceTitleArgs): string => {\n const { repoName, branch } = args\n\n const id = parseBranchName(branch)\n const label = id ? displayLabel(id) : branch\n\n return `${repoName} ${label}`\n}\n", "/**\n * Names of the error classes thrown when an interactive prompt ends without a\n * value. From `@inquirer/core`: `ExitPromptError` (user pressed Ctrl-C / Esc) and\n * `AbortPromptError` (the prompt was aborted via an `AbortSignal`). From our own\n * Ink pickers: `PromptCancelledError` (see ./prompt-cancelled-error), which is\n * registered here rather than impersonating an inquirer class name. All are\n * intentional cancellations, not failures.\n */\nconst CANCELLATION_ERROR_NAMES = new Set(['ExitPromptError', 'AbortPromptError', 'PromptCancelledError'])\n\nconst hasCancellationName = (value: unknown): boolean => {\n return value instanceof Error && CANCELLATION_ERROR_NAMES.has(value.name)\n}\n\n/**\n * True when `error` represents a user (or signal) cancellation of an\n * `@inquirer/*` prompt \u2014 i.e. pressing Ctrl-C / Esc in the branch picker or a\n * confirm step. Matched by `name` rather than `instanceof` so it stays correct\n * even when pnpm dedupes more than one copy of `@inquirer/core` into the tree\n * (an `instanceof` check fails across realms/duplicate classes).\n *\n * Also unwraps one level of `cause`, so a cancellation re-wrapped in an\n * {@link ./operation-error.OperationError} is still recognised at the top-level\n * error boundary.\n *\n * @example\n * try {\n * await checkbox({ message: 'Select release branches', choices })\n * } catch (err) {\n * if (isPromptCancellation(err)) process.exit(0) // clean back-out, not an error\n * throw err\n * }\n */\nexport const isPromptCancellation = (error: unknown): boolean => {\n if (hasCancellationName(error)) return true\n\n const cause = (error as { cause?: unknown } | null | undefined)?.cause\n\n return hasCancellationName(cause)\n}\n"],
5
+ "mappings": "oEAAA,OAAOA,MAAa,eACpB,OAAS,KAAAC,MAAS,KAgBX,IAAMC,EAAkB,SAA8B,CAC3D,GAAI,CACF,aAAMC,kBAAkB,MAAM,EA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M,CAAC,CAChB,EAWML,EAAqBI,GAA2B,CACpD,IAAMC,EAAQD,EAAO,MAAM,eAAe,EAE1C,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,iEAAiE,EAGnF,OAAOA,EAAM,CAAC,CAChB,EChEO,IAAMC,EAA2BC,GAA8C,CACpF,GAAM,CAAE,SAAAC,EAAU,OAAAC,CAAO,EAAIF,EAEvBG,EAAKC,EAAgBF,CAAM,EAC3BG,EAAQF,EAAKG,EAAaH,CAAE,EAAID,EAEtC,MAAO,GAAGD,CAAQ,IAAII,CAAK,EAC7B,ECdA,IAAME,EAA2B,IAAI,IAAI,CAAC,kBAAmB,mBAAoB,sBAAsB,CAAC,EAElGC,EAAuBC,GACpBA,aAAiB,OAASF,EAAyB,IAAIE,EAAM,IAAI,EAsB7DC,GAAwBC,GAA4B,CAC/D,GAAIH,EAAoBG,CAAK,EAAG,MAAO,GAEvC,IAAMC,EAASD,GAAkD,MAEjE,OAAOH,EAAoBI,CAAK,CAClC",
6
6
  "names": ["process", "$", "isCmuxAvailable", "$", "openCmuxDevWorkspace", "args", "cwd", "title", "layout", "layoutJson", "output", "process", "parseWorkspaceRef", "closeCmuxDevWorkspace", "ref", "error", "logger", "match", "V_SEMVER_TOKEN_RE", "canonicalizeCmuxTitle", "raw", "$", "closeCmuxWorkspaceByTitle", "title", "listOutput", "$", "ref", "findWorkspaceRefByTitle", "error", "logger", "output", "target", "canonicalizeCmuxTitle", "rawLine", "match", "lineTitle", "$", "listCmuxWorkspaceTitles", "output", "$", "titles", "rawLine", "match", "title", "canonicalizeCmuxTitle", "error", "logger", "$", "openCmuxWorkspaceWithLayout", "args", "cwd", "title", "layout", "resolveCmuxLayout", "getInfraKitConfig", "newWorkspaceOutput", "$", "workspaceRef", "parseWorkspaceRef", "surfacesOutput", "leftTopRef", "parseFirstSurfaceRef", "output", "match", "buildCmuxWorkspaceTitle", "args", "repoName", "branch", "id", "parseBranchName", "label", "displayLabel", "CANCELLATION_ERROR_NAMES", "hasCancellationName", "value", "isPromptCancellation", "error", "cause"]
7
7
  }
@@ -0,0 +1,6 @@
1
+ import h from"node:process";var c=80,p=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],u=80,r={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",teal:"\x1B[36m",green:"\x1B[32m",blue:"\x1B[34m",red:"\x1B[31m"},a="\r\x1B[2K",f=/\x1B\[[0-9;]*m|\x1B\]8;;.*?\x1B\\/g,m=s=>s.replace(f,""),l=s=>String(s).padStart(2,"0"),v=s=>`${l(s.getHours())}:${l(s.getMinutes())}:${l(s.getSeconds())}`,$=s=>`${(s/1e3).toFixed(1)}s`,L=s=>{let t=s.proxyPort===c?"":`:${s.proxyPort}`;return`http://${s.alias}${t}${s.prefixUrl}`},d=class{deps;spinnerTimer=null;spinnerPhase="";spinnerFrame=0;constructor(t={}){this.deps={write:t.write??(e=>{h.stdout.write(e)}),appendLog:t.appendLog??(()=>{}),isTTY:t.isTTY??!!h.stdout.isTTY,now:t.now??(()=>new Date),verbose:t.verbose??!1}}color(t,e){return this.deps.isTTY?`${t}${e}${r.reset}`:e}hyperlink(t,e){return!this.deps.isTTY||t===""?e:`\x1B]8;;file://${encodeURI(t).replace(/[#?]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`)}\x1B\\${e}\x1B]8;;\x1B\\`}teeOnly(t,e){this.deps.appendLog(`[${this.deps.now().toISOString()}] [${e.toUpperCase()}] ${m(t)}
2
+ `)}tee(t,e){this.teeOnly(t,e)}dispose(){}emit(t){if(this.spinnerTimer!=null&&this.deps.isTTY){this.deps.write(`${a}${t}
3
+ `),this.paintSpinner();return}this.deps.write(`${t}
4
+ `)}log(t,e="info"){(e!=="debug"||this.deps.verbose)&&this.emit(t),this.tee(t,e)}narrate(t){this.deps.verbose&&this.emit(t),this.tee(t,"info")}logFn=(t,e="info")=>{this.log(t,e)};paintSpinner(){let t=p[this.spinnerFrame%p.length];this.deps.write(`${a}${this.color(r.teal,t)} ${this.color(r.dim,this.spinnerPhase)}`)}bootStep(t){if(this.tee(t,"info"),this.spinnerPhase=t,!this.deps.isTTY){this.deps.write(`${t}
5
+ `);return}this.spinnerTimer==null&&(this.spinnerTimer=setInterval(()=>{this.spinnerFrame+=1,this.paintSpinner()},u),this.spinnerTimer.unref?.()),this.paintSpinner()}stopSpinner(){this.spinnerTimer!=null&&(clearInterval(this.spinnerTimer),this.spinnerTimer=null),this.deps.isTTY&&this.deps.write(a)}healthDot(t){return t===null?"":t?this.color(r.green,"\u25CF ok"):this.color(r.red,"\u25CF down")}ready(t){this.stopSpinner();let e=this.formatReadyLines(t);for(let i of e)this.emit(i),this.tee(i,"info")}tagWidth(t){return[...t.endpoints.map(i=>i.tag),...t.uiRefs.map(i=>i.tag),...(t.failed??[]).map(i=>i.tag)].reduce((i,n)=>Math.max(i,n.length),0)}titleLine(t){let e=[t.target,t.watch?"watch":null,t.release].filter(g=>!!g).join(" \xB7 "),i=t.failed?.length??0,n=$(t.elapsedMs),o=i>0?this.color(r.red,`${i} failed \xB7 started in ${n}`):this.color(r.green,`ready in ${n}`);return` ${this.color(r.bold,"infra-kit dev")} ${this.color(r.dim,e)} ${o}`}legendLines(t){let e=t.watch&&t.watchSummary?`watching ${t.watchSummary}`:"watch off",i=this.hyperlink(t.logHref,t.logPath),n=`${e} logs \u2192 ${i}`,o="\u2500".repeat(60);return[` ${this.color(r.dim,n)}`,` ${this.color(r.dim,o)}`]}uiRefLine(t,e){return` ${this.color(r.teal,t.padEnd(e))} ${this.color(r.dim,"\u2192 starting below (vite prints its URL)")}`}endpointLine(t,e,i){let n=i?this.healthDot(t.healthy):"",o=n?` ${n}`:"";return` ${this.color(r.teal,t.tag.padEnd(e))} ${this.color(r.blue,t.url)}${o}`}failedLine(t,e){return` ${this.color(r.teal,t.tag.padEnd(e))} ${this.color(r.red,"\u25CF failed")} ${this.color(r.dim,t.reason)}`}formatLines(t,{withHealthDot:e}){let i=this.tagWidth(t),n=["",this.titleLine(t),""];for(let o of t.endpoints)n.push(this.endpointLine(o,i,e));for(let o of t.failed??[])n.push(this.failedLine(o,i));for(let o of t.uiRefs)n.push(this.uiRefLine(o.tag,i));return n.push("",...this.legendLines(t)),n}formatHeaderLines(t){return this.formatLines(t,{withHealthDot:!1})}formatFooterLines(t){let e=this.tagWidth(t);return t.endpoints.filter(i=>i.healthy!==null).map(i=>` ${this.color(r.teal,i.tag.padEnd(e))} ${this.healthDot(i.healthy)}`)}formatReadyLines(t){return this.formatLines(t,{withHealthDot:!0})}event(t){let e=v(this.deps.now()),i=` ${this.color(r.dim,e)} ${this.color(r.teal,t.tag)} ${t.text}`;this.emit(i),this.tee(`${t.tag} ${t.text}`,"info")}};export{v as a,L as b,d as c};
6
+ //# sourceMappingURL=chunk-C2HRONYA.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/dev/render.ts"],
4
+ "sourcesContent": ["/**\n * Terminal renderer for `infra-kit dev` \u2014 a calm-print layer (never a full-screen TUI) that owns\n * every line the dev-server writes to the terminal, plus the tee to the session log (`logs.txt`).\n *\n * Design (see `.omc/plans/dev-log-redesign.md`): the boot collapses into a single transient spinner;\n * the final screen leads with per-server endpoints + health; the live tail is tagged + timestamped.\n * Full detail always reaches the log file regardless of `--verbose`.\n *\n * All I/O is injected (`write` / `appendLog` / `isTTY` / `now`) so every frame is snapshot-testable\n * and the spinner is deterministically disabled in tests (`isTTY: false`). The renderer coexists with\n * a child that owns its own TTY (vite via `turbo run dev`), because that child starts only AFTER\n * {@link DevRenderer.ready} has cleared the spinner \u2014 the spinner is never live concurrently with\n * inherited child output.\n */\nimport process from 'node:process'\n\nimport type { DevUi } from './dev-ui.js'\n\n/**\n * The port a bare `http://` URL implies. Elided from the hero URL so it matches the port-free\n * `dev.proxy` local template. Inlined rather than imported from `lib/infra-kit-config` to keep this\n * renderer free of the config module's zod import graph.\n */\nconst DEFAULT_HTTP_PORT = 80\n\nexport type LogLevel = 'info' | 'warn' | 'error' | 'debug'\n\n/** Injected I/O seams. Defaults wire to the real stdout + a caller-provided file appender. */\nexport interface DevRendererDeps {\n /** Terminal sink (default: `process.stdout.write`). */\n write: (text: string) => void\n /** File tee \u2014 always receives full detail (default: no-op; the runner passes its log appender). */\n appendLog: (text: string) => void\n /** Whether the terminal is a TTY. Gates the spinner + ANSI color; false in CI / when piped. */\n isTTY: boolean\n /** Clock seam (default: `() => new Date()`), so timestamps + `ready in Xs` are testable. */\n now: () => Date\n /** When true, boot narration reaches the terminal; otherwise it is file-only. */\n verbose: boolean\n}\n\n/** One resolved backend endpoint row in the ready header. */\nexport interface EndpointRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** The app's `.localhost` alias URL \u2014 the only form, since an app that cannot be aliased never starts. */\n url: string\n /** Liveness: `true` \u2192 `\u25CF ok`, `false` \u2192 `\u25CF down`, `null` \u2192 no dot (not probed). */\n healthy: boolean | null\n}\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\n/**\n * An app that was asked for but never came up. It has no URL and no health \u2014 but it MUST still get a\n * row: the header is a report of what the user asked for, and an app that silently vanishes from it\n * reads as \"not requested\" rather than \"broken\".\n */\nexport interface FailedRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** One-line reason, e.g. `config is missing field: 'connectionURL'`. */\n reason: string\n}\n\n/** Everything {@link DevRenderer.ready} needs to paint the final header in one shot. */\nexport interface ReadySummary {\n /** Resolved preset / target label (e.g. `client`, `*`). */\n target: string\n watch: boolean\n /**\n * True when this session launches a `turbo run dev` UI child that inherits the TTY. It is the\n * authoritative \"is this a UI session?\" signal \u2014 NOT `uiRefs.length > 0`. A UI whose port the runner\n * pre-assigned becomes an {@link EndpointRow}, not a {@link UiRef}, so `uiRefs` is normally empty even\n * for a UI session; any live region painted then would scribble into vite's inherited output. The\n * scroll-region footer (which tolerates the child) is chosen on this flag instead.\n */\n hasUiChild: boolean\n /** Slugified release for the header meta; omitted outside a git repo. */\n release?: string\n /** Backend readiness time in ms (UI is fire-and-forget, so this is BE-only \u2014 labeled honestly). */\n elapsedMs: number\n /** Real backend endpoint rows (owned ports + pre-probed health). */\n endpoints: EndpointRow[]\n /** UI apps that print their own URL below. */\n uiRefs: UiRef[]\n /**\n * Apps that failed to start. Optional only so the (many) existing summaries need not restate an\n * empty list; a non-empty one downgrades the title from a green `ready` to an honest `N failed`.\n */\n failed?: FailedRow[]\n /** Human watch summary, e.g. `1 app \u00B7 5 packages`; omitted when not watching. */\n watchSummary?: string\n /** Compact, human-readable log path shown as the `logs \u2192 \u2026` label (e.g. `~/.cache/infra-kit/<session>/logs.txt`). */\n logPath: string\n /** Absolute log path backing the clickable OSC-8 hyperlink (wrapped as `file://<logHref>`). */\n logHref: string\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 * Resolve the endpoint URL for an app: `http://<alias><:proxyPort?><prefix>`, where `alias` is the\n * portless hostname the runner registered (e.g. `feat-x.backend-api.localhost`). The runner refuses to\n * start an app it could not alias, so there is no port-form to fall back to.\n *\n * The default proxy port is `80`, which is elided: the URL is then byte-identical to the `dev.proxy`\n * local template (`http://<release>.<packageName>.localhost`) that `infra-kit/vite` proxies to, so what\n * the table prints and what the frontend calls cannot drift. An unprivileged port (zero sudo) keeps its\n * `:<port>` suffix, and `withProxyPort` grafts the same one onto the vite target.\n */\nexport const resolveEndpointUrl = (input: { prefixUrl: string; alias: string; proxyPort: number }): string => {\n const suffix = input.proxyPort === DEFAULT_HTTP_PORT ? '' : `:${input.proxyPort}`\n\n return `http://${input.alias}${suffix}${input.prefixUrl}`\n}\n\nexport class DevRenderer implements DevUi {\n private readonly deps: DevRendererDeps\n private spinnerTimer: ReturnType<typeof setInterval> | null = null\n private spinnerPhase = ''\n private spinnerFrame = 0\n\n constructor(deps: Partial<DevRendererDeps> = {}) {\n this.deps = {\n write:\n deps.write ??\n ((text: string): void => {\n process.stdout.write(text)\n }),\n appendLog: deps.appendLog ?? ((): void => {}),\n isTTY: deps.isTTY ?? Boolean(process.stdout.isTTY),\n now:\n deps.now ??\n ((): Date => {\n return new Date()\n }),\n verbose: deps.verbose ?? false,\n }\n }\n\n /** Wrap `s` in an ANSI color on a TTY; return it untouched when piped (deterministic snapshots). */\n private color(code: string, s: string): string {\n return this.deps.isTTY ? `${code}${s}${ANSI.reset}` : s\n }\n\n /**\n * Wrap `label` in an OSC-8 terminal hyperlink to `href` (a filesystem path \u2192 `file://` URI) so the\n * log path is cmd/ctrl-clickable. Returns the bare `label` when piped (deterministic snapshots) or\n * when `href` is empty \u2014 terminals without OSC-8 support silently ignore the escapes anyway.\n */\n private hyperlink(href: string, label: string): string {\n if (!this.deps.isTTY || href === '') return label\n\n // `encodeURI` escapes spaces / non-ASCII but leaves `#` and `?`, which a file URI reads as a\n // fragment / query \u2014 encode those too so a path containing them still resolves to the real file.\n const uri = encodeURI(href).replace(/[#?]/g, (c) => {\n return `%${c.charCodeAt(0).toString(16).toUpperCase()}`\n })\n\n return `\\x1B]8;;file://${uri}\\x1B\\\\${label}\\x1B]8;;\\x1B\\\\`\n }\n\n /**\n * Append one line to the log file ONLY \u2014 the canonical `[iso] [LEVEL] msg` shape, no terminal write.\n * The single source of the file-tee format: the private {@link tee} and the Ink boot UI both route\n * here, so the log file stays identical whichever renderer is live.\n */\n teeOnly(message: string, level: LogLevel): void {\n this.deps.appendLog(`[${this.deps.now().toISOString()}] [${level.toUpperCase()}] ${stripAnsi(message)}\\n`)\n }\n\n /** File tee for a line that is ALSO written to the terminal; delegates the format to {@link teeOnly}. */\n private tee(message: string, level: LogLevel): void {\n this.teeOnly(message, level)\n }\n\n /**\n * No-op for the plain renderer: it owns no Ink / raw-mode terminal state to release. Present to\n * satisfy {@link DevUi} so the runner can call `dispose()` uniformly. Idempotent by construction.\n */\n dispose(): void {\n // Nothing to release \u2014 the plain renderer never seizes the terminal.\n }\n\n /**\n * Write one terminal line spinner-safely: if the spinner is live on a TTY, erase it, print the\n * line, then repaint the spinner, so a mid-boot message never shreds the `\\r`-based spinner.\n */\n private emit(line: string): void {\n if (this.spinnerTimer != null && this.deps.isTTY) {\n this.deps.write(`${CLEAR_LINE}${line}\\n`)\n this.paintSpinner()\n\n return\n }\n\n this.deps.write(`${line}\\n`)\n }\n\n /** A general message routed by level (terminal + file tee). Debug is terminal-only in verbose. */\n log(message: string, level: LogLevel = 'info'): void {\n if (level !== 'debug' || this.deps.verbose) {\n this.emit(message)\n }\n this.tee(message, level)\n }\n\n /** A boot-narration step: terminal only when `--verbose`, but always tee'd to the log. */\n narrate(message: string): void {\n if (this.deps.verbose) {\n this.emit(message)\n }\n this.tee(message, 'info')\n }\n\n /** `LogFn`-shaped adapter for the build runner seam (which passes `(msg, level)`). */\n readonly logFn = (message: string, level: LogLevel = 'info'): void => {\n this.log(message, level)\n }\n\n // ---- boot spinner -------------------------------------------------------\n\n /** Paint the current spinner frame in place (TTY only). */\n private paintSpinner(): void {\n const frame = SPINNER_FRAMES[this.spinnerFrame % SPINNER_FRAMES.length]!\n\n this.deps.write(`${CLEAR_LINE}${this.color(ANSI.teal, frame)} ${this.color(ANSI.dim, this.spinnerPhase)}`)\n }\n\n /**\n * Update the boot phase. On a TTY this drives a single transient spinner line; when piped it\n * prints one plain phase line (no ANSI, deterministic). Always tee'd to the log.\n */\n bootStep(phase: string): void {\n this.tee(phase, 'info')\n this.spinnerPhase = phase\n\n if (!this.deps.isTTY) {\n this.deps.write(`${phase}\\n`)\n\n return\n }\n\n if (this.spinnerTimer == null) {\n this.spinnerTimer = setInterval(() => {\n this.spinnerFrame += 1\n this.paintSpinner()\n }, SPINNER_INTERVAL_MS)\n // Never keep the event loop alive for the spinner alone.\n this.spinnerTimer.unref?.()\n }\n this.paintSpinner()\n }\n\n /** Stop + erase the spinner line (idempotent). Called before the ready header prints. */\n stopSpinner(): void {\n if (this.spinnerTimer != null) {\n clearInterval(this.spinnerTimer)\n this.spinnerTimer = null\n }\n if (this.deps.isTTY) {\n this.deps.write(CLEAR_LINE)\n }\n }\n\n // ---- the ready header ---------------------------------------------------\n\n /** Format the health dot for an endpoint row (`\u25CF ok` / `\u25CF down` / '' when unprobed). */\n private healthDot(healthy: boolean | null): string {\n if (healthy === null) return ''\n if (healthy) return this.color(ANSI.green, '\u25CF ok')\n\n return this.color(ANSI.red, '\u25CF down')\n }\n\n /**\n * Collapse the boot and print the final header in one shot: title line, one endpoint row per\n * backend server (with health dot), a reference line per UI app, the watch line, the clickable\n * log path, and a separator rule. Synchronous \u2014 health is pre-probed by the caller.\n */\n ready(summary: ReadySummary): void {\n this.stopSpinner()\n\n const lines = this.formatReadyLines(summary)\n\n for (const line of lines) {\n this.emit(line)\n this.tee(line, 'info')\n }\n }\n\n /** Column width for the aligned `tag` gutter \u2014 the widest endpoint/UI/failed tag. */\n private tagWidth(summary: ReadySummary): number {\n const tags = [\n ...summary.endpoints.map((e) => {\n return e.tag\n }),\n ...summary.uiRefs.map((u) => {\n return u.tag\n }),\n ...(summary.failed ?? []).map((f) => {\n return f.tag\n }),\n ]\n\n return tags.reduce((w, t) => {\n return Math.max(w, t.length)\n }, 0)\n }\n\n /**\n * The `infra-kit dev \u00B7 <meta> ready in Xs` title line.\n *\n * A green `ready` is a claim about the whole session, so it is spent only when the whole session\n * is up. With anything in `failed` the status turns red and counts the casualties instead \u2014 the\n * boot time alone, next to a green word, is exactly how a half-dead session used to pass for a\n * healthy one.\n */\n private titleLine(summary: ReadySummary): string {\n const meta = [summary.target, summary.watch ? 'watch' : null, summary.release]\n .filter((s): s is string => {\n return Boolean(s)\n })\n .join(' \u00B7 ')\n\n const failedCount = summary.failed?.length ?? 0\n const elapsed = formatElapsed(summary.elapsedMs)\n const status =\n failedCount > 0\n ? this.color(ANSI.red, `${failedCount} failed \u00B7 started in ${elapsed}`)\n : this.color(ANSI.green, `ready in ${elapsed}`)\n\n return ` ${this.color(ANSI.bold, 'infra-kit dev')} ${this.color(ANSI.dim, meta)} ${status}`\n }\n\n /** The static legend tail: watch line + clickable log path, then a separator rule. */\n private legendLines(summary: ReadySummary): string[] {\n const watchText = summary.watch && summary.watchSummary ? `watching ${summary.watchSummary}` : 'watch off'\n const logLink = this.hyperlink(summary.logHref, summary.logPath)\n const watchLine = `${watchText} logs \u2192 ${logLink}`\n const rule = '\u2500'.repeat(60)\n\n return [` ${this.color(ANSI.dim, watchLine)}`, ` ${this.color(ANSI.dim, rule)}`]\n }\n\n /** A UI reference row (`client/ui \u2192 starting below \u2026`) \u2014 used only when infra-kit could not claim its port. */\n private uiRefLine(tag: string, tagWidth: number): string {\n return ` ${this.color(ANSI.teal, tag.padEnd(tagWidth))} ${this.color(\n ANSI.dim,\n '\u2192 starting below (vite prints its URL)',\n )}`\n }\n\n /** One endpoint row (`client/api http://\u2026`); appends a health dot only when `withHealthDot` and the endpoint is probed. */\n private endpointLine(endpoint: ReadySummary['endpoints'][number], tagWidth: number, withHealthDot: boolean): string {\n const dot = withHealthDot ? this.healthDot(endpoint.healthy) : ''\n const dotSuffix = dot ? ` ${dot}` : ''\n\n return ` ${this.color(ANSI.teal, endpoint.tag.padEnd(tagWidth))} ${this.color(ANSI.blue, endpoint.url)}${dotSuffix}`\n }\n\n /** One failed row (`client/api \u25CF failed <reason>`) \u2014 no URL, because there is nothing listening. */\n private failedLine(failed: FailedRow, tagWidth: number): string {\n return ` ${this.color(ANSI.teal, failed.tag.padEnd(tagWidth))} ${this.color(\n ANSI.red,\n '\u25CF failed',\n )} ${this.color(ANSI.dim, failed.reason)}`\n }\n\n /**\n * Shared header layout: blank, title line, blank, one endpoint row per backend, a reference row per\n * UI app, then the watch/log legend. `withHealthDot` is the ONLY difference between the static Ink\n * header (false \u2014 health is live, the footer owns it) and the ready/boot frame (true).\n */\n private formatLines(summary: ReadySummary, { withHealthDot }: { withHealthDot: boolean }): string[] {\n const tagWidth = this.tagWidth(summary)\n const lines: string[] = ['', this.titleLine(summary), '']\n\n for (const e of summary.endpoints) {\n lines.push(this.endpointLine(e, tagWidth, withHealthDot))\n }\n // Failures sit with the live rows, not in the scrollback above: the log line announcing the crash\n // is metres up the terminal by now, and the header is the only thing the user actually reads.\n for (const f of summary.failed ?? []) {\n lines.push(this.failedLine(f, tagWidth))\n }\n for (const u of summary.uiRefs) {\n lines.push(this.uiRefLine(u.tag, 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 * Live status lines for the persistent Ink footer, re-rendered in place as health flips (never\n * committed to `<Static>`): one health row per PROBED backend endpoint (`client/api \u25CF ok`).\n * Unprobed endpoints (`healthy === null`) are omitted. Pure; colors follow `isTTY`.\n */\n formatFooterLines(summary: ReadySummary): string[] {\n const tagWidth = this.tagWidth(summary)\n\n return summary.endpoints\n .filter((e) => {\n return e.healthy !== null\n })\n .map((e) => {\n return ` ${this.color(ANSI.teal, e.tag.padEnd(tagWidth))} ${this.healthDot(e.healthy)}`\n })\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": "AAcA,OAAOA,MAAa,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AG,IAAIA,EAAM,IAAI,GAAI,MAAM,CAC/C,CACF",
6
+ "names": ["process", "DEFAULT_HTTP_PORT", "SPINNER_FRAMES", "SPINNER_INTERVAL_MS", "ANSI", "CLEAR_LINE", "ANSI_PATTERN", "stripAnsi", "pad2", "n", "formatClock", "d", "formatElapsed", "ms", "resolveEndpointUrl", "input", "suffix", "DevRenderer", "deps", "text", "code", "s", "href", "label", "c", "message", "level", "line", "frame", "phase", "healthy", "summary", "lines", "e", "u", "f", "w", "t", "meta", "failedCount", "elapsed", "status", "watchText", "logLink", "watchLine", "rule", "tag", "tagWidth", "endpoint", "withHealthDot", "dot", "dotSuffix", "failed", "ts"]
7
+ }
@@ -0,0 +1,3 @@
1
+ import T from"node:crypto";import r from"node:fs";import F from"node:os";import n from"node:path";import A from"node:process";var V="env-load.sh",a="env-clear.sh",p="projects",O=7200,E="INFRA_KIT_SESSION",m="INFRA_KIT_ENV",C="INFRA_KIT_ENV_CONFIG",D="INFRA_KIT_ENV_PROJECT",S="INFRA_KIT_ENV_PROJECT_ROOT",K="INFRA_KIT_ENV_LOADED_AT",g="INFRA_KIT_ENV_AUTOLOADED",x="INFRA_KIT_ENV_CLEARED",I=/^([A-Z_]\w*)=/i,L=(t,e)=>{let o=e;for(let _=0;_<t.length;_++){if(!o&&t[_]==="\\"){_++;continue}t[_]==="'"&&(o=!o)}return o},h=t=>{if(!r.existsSync(t))return[];let e=r.readFileSync(t,"utf-8"),o=[],_=!1;for(let s of e.split(`
2
+ `)){if(!_){let c=I.exec(s);c&&o.push(c[1])}_=L(s,_)}return o},R=()=>{let t=A.env.XDG_CACHE_HOME,e=t&&t.length>0?t:n.join(F.homedir(),".cache");return n.join(e,"infra-kit")},f=()=>{let t=A.env[E];if(!t)throw new Error(`${E} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return n.join(R(),t)},i=t=>T.createHash("sha256").update(t,"utf8").digest("hex"),N=()=>n.join(R(),p),u=t=>n.join(N(),i(t)),l=(t,e,o)=>{let _=`${t}.tmp.${A.pid}`;r.writeFileSync(_,e,{mode:o});try{r.renameSync(_,t)}catch(s){throw r.rmSync(_,{force:!0}),s}},y="-worktrees";export{V as a,a as b,O as c,E as d,m as e,C as f,D as g,S as h,K as i,g as j,x as k,h as l,R as m,f as n,N as o,u as p,l as q,y as r};
3
+ //# sourceMappingURL=chunk-CHETBZ6M.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/lib/constants/constants.ts", "../src/lib/command-echo/command-echo.ts"],
4
- "sourcesContent": ["import crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nexport const ENV_LOAD_FILE = 'env-load.sh'\nexport const ENV_CLEAR_FILE = 'env-clear.sh'\n\n/** Subdir of the cache root holding the project-scoped WARM caches (one dir per\n * project, keyed by {@link warmCacheKey}). Kept in sync with the zsh block in\n * init.ts, which reads `$cache_root/projects/$key/env-load.sh`. */\nexport const WARM_CACHE_SUBDIR = 'projects'\n\n/**\n * Default warm-cache TTL in seconds (2h). Governs BOTH the node-side eviction\n * sweep and the zsh-side source gate (`_INFRA_KIT_WARM_TTL` in the shell block);\n * the two MUST stay equal, so this constant is the single source of truth and the\n * shell default is emitted from it. Short by design: a warm file older than this\n * is never sourced (bounds a revoked/rotated secret served at prompt-0) and is\n * deleted on the next write. The background refresh lands in ~1-2s regardless.\n */\nexport const DEFAULT_WARM_TTL_SECONDS = 2 * 60 * 60\n\nexport const INFRA_KIT_SESSION_VAR = 'INFRA_KIT_SESSION'\n/**\n * The active environment/config NAME (e.g. `dev`, `arthur`), exported plainly so\n * non-shell consumers can read it from `process.env`. Notably `infra-kit/vite`'s\n * `infraKitDev()` reads this to interpolate the `<env>` placeholder in cloud proxy\n * targets. Mirrors {@link INFRA_KIT_ENV_CONFIG_VAR} (same value) but is the stable,\n * purpose-named handle for tooling rather than the shell session-metadata var.\n */\nexport const INFRA_KIT_ENV_VAR = 'INFRA_KIT_ENV'\nexport const INFRA_KIT_ENV_CONFIG_VAR = 'INFRA_KIT_ENV_CONFIG'\nexport const INFRA_KIT_ENV_PROJECT_VAR = 'INFRA_KIT_ENV_PROJECT'\n/**\n * Absolute project root (git top-level) the loaded env belongs to. Lets the shell\n * startup gate tell a same-project subshell (skip) from a NEW project (load), so a\n * different project's secrets are never silently kept after `cd`/new shell.\n */\nexport const INFRA_KIT_ENV_PROJECT_ROOT_VAR = 'INFRA_KIT_ENV_PROJECT_ROOT'\nexport const INFRA_KIT_ENV_LOADED_AT_VAR = 'INFRA_KIT_ENV_LOADED_AT'\n/**\n * Marker exported into env-load.sh ONLY when the load was triggered automatically\n * (see lib/env-autoload). Its presence is the sole signal distinguishing an\n * auto-loaded env from a deliberate manual `env-load`, so auto-load never\n * clobbers a manual choice. A manual load unsets it.\n */\nexport const INFRA_KIT_ENV_AUTOLOADED_VAR = 'INFRA_KIT_ENV_AUTOLOADED'\n/**\n * Suppression sentinel exported by env-clear. While set in a shell, cli-invocation\n * auto-load stays silent (a deliberate clear must not be immediately re-loaded).\n * Lifted by a manual `env-load` or a new shell.\n */\nexport const INFRA_KIT_ENV_CLEARED_VAR = 'INFRA_KIT_ENV_CLEARED'\n\n/**\n * Matches a line of the form `KEY=...` where KEY is an env-var identifier\n * (letter or underscore, then word chars). Capture group 1 is the name. Shared\n * between env-load (validation, var counting) and parseVarNamesFromEnvFile.\n */\nexport const ENV_VAR_LINE_PATTERN = /^([A-Z_]\\w*)=/i\n\n/**\n * Track whether a physical line leaves us inside an open single-quoted value,\n * mirroring how `shellSingleQuote` emits values (`'\u2026'`, with literal quotes as\n * `'\\''`). Outside a quote a backslash escapes the next char; inside a quote a\n * `'` closes it. Lets the parser skip the continuation lines of a multiline value.\n */\nconst advanceSingleQuoteState = (line: string, startInQuote: boolean): boolean => {\n let inQuote = startInQuote\n\n for (let i = 0; i < line.length; i++) {\n if (!inQuote && line[i] === '\\\\') {\n i++\n continue\n }\n\n if (line[i] === \"'\") {\n inQuote = !inQuote\n }\n }\n\n return inQuote\n}\n\nexport const parseVarNamesFromEnvFile = (filePath: string): string[] => {\n if (!fs.existsSync(filePath)) return []\n\n const content = fs.readFileSync(filePath, 'utf-8')\n const names: string[] = []\n let inQuote = false\n\n for (const line of content.split('\\n')) {\n // Only a line that starts OUTSIDE a quoted value can be a real assignment;\n // continuation lines of a multiline secret value are skipped.\n if (!inQuote) {\n const match = ENV_VAR_LINE_PATTERN.exec(line)\n\n if (match) {\n names.push(match[1]!)\n }\n }\n\n inQuote = advanceSingleQuoteState(line, inQuote)\n }\n\n return names\n}\n\n/**\n * Root cache dir for infra-kit across all sessions. Resolved from\n * $XDG_CACHE_HOME when set, falling back to ~/.cache/infra-kit. Keep in sync\n * with the shell block emitted by `infra-kit init` (src/commands/init/init.ts).\n */\nexport const getCacheRoot = (): string => {\n const xdg = process.env.XDG_CACHE_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), '.cache')\n\n return path.join(base, 'infra-kit')\n}\n\nexport const getSessionCacheDir = (): string => {\n const session = process.env[INFRA_KIT_SESSION_VAR]\n\n if (!session) {\n throw new Error(`${INFRA_KIT_SESSION_VAR} is not set. Run \\`infra-kit init\\` then \\`source ~/.zshrc\\`.`)\n }\n\n return path.join(getCacheRoot(), session)\n}\n\n/**\n * The warm-cache key for a project: the hex SHA-256 of its CANONICAL (realpath'd)\n * directory. This MUST be byte-identical to the zsh block's\n * `printf %s \"$canon\" | shasum -a 256 | cut -c1-64` \u2014 same input string (no\n * trailing newline), same digest, full 64-hex output \u2014 or a warm file written by\n * node is never found by the shell. The shell passes the already-canonicalized\n * dir via `--project-dir`, so node hashes that VERBATIM (it does not re-resolve).\n */\nexport const warmCacheKey = (canonicalProjectDir: string): string => {\n return crypto.createHash('sha256').update(canonicalProjectDir, 'utf8').digest('hex')\n}\n\n/** Root holding all project-scoped warm caches: `$cacheRoot/projects`. */\nexport const getWarmCacheRoot = (): string => {\n return path.join(getCacheRoot(), WARM_CACHE_SUBDIR)\n}\n\n/** This project's warm-cache dir: `$cacheRoot/projects/<warmCacheKey>`. */\nexport const getProjectWarmCacheDir = (canonicalProjectDir: string): string => {\n return path.join(getWarmCacheRoot(), warmCacheKey(canonicalProjectDir))\n}\n\n/**\n * Write content atomically: write to a pid-suffixed temp file in the same\n * directory, then rename. fs.renameSync is atomic on a single filesystem, so\n * concurrent writers can't produce a half-written secret file.\n */\nexport const atomicWriteFileSync = (filePath: string, content: string, mode: number): void => {\n const tmpPath = `${filePath}.tmp.${process.pid}`\n\n fs.writeFileSync(tmpPath, content, { mode })\n\n try {\n fs.renameSync(tmpPath, filePath)\n } catch (error) {\n fs.rmSync(tmpPath, { force: true })\n throw error\n }\n}\n\nexport const WORKTREES_DIR_SUFFIX = '-worktrees'\n// eslint-disable-next-line sonarjs/publicly-writable-directories\nexport const LOG_FILE_PATH = '/tmp/mcp-infra-kit.log'\n", "import { logger } from 'src/lib/logger'\n\ninterface CommandOption {\n flag: string\n value: string | string[] | boolean\n}\n\nconst createCommandEcho = () => {\n let commandName = ''\n let options: CommandOption[] = []\n let isInteractive = false\n\n return {\n /**\n * Initialize command echo for a new command\n */\n start(name: string): void {\n commandName = name\n options = []\n isInteractive = false\n },\n\n /**\n * Mark that the command had interactive input (prompts)\n * Call this once when ANY prompt happens\n */\n setInteractive(): void {\n isInteractive = true\n },\n\n /**\n * Track an option selection\n * @param flag The CLI flag (e.g., \"--versions\")\n * @param value The selected value\n */\n addOption(flag: string, value: string | string[] | boolean): void {\n options.push({ flag, value })\n },\n\n /**\n * Print the equivalent CLI command if there was interactive input\n */\n print(): void {\n if (!isInteractive || options.length === 0) {\n return\n }\n\n const formattedOptions = options\n .map((opt) => {\n if (typeof opt.value === 'boolean') {\n return opt.value ? opt.flag : ''\n }\n\n if (Array.isArray(opt.value)) {\n return `${opt.flag} \"${opt.value.join(', ')}\"`\n }\n\n return `${opt.flag} \"${opt.value}\"`\n })\n .filter(Boolean)\n .join(' ')\n\n logger.info(`\uD83D\uDCDF Equivalent command: \\npnpm exec infra-kit ${commandName} ${formattedOptions}\\n`)\n },\n\n /**\n * Reset state (useful for testing)\n */\n reset(): void {\n commandName = ''\n options = []\n isInteractive = false\n },\n }\n}\n\n// Singleton instance (same pattern as logger)\nexport const commandEcho = createCommandEcho()\n"],
5
- "mappings": "wCAAA,OAAOA,MAAY,cACnB,OAAOC,MAAQ,UACf,OAAOC,MAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,MAAa,eAEb,IAAMC,EAAgB,cAChBC,EAAiB,eAKjBC,EAAoB,WAUpBC,EAA2B,KAE3BC,EAAwB,oBAQxBC,EAAoB,gBACpBC,EAA2B,uBAC3BC,EAA4B,wBAM5BC,EAAiC,6BACjCC,EAA8B,0BAO9BC,EAA+B,2BAM/BC,EAA4B,wBAO5BC,EAAuB,iBAQ9BC,EAA0B,CAACC,EAAcC,IAAmC,CAChF,IAAIC,EAAUD,EAEd,QAASE,EAAI,EAAGA,EAAIH,EAAK,OAAQG,IAAK,CACpC,GAAI,CAACD,GAAWF,EAAKG,CAAC,IAAM,KAAM,CAChCA,IACA,QACF,CAEIH,EAAKG,CAAC,IAAM,MACdD,EAAU,CAACA,EAEf,CAEA,OAAOA,CACT,EAEaE,EAA4BC,GAA+B,CACtE,GAAI,CAACvB,EAAG,WAAWuB,CAAQ,EAAG,MAAO,CAAC,EAEtC,IAAMC,EAAUxB,EAAG,aAAauB,EAAU,OAAO,EAC3CE,EAAkB,CAAC,EACrBL,EAAU,GAEd,QAAWF,KAAQM,EAAQ,MAAM;AAAA,CAAI,EAAG,CAGtC,GAAI,CAACJ,EAAS,CACZ,IAAMM,EAAQV,EAAqB,KAAKE,CAAI,EAExCQ,GACFD,EAAM,KAAKC,EAAM,CAAC,CAAE,CAExB,CAEAN,EAAUH,EAAwBC,EAAME,CAAO,CACjD,CAEA,OAAOK,CACT,EAOaE,EAAe,IAAc,CACxC,IAAMC,EAAMzB,EAAQ,IAAI,eAClB0B,EAAOD,GAA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ACtB,IAAKM,GACA,OAAOA,EAAI,OAAU,UAChBA,EAAI,MAAQA,EAAI,KAAO,GAG5B,MAAM,QAAQA,EAAI,KAAK,EAClB,GAAGA,EAAI,IAAI,KAAKA,EAAI,MAAM,KAAK,IAAI,CAAC,IAGtC,GAAGA,EAAI,IAAI,KAAKA,EAAI,KAAK,GACjC,EACA,OAAO,OAAO,EACd,KAAK,GAAG,EAEXC,EAAO,KAAK;AAAA,sBAAgDR,CAAW,IAAIM,CAAgB;AAAA,CAAI,CACjG,EAKA,OAAc,CACZN,EAAc,GACdC,EAAU,CAAC,EACXC,EAAgB,EAClB,CACF,CACF,EAGaO,EAAcV,EAAkB",
6
- "names": ["crypto", "fs", "os", "path", "process", "ENV_LOAD_FILE", "ENV_CLEAR_FILE", "WARM_CACHE_SUBDIR", "DEFAULT_WARM_TTL_SECONDS", "INFRA_KIT_SESSION_VAR", "INFRA_KIT_ENV_VAR", "INFRA_KIT_ENV_CONFIG_VAR", "INFRA_KIT_ENV_PROJECT_VAR", "INFRA_KIT_ENV_PROJECT_ROOT_VAR", "INFRA_KIT_ENV_LOADED_AT_VAR", "INFRA_KIT_ENV_AUTOLOADED_VAR", "INFRA_KIT_ENV_CLEARED_VAR", "ENV_VAR_LINE_PATTERN", "advanceSingleQuoteState", "line", "startInQuote", "inQuote", "i", "parseVarNamesFromEnvFile", "filePath", "content", "names", "match", "getCacheRoot", "xdg", "base", "getSessionCacheDir", "session", "warmCacheKey", "canonicalProjectDir", "getWarmCacheRoot", "getProjectWarmCacheDir", "atomicWriteFileSync", "mode", "tmpPath", "error", "WORKTREES_DIR_SUFFIX", "createCommandEcho", "commandName", "options", "isInteractive", "name", "flag", "value", "formattedOptions", "opt", "logger", "commandEcho"]
3
+ "sources": ["../src/lib/constants/constants.ts"],
4
+ "sourcesContent": ["import crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nexport const ENV_LOAD_FILE = 'env-load.sh'\nexport const ENV_CLEAR_FILE = 'env-clear.sh'\n\n/** Subdir of the cache root holding the project-scoped WARM caches (one dir per\n * project, keyed by {@link warmCacheKey}). Kept in sync with the zsh block in\n * init.ts, which reads `$cache_root/projects/$key/env-load.sh`. */\nexport const WARM_CACHE_SUBDIR = 'projects'\n\n/**\n * Default warm-cache TTL in seconds (2h). Governs BOTH the node-side eviction\n * sweep and the zsh-side source gate (`_INFRA_KIT_WARM_TTL` in the shell block);\n * the two MUST stay equal, so this constant is the single source of truth and the\n * shell default is emitted from it. Short by design: a warm file older than this\n * is never sourced (bounds a revoked/rotated secret served at prompt-0) and is\n * deleted on the next write. The background refresh lands in ~1-2s regardless.\n */\nexport const DEFAULT_WARM_TTL_SECONDS = 2 * 60 * 60\n\nexport const INFRA_KIT_SESSION_VAR = 'INFRA_KIT_SESSION'\n/**\n * The active environment/config NAME (e.g. `dev`, `arthur`), exported plainly so\n * non-shell consumers can read it from `process.env`. Notably `infra-kit/vite`'s\n * `infraKitDev()` reads this to interpolate the `<env>` placeholder in cloud proxy\n * targets. Mirrors {@link INFRA_KIT_ENV_CONFIG_VAR} (same value) but is the stable,\n * purpose-named handle for tooling rather than the shell session-metadata var.\n */\nexport const INFRA_KIT_ENV_VAR = 'INFRA_KIT_ENV'\nexport const INFRA_KIT_ENV_CONFIG_VAR = 'INFRA_KIT_ENV_CONFIG'\nexport const INFRA_KIT_ENV_PROJECT_VAR = 'INFRA_KIT_ENV_PROJECT'\n/**\n * Absolute project root (git top-level) the loaded env belongs to. Lets the shell\n * startup gate tell a same-project subshell (skip) from a NEW project (load), so a\n * different project's secrets are never silently kept after `cd`/new shell.\n */\nexport const INFRA_KIT_ENV_PROJECT_ROOT_VAR = 'INFRA_KIT_ENV_PROJECT_ROOT'\nexport const INFRA_KIT_ENV_LOADED_AT_VAR = 'INFRA_KIT_ENV_LOADED_AT'\n/**\n * Marker exported into env-load.sh ONLY when the load was triggered automatically\n * (see lib/env-autoload). Its presence is the sole signal distinguishing an\n * auto-loaded env from a deliberate manual `env-load`, so auto-load never\n * clobbers a manual choice. A manual load unsets it.\n */\nexport const INFRA_KIT_ENV_AUTOLOADED_VAR = 'INFRA_KIT_ENV_AUTOLOADED'\n/**\n * Suppression sentinel exported by env-clear. While set in a shell, cli-invocation\n * auto-load stays silent (a deliberate clear must not be immediately re-loaded).\n * Lifted by a manual `env-load` or a new shell.\n */\nexport const INFRA_KIT_ENV_CLEARED_VAR = 'INFRA_KIT_ENV_CLEARED'\n\n/**\n * Matches a line of the form `KEY=...` where KEY is an env-var identifier\n * (letter or underscore, then word chars). Capture group 1 is the name. Shared\n * between env-load (validation, var counting) and parseVarNamesFromEnvFile.\n */\nexport const ENV_VAR_LINE_PATTERN = /^([A-Z_]\\w*)=/i\n\n/**\n * Track whether a physical line leaves us inside an open single-quoted value,\n * mirroring how `shellSingleQuote` emits values (`'\u2026'`, with literal quotes as\n * `'\\''`). Outside a quote a backslash escapes the next char; inside a quote a\n * `'` closes it. Lets the parser skip the continuation lines of a multiline value.\n */\nconst advanceSingleQuoteState = (line: string, startInQuote: boolean): boolean => {\n let inQuote = startInQuote\n\n for (let i = 0; i < line.length; i++) {\n if (!inQuote && line[i] === '\\\\') {\n i++\n continue\n }\n\n if (line[i] === \"'\") {\n inQuote = !inQuote\n }\n }\n\n return inQuote\n}\n\nexport const parseVarNamesFromEnvFile = (filePath: string): string[] => {\n if (!fs.existsSync(filePath)) return []\n\n const content = fs.readFileSync(filePath, 'utf-8')\n const names: string[] = []\n let inQuote = false\n\n for (const line of content.split('\\n')) {\n // Only a line that starts OUTSIDE a quoted value can be a real assignment;\n // continuation lines of a multiline secret value are skipped.\n if (!inQuote) {\n const match = ENV_VAR_LINE_PATTERN.exec(line)\n\n if (match) {\n names.push(match[1]!)\n }\n }\n\n inQuote = advanceSingleQuoteState(line, inQuote)\n }\n\n return names\n}\n\n/**\n * Root cache dir for infra-kit across all sessions. Resolved from\n * $XDG_CACHE_HOME when set, falling back to ~/.cache/infra-kit. Keep in sync\n * with the shell block emitted by `infra-kit init` (src/commands/init/init.ts).\n */\nexport const getCacheRoot = (): string => {\n const xdg = process.env.XDG_CACHE_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), '.cache')\n\n return path.join(base, 'infra-kit')\n}\n\nexport const getSessionCacheDir = (): string => {\n const session = process.env[INFRA_KIT_SESSION_VAR]\n\n if (!session) {\n throw new Error(`${INFRA_KIT_SESSION_VAR} is not set. Run \\`infra-kit init\\` then \\`source ~/.zshrc\\`.`)\n }\n\n return path.join(getCacheRoot(), session)\n}\n\n/**\n * The warm-cache key for a project: the hex SHA-256 of its CANONICAL (realpath'd)\n * directory. This MUST be byte-identical to the zsh block's\n * `printf %s \"$canon\" | shasum -a 256 | cut -c1-64` \u2014 same input string (no\n * trailing newline), same digest, full 64-hex output \u2014 or a warm file written by\n * node is never found by the shell. The shell passes the already-canonicalized\n * dir via `--project-dir`, so node hashes that VERBATIM (it does not re-resolve).\n */\nexport const warmCacheKey = (canonicalProjectDir: string): string => {\n return crypto.createHash('sha256').update(canonicalProjectDir, 'utf8').digest('hex')\n}\n\n/** Root holding all project-scoped warm caches: `$cacheRoot/projects`. */\nexport const getWarmCacheRoot = (): string => {\n return path.join(getCacheRoot(), WARM_CACHE_SUBDIR)\n}\n\n/** This project's warm-cache dir: `$cacheRoot/projects/<warmCacheKey>`. */\nexport const getProjectWarmCacheDir = (canonicalProjectDir: string): string => {\n return path.join(getWarmCacheRoot(), warmCacheKey(canonicalProjectDir))\n}\n\n/**\n * Write content atomically: write to a pid-suffixed temp file in the same\n * directory, then rename. fs.renameSync is atomic on a single filesystem, so\n * concurrent writers can't produce a half-written secret file.\n */\nexport const atomicWriteFileSync = (filePath: string, content: string, mode: number): void => {\n const tmpPath = `${filePath}.tmp.${process.pid}`\n\n fs.writeFileSync(tmpPath, content, { mode })\n\n try {\n fs.renameSync(tmpPath, filePath)\n } catch (error) {\n fs.rmSync(tmpPath, { force: true })\n throw error\n }\n}\n\nexport const W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,EAAK,KAAK2B,EAAM,WAAW,CACpC,EAEaC,EAAqB,IAAc,CAC9C,IAAMC,EAAU5B,EAAQ,IAAIK,CAAqB,EAEjD,GAAI,CAACuB,EACH,MAAM,IAAI,MAAM,GAAGvB,CAAqB,+DAA+D,EAGzG,OAAON,EAAK,KAAKyB,EAAa,EAAGI,CAAO,CAC1C,EAUaC,EAAgBC,GACpBlC,EAAO,WAAW,QAAQ,EAAE,OAAOkC,EAAqB,MAAM,EAAE,OAAO,KAAK,EAIxEC,EAAmB,IACvBhC,EAAK,KAAKyB,EAAa,EAAGrB,CAAiB,EAIvC6B,EAA0BF,GAC9B/B,EAAK,KAAKgC,EAAiB,EAAGF,EAAaC,CAAmB,CAAC,EAQ3DG,EAAsB,CAACb,EAAkBC,EAAiBa,IAAuB,CAC5F,IAAMC,EAAU,GAAGf,CAAQ,QAAQpB,EAAQ,GAAG,GAE9CH,EAAG,cAAcsC,EAASd,EAAS,CAAE,KAAAa,CAAK,CAAC,EAE3C,GAAI,CACFrC,EAAG,WAAWsC,EAASf,CAAQ,CACjC,OAASgB,EAAO,CACd,MAAAvC,EAAG,OAAOsC,EAAS,CAAE,MAAO,EAAK,CAAC,EAC5BC,CACR,CACF,EAEaC,EAAuB",
6
+ "names": ["crypto", "fs", "os", "path", "process", "ENV_LOAD_FILE", "ENV_CLEAR_FILE", "WARM_CACHE_SUBDIR", "DEFAULT_WARM_TTL_SECONDS", "INFRA_KIT_SESSION_VAR", "INFRA_KIT_ENV_VAR", "INFRA_KIT_ENV_CONFIG_VAR", "INFRA_KIT_ENV_PROJECT_VAR", "INFRA_KIT_ENV_PROJECT_ROOT_VAR", "INFRA_KIT_ENV_LOADED_AT_VAR", "INFRA_KIT_ENV_AUTOLOADED_VAR", "INFRA_KIT_ENV_CLEARED_VAR", "ENV_VAR_LINE_PATTERN", "advanceSingleQuoteState", "line", "startInQuote", "inQuote", "i", "parseVarNamesFromEnvFile", "filePath", "content", "names", "match", "getCacheRoot", "xdg", "base", "getSessionCacheDir", "session", "warmCacheKey", "canonicalProjectDir", "getWarmCacheRoot", "getProjectWarmCacheDir", "atomicWriteFileSync", "mode", "tmpPath", "error", "WORKTREES_DIR_SUFFIX"]
7
7
  }
@@ -0,0 +1,2 @@
1
+ import o from"node:path";var i="infra-kit",s=`${i}@latest`,d=(n,t,e)=>{let r=o.relative(e(o.resolve(n)),o.resolve(t));return r!==""&&!r.startsWith("..")&&!o.isAbsolute(r)},a=(n,t)=>o.resolve(n).split(o.sep).includes(t),p=(n,t,e,r)=>{let l=n[t];return l!=null&&l!==""&&d(l,e,r)},f=[{manager:"volta",test:({selfRealPath:n,env:t,realpath:e})=>p(t,"VOLTA_HOME",n,e)||a(n,".volta")||a(n,"volta"),updateCommand:["volta","install",i],canSelfSpawn:!0},{manager:"homebrew",test:({selfRealPath:n,env:t,realpath:e})=>a(n,"Cellar")||p(t,"HOMEBREW_PREFIX",n,e),updateCommand:["brew","upgrade",i],canSelfSpawn:!1},{manager:"pnpm",test:({selfRealPath:n,env:t,realpath:e})=>p(t,"PNPM_HOME",n,e)||a(n,"pnpm")&&a(n,"global"),updateCommand:["pnpm","add","-g",s],canSelfSpawn:!0},{manager:"bun",test:({selfRealPath:n,env:t,realpath:e})=>p(t,"BUN_INSTALL",n,e)||a(n,".bun"),updateCommand:["bun","add","-g",s],canSelfSpawn:!0},{manager:"yarn",test:({selfRealPath:n})=>a(n,".yarn")||a(n,"yarn")&&a(n,"global"),updateCommand:["yarn","global","add",s],canSelfSpawn:!0},{manager:"npm",test:({selfRealPath:n,env:t,realpath:e})=>p(t,"npm_config_prefix",n,e),updateCommand:["npm","install","-g",s],canSelfSpawn:!0}],g=["npm","install","-g",s],M=n=>{let{selfRealPath:t,env:e,realpath:r,lazyNpmRoot:l}=n,m=f.find(({test:c})=>c({selfRealPath:t,env:e,realpath:r}));if(m)return{manager:m.manager,updateCommand:m.updateCommand,canSelfSpawn:m.canSelfSpawn};let u=l?.();return u!=null&&u!==""&&d(u,t,r)?{manager:"npm",updateCommand:g,canSelfSpawn:!0}:{manager:"unknown",updateCommand:g,canSelfSpawn:!1}},S=(n,t,e)=>a(n,"node_modules")&&d(t,n,e);import{realpathSync as I}from"node:fs";import h from"node:path";var b=n=>{try{return I(n)}catch{return h.resolve(n)}};import{execFileSync as w}from"node:child_process";import v from"node:process";var x=3e3,y=()=>{try{let t=w("npm",["root","-g"],{encoding:"utf-8",timeout:x,stdio:["ignore","pipe","ignore"],shell:v.platform==="win32"}).trim();return t===""?void 0:t}catch{return}};export{i as a,M as b,S as c,y as d,b as e};
2
+ //# sourceMappingURL=chunk-F6VCGS3D.js.map