infra-kit 0.3.11 → 0.3.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-ADCSGQAU.js +2 -0
- package/dist/{chunk-JXLXSX7Q.js.map → chunk-ADCSGQAU.js.map} +1 -1
- package/dist/{chunk-M46KGMQ6.js → chunk-DWZSB6O6.js} +4 -4
- package/dist/{chunk-M46KGMQ6.js.map → chunk-DWZSB6O6.js.map} +2 -2
- package/dist/{chunk-KPQTJQ42.js → chunk-LJVPQQ75.js} +2 -2
- package/dist/{chunk-KPQTJQ42.js.map → chunk-LJVPQQ75.js.map} +1 -1
- package/dist/chunk-M5FC2MOJ.js +220 -0
- package/dist/chunk-M5FC2MOJ.js.map +7 -0
- package/dist/{chunk-PZ2AWWGK.js → chunk-VISEADOF.js} +2 -2
- package/dist/cli.js +10 -10
- package/dist/cli.js.map +3 -3
- package/dist/dev-server.js +2 -2
- package/dist/{dev-wizard-run-S5HEFLYE.js → dev-wizard-run-4SVW4W3I.js} +2 -2
- package/dist/mcp.js +1 -1
- package/dist/mcp.js.map +4 -4
- package/dist/update-check.js +1 -1
- package/package.json +6 -6
- package/readme.md +1 -1
- package/dist/chunk-JXLXSX7Q.js +0 -2
- package/dist/chunk-VNHAMXNA.js +0 -218
- package/dist/chunk-VNHAMXNA.js.map +0 -7
- /package/dist/{chunk-PZ2AWWGK.js.map → chunk-VISEADOF.js.map} +0 -0
- /package/dist/{dev-wizard-run-S5HEFLYE.js.map → dev-wizard-run-4SVW4W3I.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as _}from"./chunk-LKKKDB6V.js";import{B as c,N as L,V as A,X as O,g as S,m as R}from"./chunk-DWZSB6O6.js";import B from"node:process";import{$ as w}from"zx";var M=async()=>{try{return await w`cmux --version`.quiet(),!0}catch{return!1}},j=async r=>{let{cwd:e,title:t,layout:o}=r,s=JSON.stringify(o),n=(await w({env:{...B.env,CMUX_QUIET:"1"}})`cmux new-workspace --name ${t} --cwd ${e} --focus false --layout ${s}`).stdout;return U(n)},F=async r=>{try{await w`cmux close-workspace --workspace ${r}`.quiet()}catch(e){c.debug({error:e,ref:r},"cmux: skipped closing dev workspace")}},U=r=>{let e=r.match(/workspace:\d+/);if(!e)throw new Error("cmux: could not locate workspace ref in new-workspace output");return e[0]};import{$ as J}from"zx";import{realpath as q}from"node:fs/promises";import{$ as I}from"zx";var y=async r=>{try{return await q(r)}catch{return r}},P=async()=>{try{let[r,e]=await Promise.all([I`cmux workspace list --json`.quiet(),I`cmux workspace-group list --json`.quiet()]),t=JSON.parse(r.stdout).workspaces??[],o=JSON.parse(e.stdout).groups??[],s=new Set(o.map(n=>n.anchor_workspace_ref).filter(n=>typeof n=="string")),a=new Map;for(let n of t)!n.current_directory||s.has(n.ref)||a.set(await y(n.current_directory),n.ref);return a}catch(r){return c.debug({error:r},"cmux: skipped listing workspaces by cwd"),new Map}};var G=async r=>{try{let t=(await P()).get(await y(r));if(!t)return;await J`cmux workspace close ${t}`.quiet()}catch(e){c.debug({error:e,cwd:r},"cmux: skipped closing workspace by cwd")}};import{$ as k}from"zx";var N=async r=>{try{let e=(await k`cmux workspace-group list --json`.quiet()).stdout;return(JSON.parse(e).groups??[]).find(s=>s.name===r)?.ref??null}catch(e){return c.debug({error:e,name:r},"cmux: skipped group lookup"),null}},H=async(r,e)=>{try{let o=(await k`cmux workspace-group create --name ${r} --from ${e.join(",")}`).stdout.match(/workspace_group:\d+/)?.[0]??await N(r);return o&&await k`cmux workspace-group pin ${o}`.quiet(),o??null}catch(t){return c.warn({error:t,name:r},"\u26A0\uFE0F cmux: failed to create workspace group"),null}};import{$ as m}from"zx";var z=async r=>{let{cwd:e,title:t,group:o}=r,s=A(await O()),a=o?(await m`cmux workspace create --cwd ${e} --group ${o} --group-placement end`).stdout:(await m`cmux workspace create --cwd ${e}`).stdout,n=Q(a),p=(await m`cmux list-pane-surfaces --workspace ${n}`).stdout,u=K(p);return await m`cmux new-split right --workspace ${n} --surface ${u}`,s==="three-pane"&&await m`cmux new-split down --workspace ${n} --surface ${u}`,t&&await m`cmux workspace rename --workspace ${n} --title ${t}`,n},K=r=>{let e=r.match(/surface:\d+/);if(!e)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return e[0]},Q=r=>{let e=r.match(/workspace:\d+/);if(!e)throw new Error("cmux: could not locate workspace ref in workspace create output");return e[0]};var V=r=>{let{branch:e}=r,t=S(e);return t?R(t):e};var X=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),T=r=>r instanceof Error&&X.has(r.name),ne=r=>{if(T(r))return!0;let e=r?.cause;return T(e)};import{loadDev as Y}from"@slip-stream-kit/config/internal";import Z from"node:path";var rr=(r,e)=>{let t=new Set;for(let o of Object.values(r))for(let s of Object.keys(L(o,e).proxy))t.add(s);return[...t]},er=async(r,e)=>{let t={},o=[];return await Promise.all(e.map(async s=>{try{let n=(await Y(Z.join(r,"apps",s,"ui")))?.proxy?.routes;if(!n)return;t[s]=Object.fromEntries(Object.entries(n).map(([p,u])=>[p,u.packageName]))}catch(a){o.push({app:s,message:a instanceof Error?a.message:String(a)})}})),{routePkg:(s,a)=>t[s]?.[a],loadErrors:o}},pe=async(r,e,t,o)=>{let{routePkg:s,loadErrors:a}=await er(r,rr(e,t));return{ctx:{discovered:t,apiPkgByApp:Object.fromEntries(o.map(n=>[n.name,n.packageName])),routePkg:s},loadErrors:a}};import{execFile as tr}from"node:child_process";import{createHash as or}from"node:crypto";import{existsSync as W,readFileSync as d}from"node:fs";import sr from"node:http";import nr from"node:https";import ar from"node:net";import{homedir as ir}from"node:os";import{dirname as h,join as l}from"node:path";import f from"node:process";import cr from"node:tls";import{fileURLToPath as ur}from"node:url";import{promisify as pr}from"node:util";var mr=pr(tr),lr=r=>{let e=JSON.parse(d(r,"utf-8")),t=typeof e.bin=="string"?e.bin:e.bin?.portless;return t==null||t===""?null:t},fr=()=>{try{let r=h(ur(import.meta.url));for(;;){let e=l(r,"node_modules","portless","package.json");if(W(e)){let o=lr(e);return o==null?null:l(h(e),o)}let t=h(r);if(t===r)return null;r=t}}catch{return null}},b,D=()=>(b===void 0&&(b=fr()),b),gr=/^[\w@%+=:,./-]+$/,dr="'\\''",xr=r=>gr.test(r)?r:`'${r.replaceAll("'",dr)}'`,ve=(r,e)=>{let t=[e.execPath??f.execPath,e.bin,...r];return(e.sudo===!0?"sudo ":"")+t.map(xr).join(" ")},yr=1500,C=1500,wr="x-portless",E="127.0.0.1",Pr="localhost",kr="/Library/LaunchDaemons/sh.portless.proxy.plist",hr="/etc/systemd/system/portless.service",br=(r=W)=>{try{return f.platform==="darwin"?r(kr)?"yes":"no":f.platform==="linux"?r(hr)?"yes":"no":"unknown"}catch{return"unknown"}},Cr=r=>new Promise(e=>{let t=ar.connect({host:E,port:r}),o=s=>{t.destroy(),e(s)};t.setTimeout(C),t.once("connect",()=>{o(!0)}),t.once("timeout",()=>{o(!1)}),t.once("error",()=>{o(!1)})}),Er=(r,e)=>new Promise(t=>{let s=(e?nr.request:sr.request)({host:E,port:r,method:"HEAD",path:"/",timeout:C,...e?{rejectUnauthorized:!1,servername:Pr}:{}},a=>{a.resume(),t(a.headers[wr]==="1")});s.on("error",()=>{t(!1)}),s.on("timeout",()=>{s.destroy(),t(!1)}),s.end()}),vr=async(r,{timeoutMs:e})=>{let t=D();if(t==null)throw new Error("portless is not installed (not resolvable from node_modules)");await mr(f.execPath,[t,...r],{signal:AbortSignal.timeout(e),encoding:"utf-8",env:_(f.env)})},v=()=>f.env.PORTLESS_STATE_DIR??l(ir(),".portless"),Sr="ca.pem",Rr="ca.trusted",$=()=>l(v(),Sr),Se=()=>{try{let r=d(l(v(),Rr),"utf-8").trim();return r===""?!1:or("sha256").update(d($())).digest("hex")===r.toLowerCase()}catch{return!1}},Re=(r,e)=>new Promise(t=>{let o;try{o=d($())}catch{t({ok:!1,code:"ENOENT"});return}let s=cr.connect({host:E,port:r,servername:e,ca:[o],rejectUnauthorized:!0},()=>{let a=s.authorizationError,n=s.authorized;s.destroy(),t(n?{ok:!0}:{ok:!1,code:a?.code??a?.message??"UNKNOWN"})});s.setTimeout(C),s.once("timeout",()=>{s.destroy(),t({ok:!1,code:"ETIMEDOUT"})}),s.once("error",a=>{s.destroy(),t({ok:!1,code:a.code??"UNKNOWN"})})}),Le=()=>{try{let r=JSON.parse(d(l(v(),"routes.json"),"utf-8"));return Array.isArray(r)?r.flatMap(e=>{let{hostname:t,port:o}=e??{};return typeof t!="string"||t===""||typeof o!="number"?[]:[{name:t,port:o}]}):[]}catch{return[]}},Ae=(r={})=>{let e=r.bin===void 0?D():r.bin,t=r.run??vr,o=r.isListening??Cr,s=r.isProxyServing??Er,a=r.isServiceInstalled??br,n=r.timeoutMs??yr,p=null,u=async i=>{try{return await t(i,{timeoutMs:n}),!0}catch{return!1}},x=async()=>(p??=await u(["--version"]),p);return{binPath:()=>e,isAvailable:x,isProxyServing:async(i,g)=>!await x()||!await o(i)?!1:s(i,g),probeProxy:async(i,g)=>await o(i)?await s(i,g)?"serving":"not-portless":"daemon-down",isServiceInstalled:a,registerAlias:async(i,g)=>await x()?u(["alias",i,String(g)]):!1,removeAlias:async i=>{await x()&&await u(["alias","--remove",i])}}};export{pe as a,fr as b,ve as c,Cr as d,Er as e,$ as f,Se as g,Re as h,Le as i,Ae as j,y as k,P as l,G as m,N as n,H as o,M as p,j as q,F as r,z as s,V as t,ne as u};
|
|
2
|
+
//# sourceMappingURL=chunk-ADCSGQAU.js.map
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/integrations/cmux/open-dev-workspace.ts", "../src/integrations/cmux/close-workspace-by-cwd.ts", "../src/integrations/cmux/list-workspaces-by-cwd.ts", "../src/integrations/cmux/cmux-groups.ts", "../src/integrations/cmux/open-workspace-with-layout.ts", "../src/integrations/cmux/workspace-title.ts", "../src/lib/errors/is-prompt-cancellation.ts", "../src/dev/preset-proxy-context.ts", "../src/dev/proxy/portless-driver.ts"],
|
|
4
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-cwd.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", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\nimport { listCmuxWorkspacesByCwd, realpathForCmuxCwd } from './list-workspaces-by-cwd'\n\n/**\n * Best-effort close of the cmux workspace rooted at `cwd`. Resolves the workspace\n * ref via {@link listCmuxWorkspacesByCwd} (which excludes group anchors, so this\n * can never close a group header) and closes it. Silently no-ops if cmux isn't\n * running, no workspace matches the cwd, or the close fails.\n *\n * Called BEFORE `git worktree remove`, so `cwd` still exists and normalizes the\n * same way as cmux's reported `current_directory`.\n */\nexport const closeCmuxWorkspaceByCwd = async (cwd: string): Promise<void> => {\n try {\n const byCwd = await listCmuxWorkspacesByCwd()\n\n const ref = byCwd.get(await realpathForCmuxCwd(cwd))\n\n if (!ref) {\n return\n }\n\n await $`cmux workspace close ${ref}`.quiet()\n } catch (error) {\n logger.debug({ error, cwd }, 'cmux: skipped closing workspace by cwd')\n }\n}\n", "import { realpath } from 'node:fs/promises'\nimport { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\ninterface CmuxWorkspaceListEntry {\n ref: string\n current_directory: string | null\n}\n\ninterface CmuxGroupListEntry {\n anchor_workspace_ref: string | null\n}\n\n/**\n * Resolve `path` through the filesystem, falling back to the input when it can't\n * be resolved (e.g. the directory was already removed). Both the cmux-reported\n * cwd and the caller's target cwd are normalized the same way so a macOS\n * `/var`\u2192`/private/var` style symlink can't make two equal paths compare unequal\n * (the realpath-asymmetry footgun this repo has been burned by before).\n */\nconst safeRealpath = async (path: string): Promise<string> => {\n try {\n return await realpath(path)\n } catch {\n return path\n }\n}\n\n/**\n * Build a `realpath(cwd) \u2192 workspace ref` map of every currently-open cmux\n * workspace, keyed on its working directory. This is the dedup/close identity for\n * infra-kit's worktree workspaces \u2014 unique per worktree, and (unlike the title)\n * stable after the repo-name title prefix was dropped (two repos can share a\n * branch name like `fix-post-script-ci-cd`, but never a worktree path).\n *\n * Two entries are deliberately excluded:\n * - workspaces with no `current_directory` (e.g. `infra-kit dev` panes) \u2014 they\n * carry no worktree identity;\n * - group ANCHOR workspaces \u2014 cmux reports the anchor's cwd as the main-repo\n * root, so it collides with the real main-checkout workspace. Keying an\n * anchor into the map would shadow the main workspace (breaking dedup) and,\n * worse, let close-by-cwd close the group header. Anchors are dropped up front\n * via `workspace-group list`'s `anchor_workspace_ref`.\n *\n * Returns an empty map if cmux isn't running or the output can't be parsed \u2014\n * callers treat \"empty\" as \"unknown, proceed as if nothing is open\".\n */\nexport const listCmuxWorkspacesByCwd = async (): Promise<Map<string, string>> => {\n try {\n const [workspacesOutput, groupsOutput] = await Promise.all([\n $`cmux workspace list --json`.quiet(),\n $`cmux workspace-group list --json`.quiet(),\n ])\n\n const workspaces = (JSON.parse(workspacesOutput.stdout).workspaces ?? []) as CmuxWorkspaceListEntry[]\n const groups = (JSON.parse(groupsOutput.stdout).groups ?? []) as CmuxGroupListEntry[]\n\n const anchorRefs = new Set(\n groups\n .map((group) => {\n return group.anchor_workspace_ref\n })\n .filter((ref): ref is string => {\n return typeof ref === 'string'\n }),\n )\n\n const byCwd = new Map<string, string>()\n\n for (const workspace of workspaces) {\n if (!workspace.current_directory || anchorRefs.has(workspace.ref)) {\n continue\n }\n\n byCwd.set(await safeRealpath(workspace.current_directory), workspace.ref)\n }\n\n return byCwd\n } catch (error) {\n logger.debug({ error }, 'cmux: skipped listing workspaces by cwd')\n\n return new Map()\n }\n}\n\n/** Exported for callers that need the same normalization when looking up a target cwd. */\nexport { safeRealpath as realpathForCmuxCwd }\n", "import { $ } from 'zx'\n\nimport { logger } from 'src/lib/logger'\n\ninterface CmuxGroupListEntry {\n ref: string\n name: string\n}\n\n/**\n * Return the `workspace_group:N` ref of the sidebar group titled exactly `name`,\n * or `null` if no such group exists (or cmux is unreachable). Group names are the\n * repo name (basename of the main-repo root), so worktree workspaces for one repo\n * all resolve to the same group regardless of which worktree the command runs in.\n */\nexport const findCmuxGroupRefByName = async (name: string): Promise<string | null> => {\n try {\n const output = (await $`cmux workspace-group list --json`.quiet()).stdout\n\n const groups = (JSON.parse(output).groups ?? []) as CmuxGroupListEntry[]\n\n const match = groups.find((group) => {\n return group.name === name\n })\n\n return match?.ref ?? null\n } catch (error) {\n logger.debug({ error, name }, 'cmux: skipped group lookup')\n\n return null\n }\n}\n\n/**\n * Create a pinned sidebar group named `name` seeded with EXACTLY `fromRefs`, and\n * return its ref (or `null` on failure).\n *\n * `--from` is load-bearing: `cmux workspace-group create` defaults `--from` to the\n * currently-selected/caller workspace, so omitting it silently captures an\n * unrelated workspace (and, under the `--all` fan-out, steals a sibling repo's\n * freshly-created workspace). Passing the seed refs explicitly makes creation\n * deterministic and capture-free \u2014 no snapshot/self-heal needed. The group also\n * gets a synthetic anchor workspace (its header row), matching how the user's\n * groups are already shaped.\n */\nexport const createCmuxGroupFrom = async (name: string, fromRefs: string[]): Promise<string | null> => {\n try {\n const output = (await $`cmux workspace-group create --name ${name} --from ${fromRefs.join(',')}`).stdout\n\n const ref = output.match(/workspace_group:\\d+/)?.[0] ?? (await findCmuxGroupRefByName(name))\n\n if (ref) {\n await $`cmux workspace-group pin ${ref}`.quiet()\n }\n\n return ref ?? null\n } catch (error) {\n logger.warn({ error, name }, '\u26A0\uFE0F cmux: failed to create workspace group')\n\n return null\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 * When set, the workspace is created directly inside this sidebar group\n * (`workspace_group:N` ref) via `--group`, appended at the end so existing\n * members aren't reordered. Omit to create an ungrouped workspace (e.g. the\n * first worktree of a repo, which then seeds a new group).\n */\n group?: 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. Returns the created\n * `workspace:N` ref so callers can seed a group from it.\n */\nexport const openCmuxWorkspaceWithLayout = async (args: OpenCmuxWorkspaceArgs): Promise<string> => {\n const { cwd, title, group } = args\n\n const layout = resolveCmuxLayout(await getInfraKitConfig())\n\n const newWorkspaceOutput = group\n ? (await $`cmux workspace create --cwd ${cwd} --group ${group} --group-placement end`).stdout\n : (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 return workspaceRef\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 branch: string\n}\n\n/**\n * Builds the cmux workspace title for a worktree. The title is now just the\n * branch's display label \u2014 the repo name is NOT prefixed, because every worktree\n * workspace lives inside a per-repo sidebar GROUP whose header already carries the\n * repo name (e.g. group `hulyo-monorepo` \u2192 workspaces titled `1.48.0`,\n * `checkout-redesign`, `dev`). Release branches render via their release-id label\n * (`release/v1.48.0` \u2192 `1.48.0`, `release/checkout-redesign` \u2192 `checkout-redesign`);\n * non-release branches fall back to the raw branch string.\n *\n * Note: the title is NO LONGER a dedup/close key \u2014 that role moved to the\n * workspace cwd (see {@link listCmuxWorkspacesByCwd}), because dropping the repo\n * prefix makes titles collide across repos (both hulyo and travelist can have a\n * `fix-post-script-ci-cd` branch).\n */\nexport const buildCmuxWorkspaceTitle = (args: BuildCmuxWorkspaceTitleArgs): string => {\n const { branch } = args\n\n const id = parseBranchName(branch)\n\n return id ? displayLabel(id) : branch\n}\n", "/**\n * Names of the error classes thrown when an interactive prompt ends without a\n * value. From `@inquirer/core`: `ExitPromptError` (Ctrl-C \u2014 and ONLY Ctrl-C:\n * inquirer binds no escape key, so it raises this from readline's SIGINT) and\n * `AbortPromptError` (the prompt was aborted via an `AbortSignal`, which is how\n * Esc arrives \u2014 see lib/prompts/escapable-context). From our own Ink pickers:\n * `PromptCancelledError` (see ./prompt-cancelled-error), which is registered here\n * rather than impersonating an inquirer class name. All are intentional\n * 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 interactive\n * prompt \u2014 Ctrl-C anywhere, or Esc, which reaches an `@inquirer` prompt as an\n * abort and an Ink picker as a `PromptCancelledError`. Matched by `name` rather\n * 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", "/**\n * Assembles the impure {@link PresetProxyContext} `validatePresetProxy` needs, so the STATIC\n * proxy-locality rule in `presets.ts` never has to touch the filesystem or `loadDev` itself.\n *\n * Shared by two callers that must never disagree about what \"satisfiable\" means:\n * - `infra-kit audit` (`commands/audit/preset-proxy-check.ts`) \u2014 checks every preset.\n * - `infra-kit dev <preset>` (`dev-server.ts`) \u2014 checks only the one preset about to run, BEFORE\n * any server spawns.\n */\nimport { loadDev } from '@slip-stream-kit/config/internal'\nimport path from 'node:path'\n\nimport { resolvePreset } from 'src/dev/presets'\nimport type { DiscoveredParts, PresetProxyContext } from 'src/dev/presets'\nimport type { DevPresets } from 'src/lib/infra-kit-config'\n\n/** A frontend config that a preset references but that failed to load (bad/invalid config). */\nexport interface LoadError {\n app: string\n message: string\n}\n\ninterface RoutePkgLookup {\n routePkg: PresetProxyContext['routePkg']\n loadErrors: LoadError[]\n}\n\n/**\n * The set of frontend app folders any preset's proxy override actually references \u2014\n * the only configs the caller needs to load. Scoping to these keeps an unrelated\n * broken frontend config from failing (or crashing) a check it was never relevant to.\n */\nconst collectReferencedApps = (presets: DevPresets, discovered: DiscoveredParts): string[] => {\n const apps = new Set<string>()\n\n for (const preset of Object.values(presets)) {\n for (const app of Object.keys(resolvePreset(preset, discovered).proxy)) {\n apps.add(app)\n }\n }\n\n return [...apps]\n}\n\n/**\n * Load each referenced frontend's `dev.proxy.routes` into a sync `(app, route) \u2192 pkg`\n * lookup. A config that throws (schema-invalid, import error) is captured as a\n * {@link LoadError} instead of rejecting, so one bad config yields an actionable\n * result rather than crashing the whole check.\n */\nconst buildRoutePkgLookup = async (root: string, apps: string[]): Promise<RoutePkgLookup> => {\n const routesByApp: Record<string, Record<string, string>> = {}\n const loadErrors: LoadError[] = []\n\n await Promise.all(\n apps.map(async (app) => {\n try {\n const dev = await loadDev(path.join(root, 'apps', app, 'ui'))\n const routes = dev?.proxy?.routes\n\n if (!routes) return\n\n routesByApp[app] = Object.fromEntries(\n Object.entries(routes).map(([route, route_]) => {\n return [route, route_.packageName]\n }),\n )\n } catch (error) {\n loadErrors.push({ app, message: error instanceof Error ? error.message : String(error) })\n }\n }),\n )\n\n return {\n routePkg: (app, route) => {\n return routesByApp[app]?.[route]\n },\n loadErrors,\n }\n}\n\n/** Result of {@link buildPresetProxyContext}: the assembled context, plus any config that failed to load. */\nexport interface PresetProxyContextResult {\n ctx: PresetProxyContext\n loadErrors: LoadError[]\n}\n\n/**\n * Build the {@link PresetProxyContext} `validatePresetProxy` needs for `presets`: a sync\n * `(app, route) \u2192 pkg` lookup from each referenced frontend's `infra-kit.config.ts`\n * (the SAME file, through the same `loadDev`, that the vite helper resolves at runtime), plus\n * the api package name for every discovered api app.\n *\n * @example\n * const { ctx, loadErrors } = await buildPresetProxyContext('/repo', presets, discovered, apiApps)\n * const issues = validatePresetProxy(presets, ctx)\n */\nexport const buildPresetProxyContext = async (\n root: string,\n presets: DevPresets,\n discovered: DiscoveredParts,\n apiApps: { name: string; packageName: string }[],\n): Promise<PresetProxyContextResult> => {\n const { routePkg, loadErrors } = await buildRoutePkgLookup(root, collectReferencedApps(presets, discovered))\n\n return {\n ctx: {\n discovered,\n apiPkgByApp: Object.fromEntries(\n apiApps.map((a) => {\n return [a.name, a.packageName]\n }),\n ),\n routePkg,\n },\n loadErrors,\n }\n}\n", "/**\n * Thin, injectable driver for the `portless` daemon (Layer B \u2014 see `.omc/plans/dev-https-portless.md`).\n *\n * `infra-kit dev` uses it to register `<release>.<package>.localhost \u2192 127.0.0.1:<port>` routes so the\n * hero URLs resolve over **HTTPS on :443, with no port in the URL**. Every call here is **time-bounded and\n * never throws**: a missing binary, a non-zero exit, or a wedged process resolves to `false`/no-op. That is\n * a reporting contract, not a tolerance one \u2014 portless IS a hard dependency of the dev loop, and\n * `DevServerRunner.ensureProxy` turns a `false` from this driver into a fatal, actionable start error.\n *\n * The binary is NOT resolved from `PATH`: `portless` is a normal npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only when the process was launched via pnpm/npm. Since\n * `infra-kit dev` is often launched otherwise (a global bin, a cmux runner, a foreign cwd), we resolve\n * portless's own `dist/cli.js` by walking `node_modules` from this file (see {@link resolvePortlessBin})\n * and run it with the current `node` (`process.execPath`) \u2014 so it works regardless of how `dev` was\n * invoked. Args are fixed literals plus discovered release/package names + a numeric port, never\n * shell-interpolated.\n *\n * **The daemon is PROBED, never started.** `:443` is privileged, and portless binds it by re-execing\n * itself through `sudo` with an inherited stdio \u2014 which a detached `stdio:'ignore'` child can never\n * satisfy: the password prompt has nowhere to go. Setup is one-time and out-of-band: a root\n * `portless service install`, printed for the user by {@link formatPortlessCommand} (never as a bare\n * `portless`, which no shell can resolve \u2014 see there).\n *\n * All process I/O is injected (`run` for awaited commands, `isProxyServing` for the wire probe) so tests\n * never shell out and can assert the exact portless argv.\n */\nimport type { Buffer } from 'node:buffer'\nimport { execFile } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport http from 'node:http'\nimport https from 'node:https'\nimport net from 'node:net'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport tls from 'node:tls'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\n\nimport { withoutPackageManagerEnv } from 'src/lib/pm-env'\n\nconst execFileAsync = promisify(execFile)\n\n/** Read `bin.portless` (the `dist/cli.js` relative path) from a portless `package.json` on disk. */\nconst readBinRel = (pkgJsonPath: string): string | null => {\n const pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) as { bin?: string | Record<string, string> }\n const rel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.portless\n\n return rel == null || rel === '' ? null : rel\n}\n\n/**\n * Resolve the absolute path to portless's CLI entry (`portless/dist/cli.js`) from node_modules,\n * independent of `PATH`. Returns `null` when portless is not installed, degrading the whole driver to\n * a no-op.\n *\n * portless is ESM-only (its `.` export exposes only `import`/`types`, no `require`), so\n * `createRequire().resolve` can't see it. We instead walk `node_modules` upward from this file \u2014 the\n * standard resolution path \u2014 and read the package's `package.json` straight off disk, which bypasses the\n * exports map that would otherwise hide both `package.json` and the main entry.\n */\nexport const resolvePortlessBin = (): string | null => {\n try {\n let dir = dirname(fileURLToPath(import.meta.url))\n\n for (;;) {\n const pkgJsonPath = join(dir, 'node_modules', 'portless', 'package.json')\n\n if (existsSync(pkgJsonPath)) {\n const rel = readBinRel(pkgJsonPath)\n\n return rel == null ? null : join(dirname(pkgJsonPath), rel)\n }\n const parent = dirname(dir)\n\n if (parent === dir) return null\n dir = parent\n }\n } catch {\n return null\n }\n}\n\n/** Resolve portless's CLI once per process \u2014 the on-disk location never changes within a run. */\nlet cachedBin: string | null | undefined\nconst portlessBin = (): string | null => {\n if (cachedBin === undefined) cachedBin = resolvePortlessBin()\n\n return cachedBin\n}\n\n/**\n * Characters that survive a POSIX shell unquoted. Anything outside this set (a space, a paren \u2014 both of\n * which appear in real install paths like `/Applications/My Editor.app`) gets single-quoted.\n */\nconst SHELL_SAFE = /^[\\w@%+=:,./-]+$/\n\n/** A literal `'` inside single quotes: close, emit an escaped quote, reopen \u2014 the only way a shell allows it. */\nconst SINGLE_QUOTE_ESCAPE = \"'\\\\''\"\n\n/** Single-quote `value` for a POSIX shell unless it is already inert. */\nconst shellQuote = (value: string): string => {\n return SHELL_SAFE.test(value) ? value : `'${value.replaceAll(\"'\", SINGLE_QUOTE_ESCAPE)}'`\n}\n\n/** Seams for {@link formatPortlessCommand}, injected so tests never depend on the real node_modules layout. */\nexport interface FormatPortlessCommandOptions {\n /**\n * Absolute path to portless's `dist/cli.js`. **Required and non-nullable on purpose.** The caller must\n * have resolved portless before it can describe how to run it, so \"I could not find the binary\" cannot be\n * silently rendered as a plausible-looking command \u2014 the type makes that unwritable rather than merely\n * discouraged. A `null` bin is a different report (\"run `pnpm install`\"), which every caller makes first.\n */\n bin: string\n /** Prefix with `sudo` \u2014 only `service install`, which binds the privileged `:443`, needs it. */\n sudo?: boolean\n execPath?: string\n}\n\n/**\n * Render a portless command the user can actually paste into a shell.\n *\n * This exists because the obvious string is a lie. `portless` is a plain npm dependency living in\n * `node_modules/.bin`, which is on `PATH` only inside a pnpm/npm script \u2014 so printing `sudo portless service\n * install` hands the user a command that dies with `sudo: portless: command not found`. `sudo` makes it\n * strictly worse: it replaces `PATH` with `secure_path`, so even a shell that *could* resolve `portless`\n * loses it the moment the command is elevated.\n *\n * We therefore print what the driver itself runs (see {@link defaultRun}): the current interpreter, by\n * absolute path, invoking portless's `dist/cli.js`, by absolute path. Nothing is resolved from `PATH`, so the\n * command works under `sudo`, from any cwd, and however `infra-kit` was launched.\n *\n * This is not merely cosmetic. portless's `service install` writes **the interpreter and script path it was\n * invoked with** straight into the launchd plist's `ProgramArguments` (`nodePath: process.execPath` plus\n * `process.argv[1]`), so the command printed here is the command that gets installed as a **root system\n * daemon**. Printing a name for the shell to resolve would not just fail \u2014 it would decide what runs as root.\n *\n * @example\n * formatPortlessCommand(['service', 'install'], { sudo: true, bin })\n * // 'sudo /usr/local/bin/node /repo/node_modules/portless/dist/cli.js service install'\n */\nexport const formatPortlessCommand = (args: string[], options: FormatPortlessCommandOptions): string => {\n const words = [options.execPath ?? process.execPath, options.bin, ...args]\n const prefix = options.sudo === true ? 'sudo ' : ''\n\n return prefix + words.map(shellQuote).join(' ')\n}\n\n/** Awaited portless invocation. Rejects on non-zero exit / timeout; the driver swallows that into a no-op. */\nexport type PortlessRun = (args: string[], opts: { timeoutMs: number }) => Promise<void>\n\n/** Cheap \"is anything at all accepting TCP here?\" pre-filter in front of the wire probe. */\nexport type IsListening = (port: number) => Promise<boolean>\n\n/**\n * Ground-truth identity: is the process serving `port` actually **portless**, and (when `tls`) is it\n * serving **TLS**? See {@link defaultIsProxyServing} for why this cannot be answered from state files.\n */\nexport type IsProxyServing = (port: number, tls: boolean) => Promise<boolean>\n\nconst DEFAULT_TIMEOUT_MS = 1500\nconst PROBE_TIMEOUT_MS = 1500\n\n/** Response header portless sets on every response it serves. Node lower-cases response header names. */\nconst PORTLESS_HEADER = 'x-portless'\n\n/** IPv4 loopback: portless binds and dials `127.0.0.1`. */\nconst LOOPBACK = '127.0.0.1'\n\n/**\n * SNI for the probe. Node sends **no SNI to an IP literal** (RFC 6066), which would drop portless onto its\n * default certificate \u2014 whose SANs are `localhost`, `*.localhost`, `*.local` and contain **no IP entry**.\n * `localhost` is always in that set, so it is the one name guaranteed to work even on a machine with zero\n * aliases registered.\n */\nconst PROBE_SERVERNAME = 'localhost'\n\n/**\n * Whether portless's OS-level service (the thing `service install` registers) is present on disk.\n * `'unknown'` on a platform this check does not cover (currently anything but macOS/Linux) \u2014 a caller must\n * never read `'unknown'` as `'no'`, since doing so would tell an already-provisioned Windows machine to\n * reinstall.\n */\nexport type ServiceInstalled = 'yes' | 'no' | 'unknown'\n\n/**\n * portless's launchd service label (`sh.portless.proxy`, hard-coded in portless's own CLI) and the two\n * fixed paths its `service install`/`uninstall` write to on macOS and Linux. These are read-only constants\n * of portless's OWN implementation, not ours \u2014 see `dist/cli.js`'s `SERVICE_LABEL`/`buildServiceSpec`. There\n * is no per-user or per-project variant: `service install` always targets exactly one of these two paths.\n * Exported so a test can assert against the exact path this check reads, without hard-coding a second copy.\n */\nexport const DARWIN_SERVICE_PLIST_PATH = '/Library/LaunchDaemons/sh.portless.proxy.plist'\nexport const LINUX_SERVICE_UNIT_PATH = '/etc/systemd/system/portless.service'\n\n/** The `existsSync` seam {@link defaultIsServiceInstalled} takes, injected so tests never touch real root paths. */\nexport type ExistsCheck = (path: string) => boolean\n\n/**\n * Cheap, synchronous, never-throwing check for whether portless's OS service is registered \u2014 a plain\n * `existsSync` on the fixed path `service install` writes to, never a `launchctl`/`systemctl` shell-out. This\n * is what lets {@link createPortlessDriver}'s daemon-down classification tell \"never installed\" apart from\n * \"installed, but not currently answering\" without adding a second process spawn to every failed probe.\n *\n * Deliberately does not attempt Windows detection (a Task Scheduler task, which needs `schtasks` to query) \u2014\n * `'unknown'` there is honest; a guessed `'no'` would send an already-provisioned machine back through\n * `service install` for no reason.\n *\n * `exists` defaults to the real `existsSync` but is a normal parameter (not a named-import spy target) so a\n * test can assert both branches without touching `/Library/LaunchDaemons` \u2014 a root-owned path a dev machine\n * may genuinely have populated, which would make an un-injected assertion true or false depending on the\n * author's own machine state rather than the code under test.\n */\nexport const defaultIsServiceInstalled = (exists: ExistsCheck = existsSync): ServiceInstalled => {\n try {\n if (process.platform === 'darwin') return exists(DARWIN_SERVICE_PLIST_PATH) ? 'yes' : 'no'\n if (process.platform === 'linux') return exists(LINUX_SERVICE_UNIT_PATH) ? 'yes' : 'no'\n\n return 'unknown'\n } catch {\n return 'unknown'\n }\n}\n\n/**\n * Fine-grained outcome of probing the proxy port, distinguishing the two ways \"not serving\" happens so\n * {@link createPortlessDriver}'s caller can print a distinct, actionable fix for each:\n * - `'serving'` \u2014 portless answered on the wire (the old boolean `true`).\n * - `'daemon-down'` \u2014 nothing is even accepting TCP on the port (refused). Combined with\n * {@link ServiceInstalled} this splits into \"never installed\" vs \"installed but crashed/stopped\".\n * - `'not-portless'` \u2014 something IS listening, but it did not answer with `X-Portless: 1` \u2014 a squatter has\n * the port, and installing/trusting portless will not free it.\n */\nexport type ProxyProbeOutcome = 'serving' | 'daemon-down' | 'not-portless'\n\nexport const defaultIsListening: IsListening = (port) => {\n return new Promise((resolve) => {\n const socket = net.connect({ host: LOOPBACK, port })\n const finish = (result: boolean): void => {\n socket.destroy()\n resolve(result)\n }\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('connect', () => {\n finish(true)\n })\n socket.once('timeout', () => {\n finish(false)\n })\n socket.once('error', () => {\n finish(false)\n })\n })\n}\n\n/**\n * Is the listener on `port` portless itself, serving `tls`? Proven **on the wire**, by asking it: portless\n * sets `X-Portless: 1` on every response, before route lookup \u2014 so an unrouted host still answers the probe\n * (a 404 with the header is a pass). This mirrors portless's own `isProxyRunning`.\n *\n * This replaces the old state-file check (`proxy.port` + `proxy.pid`), which was **unsound**: portless's\n * `resolveStateDir(_port)` ignores its port argument, so `proxy.port` / `proxy.pid` / `proxy.tls` are\n * process-global singletons shared by every daemon on every port. Starting ANY daemon rewrites them, and\n * stopping ANY daemon DELETES them \u2014 so a second, unrelated daemon (or a stale sibling repo still on the\n * old CLI, falling back to an unprivileged port) makes a perfectly healthy `:443` daemon look dead. Both\n * were reproduced against portless 0.15.1; see `.omc/research/portless-https-spike.md`.\n *\n * `rejectUnauthorized: false` is deliberate and load-bearing: this probe answers *\"is portless serving\n * here?\"*, **never** *\"is its CA trusted?\"*. Validating the chain here would collapse two different\n * failures \u2014 a daemon that is down, and a CA that was never trusted \u2014 into one indistinguishable error,\n * with two different fixes (a root `service install` vs the sudo-free `trust`). Trust is a separate,\n * explicitly-validating probe (doctor's CA check).\n */\nexport const defaultIsProxyServing: IsProxyServing = (port, tls) => {\n return new Promise((resolve) => {\n const request = tls ? https.request : http.request\n const req = request(\n {\n host: LOOPBACK,\n port,\n method: 'HEAD',\n path: '/',\n timeout: PROBE_TIMEOUT_MS,\n ...(tls ? { rejectUnauthorized: false, servername: PROBE_SERVERNAME } : {}),\n },\n (res) => {\n res.resume()\n resolve(res.headers[PORTLESS_HEADER] === '1')\n },\n )\n\n req.on('error', () => {\n resolve(false)\n })\n req.on('timeout', () => {\n req.destroy()\n resolve(false)\n })\n req.end()\n })\n}\n\nconst defaultRun: PortlessRun = async (args, { timeoutMs }) => {\n const bin = portlessBin()\n\n if (bin == null) throw new Error('portless is not installed (not resolvable from node_modules)')\n await execFileAsync(process.execPath, [bin, ...args], {\n signal: AbortSignal.timeout(timeoutMs),\n encoding: 'utf-8',\n env: withoutPackageManagerEnv(process.env),\n })\n}\n\n/**\n * portless's state directory. Exported so `doctor` reports on the same directory the driver reads.\n *\n * The default is deliberately **unchanged** (`~/.portless`): portless's `service install` bakes\n * `PORTLESS_STATE_DIR`, resolved from `SUDO_USER`, into the launchd plist \u2014 so the root daemon reads the\n * *invoking user's* home. Pointing this anywhere else by default would manufacture the very split it looks\n * like it prevents.\n */\nexport const portlessStateDir = (): string => {\n return process.env.PORTLESS_STATE_DIR ?? join(homedir(), '.portless')\n}\n\n/** portless's local CA certificate \u2014 the root every host cert it mints is signed by. */\nconst CA_CERT_FILE = 'ca.pem'\n\n/**\n * Marker portless's `trust` writes: the **hex sha256 of `ca.pem`'s bytes** that was added to the login\n * keychain (`writeTrustMarker` \u2192 `caFingerprint`, `cli.js:78-101`). It records WHICH CA was trusted, so a\n * regenerated CA leaves a marker that no longer matches.\n */\nconst CA_TRUST_MARKER_FILE = 'ca.trusted'\n\n/** A route portless is serving: `<name> \u2192 127.0.0.1:<port>`. */\nexport interface PortlessRoute {\n /**\n * The registered hostname (e.g. `2-4.client-api.localhost`). Usable verbatim as a\n * `portless alias --remove <name>` argument \u2014 portless strips a trailing TLD off the name it is handed\n * (`parseHostnames`, `chunk-SD2PIWJU.js:68-79`) \u2014 and as a TLS `servername`.\n */\n name: string\n port: number\n}\n\n/** Absolute path to portless's local CA certificate, in whichever state dir {@link portlessStateDir} names. */\nexport const readCaPath = (): string => {\n return join(portlessStateDir(), CA_CERT_FILE)\n}\n\n/**\n * Was `portless trust` run for the CA that is on disk right now? Compares `sha256(ca.pem)` against the\n * fingerprint recorded in `ca.trusted`. `false` when either file is missing; never throws.\n *\n * **This proves the marker was written for THIS fingerprint \u2014 not that the keychain still trusts it.** A\n * user who deletes the certificate from Keychain Access by hand leaves the marker behind and gets a false\n * pass here. That residual is accepted (reading the keychain would mean shelling out to `security` on a\n * check that must stay cheap); it is why this is a *separate* check from the chain handshake\n * ({@link handshakeChainsToCa}), which proves what the daemon actually serves.\n */\nexport const caFingerprintMatches = (): boolean => {\n try {\n const recorded = readFileSync(join(portlessStateDir(), CA_TRUST_MARKER_FILE), 'utf-8').trim()\n\n if (recorded === '') return false\n\n const actual = createHash('sha256').update(readFileSync(readCaPath())).digest('hex')\n\n return actual === recorded.toLowerCase()\n } catch {\n return false\n }\n}\n\n/** Outcome of {@link handshakeChainsToCa}: `code` is the Node TLS error code, which the caller discriminates on. */\nexport type HandshakeResult = { ok: true } | { ok: false; code: string }\n\n/**\n * Does the certificate served on `port` chain to the CA in `ca.pem`? A **validating** TLS handshake \u2014 the\n * complement of {@link defaultIsProxyServing}, which deliberately does not validate.\n *\n * `servername` is **mandatory and load-bearing**, never optional: Node sends no SNI to an IP literal\n * (RFC 6066), which drops portless onto its default certificate, whose SANs (`localhost`, `*.localhost`,\n * `*.local`) contain **no IP entry** \u2014 so a validating probe of `127.0.0.1` with no `servername` fails with\n * `ERR_TLS_CERT_ALTNAME_INVALID` against a perfectly healthy daemon. Any such code coming back from here is\n * therefore a bug in the CALLER's probe, never a finding about the user's trust store. Passing an\n * unregistered name is safe: portless's SNI callback mints a cert on demand for any servername.\n *\n * Time-bounded; never throws.\n */\nexport const handshakeChainsToCa = (port: number, servername: string): Promise<HandshakeResult> => {\n return new Promise((resolve) => {\n let ca: Buffer<ArrayBufferLike>\n\n try {\n ca = readFileSync(readCaPath())\n } catch {\n resolve({ ok: false, code: 'ENOENT' })\n\n return\n }\n\n const socket = tls.connect({ host: LOOPBACK, port, servername, ca: [ca], rejectUnauthorized: true }, () => {\n // With `rejectUnauthorized: true` a chain failure normally surfaces as an 'error' event and this\n // callback never runs; the check is here so a future Node that connects-then-reports can't slip a\n // rejected chain through as a pass.\n const authError = socket.authorizationError as NodeJS.ErrnoException | undefined\n const authorized = socket.authorized\n\n socket.destroy()\n resolve(authorized ? { ok: true } : { ok: false, code: authError?.code ?? authError?.message ?? 'UNKNOWN' })\n })\n\n socket.setTimeout(PROBE_TIMEOUT_MS)\n socket.once('timeout', () => {\n socket.destroy()\n resolve({ ok: false, code: 'ETIMEDOUT' })\n })\n socket.once('error', (err: NodeJS.ErrnoException) => {\n socket.destroy()\n resolve({ ok: false, code: err.code ?? 'UNKNOWN' })\n })\n })\n}\n\n/**\n * Routes portless currently has registered, read from `routes.json` in {@link portlessStateDir}. `[]` on any\n * failure (absent file, malformed JSON, unexpected shape) \u2014 an unreadable route list is reported as \"no\n * routes\", never as an error, because every caller uses this for diagnostics only.\n */\nexport const listRoutes = (): PortlessRoute[] => {\n try {\n const raw: unknown = JSON.parse(readFileSync(join(portlessStateDir(), 'routes.json'), 'utf-8'))\n\n if (!Array.isArray(raw)) return []\n\n return raw.flatMap((entry): PortlessRoute[] => {\n const { hostname, port } = (entry ?? {}) as { hostname?: unknown; port?: unknown }\n\n if (typeof hostname !== 'string' || hostname === '' || typeof port !== 'number') return []\n\n return [{ name: hostname, port }]\n })\n } catch {\n return []\n }\n}\n\nexport interface PortlessDriver {\n /**\n * Absolute path to the `dist/cli.js` this driver executes, or `null` when portless is not installed.\n *\n * Exposed so a caller rendering a remediation ({@link formatPortlessCommand}) names the binary THIS driver\n * would run, rather than re-resolving one behind its back \u2014 which, under an injected driver, would print a\n * fix derived from the real machine instead of the one under test.\n */\n binPath: () => string | null\n /** Resolve (and memoize) whether the `portless` binary is usable. Absent \u2192 every other call no-ops. */\n isAvailable: () => Promise<boolean>\n /**\n * Is a portless daemon serving `port` over `tls`? **Probe only \u2014 this never starts anything.** Binding\n * the privileged `:443` needs root, and portless's sudo re-exec cannot prompt from a detached child, so\n * the daemon is installed once, out-of-band (a root `service install`). A `false` here is turned into a\n * fatal, actionable start error by the caller.\n */\n isProxyServing: (port: number, tls: boolean) => Promise<boolean>\n /**\n * Same probe as {@link PortlessDriver.isProxyServing}, but reporting WHICH way it failed instead of\n * collapsing every non-serving case into `false`. `ensureProxy` uses this to print a distinct, actionable\n * message for \"nothing there\", \"something else is there\", and (combined with {@link isServiceInstalled})\n * \"installed but not running\" vs \"never installed\". Never starts anything \u2014 probe only, same as above.\n */\n probeProxy: (port: number, tls: boolean) => Promise<ProxyProbeOutcome>\n /**\n * Is portless's OS-level service (what `service install` registers) present on disk? Cheap, synchronous,\n * never throws. `'unknown'` on a platform this cannot check \u2014 a caller must not read that as `'no'`.\n */\n isServiceInstalled: () => ServiceInstalled\n /**\n * Register `<name> \u2192 127.0.0.1:<port>` (`name` = `<release>.<package>`). Returns `true` on success so\n * the caller shows the hero URL only for an alias that actually resolves (best-effort otherwise).\n */\n registerAlias: (name: string, port: number) => Promise<boolean>\n /** Deregister `<name>`. Best-effort. */\n removeAlias: (name: string) => Promise<void>\n}\n\nexport interface PortlessDriverDeps {\n /** Override the resolved `dist/cli.js` path (default: the real node_modules walk). Injected in tests. */\n bin?: string | null\n run?: PortlessRun\n /** TCP liveness pre-filter (default: real `net` connect). Injected in tests. */\n isListening?: IsListening\n /** Wire-probe identity check (default: real `HEAD /` + `X-Portless`). Injected in tests. */\n isProxyServing?: IsProxyServing\n /** OS-service-on-disk check (default: real `existsSync` on the plist/unit path). Injected in tests. */\n isServiceInstalled?: () => ServiceInstalled\n timeoutMs?: number\n}\n\n/**\n * Build a {@link PortlessDriver}. Inject `run` in tests to assert argv without shelling out.\n * `isAvailable` memoizes so the binary is probed at most once per runner.\n */\nexport const createPortlessDriver = (deps: PortlessDriverDeps = {}): PortlessDriver => {\n const bin = deps.bin === undefined ? portlessBin() : deps.bin\n const run = deps.run ?? defaultRun\n const isListening = deps.isListening ?? defaultIsListening\n const isProxyServing = deps.isProxyServing ?? defaultIsProxyServing\n const isServiceInstalled = deps.isServiceInstalled ?? defaultIsServiceInstalled\n const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let availability: boolean | null = null\n\n /** Run a portless subcommand, swallowing any failure into `false` (best-effort contract). */\n const tryRun = async (args: string[]): Promise<boolean> => {\n try {\n await run(args, { timeoutMs })\n\n return true\n } catch {\n return false\n }\n }\n\n const isAvailable = async (): Promise<boolean> => {\n availability ??= await tryRun(['--version'])\n\n return availability\n }\n\n const serving = async (port: number, tls: boolean): Promise<boolean> => {\n if (!(await isAvailable())) return false\n // Nothing is even accepting TCP \u2192 skip the (more expensive) wire probe entirely.\n if (!(await isListening(port))) return false\n\n return isProxyServing(port, tls)\n }\n\n /**\n * The classifying counterpart of {@link serving}. Deliberately does NOT gate on `isAvailable()` first (unlike\n * `serving`): a broken/missing CLI binary says nothing about whether a daemon a PRIOR install started is\n * still up on the wire, so the two are independent facts and the caller (which already checked availability\n * before ever calling this) must not have that distinction collapsed here.\n */\n const probeProxy = async (port: number, tls: boolean): Promise<ProxyProbeOutcome> => {\n if (!(await isListening(port))) return 'daemon-down'\n\n return (await isProxyServing(port, tls)) ? 'serving' : 'not-portless'\n }\n\n const registerAlias = async (name: string, port: number): Promise<boolean> => {\n if (!(await isAvailable())) return false\n\n return tryRun(['alias', name, String(port)])\n }\n\n const removeAlias = async (name: string): Promise<void> => {\n if (!(await isAvailable())) return\n await tryRun(['alias', '--remove', name])\n }\n\n return {\n binPath: () => {\n return bin\n },\n isAvailable,\n isProxyServing: serving,\n probeProxy,\n isServiceInstalled,\n registerAlias,\n removeAlias,\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
5
|
+
"mappings": "mHAAA,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,EAAI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AAS,IACA1B,EAET,YAAA4B,EACA,eApCc,MAAO1C,EAAcO,IAC/B,CAAE,MAAMmC,EAAY,GAEpB,CAAE,MAAML,EAAYrC,CAAI,EAAW,GAEhCsC,EAAetC,EAAMO,CAAG,EAgC/B,WAvBiB,MAAOP,EAAcO,IAChC,MAAM8B,EAAYrC,CAAI,EAEpB,MAAMsC,EAAetC,EAAMO,CAAG,EAAK,UAAY,eAFhB,cAuBvC,mBAAAgC,EACA,cAnBoB,MAAOI,EAAc3C,IACnC,MAAM0C,EAAY,EAEjBD,EAAO,CAAC,QAASE,EAAM,OAAO3C,CAAI,CAAC,CAAC,EAFR,GAmBnC,YAdkB,MAAO2C,GAAgC,CACnD,MAAMD,EAAY,GACxB,MAAMD,EAAO,CAAC,QAAS,WAAYE,CAAI,CAAC,CAC1C,CAYA,CACF",
|
|
6
6
|
"names": ["process", "$", "isCmuxAvailable", "$", "openCmuxDevWorkspace", "args", "cwd", "title", "layout", "layoutJson", "output", "process", "parseWorkspaceRef", "closeCmuxDevWorkspace", "ref", "error", "logger", "match", "$", "realpath", "$", "safeRealpath", "path", "realpath", "listCmuxWorkspacesByCwd", "workspacesOutput", "groupsOutput", "$", "workspaces", "groups", "anchorRefs", "group", "ref", "byCwd", "workspace", "error", "logger", "closeCmuxWorkspaceByCwd", "cwd", "ref", "listCmuxWorkspacesByCwd", "safeRealpath", "$", "error", "logger", "$", "findCmuxGroupRefByName", "name", "output", "$", "group", "error", "logger", "createCmuxGroupFrom", "fromRefs", "ref", "$", "openCmuxWorkspaceWithLayout", "args", "cwd", "title", "group", "layout", "resolveCmuxLayout", "getInfraKitConfig", "newWorkspaceOutput", "$", "workspaceRef", "parseWorkspaceRef", "surfacesOutput", "leftTopRef", "parseFirstSurfaceRef", "output", "match", "buildCmuxWorkspaceTitle", "args", "branch", "id", "parseBranchName", "displayLabel", "CANCELLATION_ERROR_NAMES", "hasCancellationName", "value", "isPromptCancellation", "error", "cause", "loadDev", "path", "collectReferencedApps", "presets", "discovered", "apps", "preset", "app", "resolvePreset", "buildRoutePkgLookup", "root", "routesByApp", "loadErrors", "routes", "loadDev", "path", "route", "route_", "error", "buildPresetProxyContext", "apiApps", "routePkg", "a", "execFile", "createHash", "existsSync", "readFileSync", "http", "https", "net", "homedir", "dirname", "join", "process", "tls", "fileURLToPath", "promisify", "execFileAsync", "promisify", "execFile", "readBinRel", "pkgJsonPath", "pkg", "readFileSync", "rel", "resolvePortlessBin", "dir", "dirname", "fileURLToPath", "join", "existsSync", "parent", "cachedBin", "portlessBin", "SHELL_SAFE", "SINGLE_QUOTE_ESCAPE", "shellQuote", "value", "formatPortlessCommand", "args", "options", "words", "process", "DEFAULT_TIMEOUT_MS", "PROBE_TIMEOUT_MS", "PORTLESS_HEADER", "LOOPBACK", "PROBE_SERVERNAME", "DARWIN_SERVICE_PLIST_PATH", "LINUX_SERVICE_UNIT_PATH", "defaultIsServiceInstalled", "exists", "defaultIsListening", "port", "resolve", "socket", "net", "finish", "result", "defaultIsProxyServing", "tls", "req", "https", "http", "res", "defaultRun", "timeoutMs", "bin", "withoutPackageManagerEnv", "portlessStateDir", "homedir", "CA_CERT_FILE", "CA_TRUST_MARKER_FILE", "readCaPath", "caFingerprintMatches", "recorded", "createHash", "handshakeChainsToCa", "servername", "ca", "authError", "authorized", "err", "listRoutes", "raw", "entry", "hostname", "createPortlessDriver", "deps", "run", "isListening", "isProxyServing", "isServiceInstalled", "availability", "tryRun", "isAvailable", "name"]
|
|
7
7
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import M from"node:process";import j from"pino";import pe from"pino-pretty";var O="/tmp/mcp-infra-kit.log",F=["token","*.token","serviceToken","*.serviceToken","DOPPLER_TOKEN","*.DOPPLER_TOKEN","INFRA_KIT_ENV_TOKEN","*.INFRA_KIT_ENV_TOKEN"],
|
|
2
|
-
`)){if(o.startsWith("worktree ")){n&&r.push(n),n={path:o.slice(9),branch:null,detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o.startsWith("branch ")?n.branch=o.slice(7).replace(/^refs\/heads\//,""):o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="locked"||o.startsWith("locked ")?n.locked=!0:(o==="prunable"||o.startsWith("prunable "))&&(n.prunable=!0))}return n&&r.push(n),r},Oe=async e=>{let t=await Z(Q.cwd()),r=n=>e==="release"?T(n):n.startsWith("feature/");return t.map(n=>n.branch).filter(n=>n!==null&&r(n))},Me=e=>{let t=E(e);return t&&/not a git repository/i.test(t)?"not a git repository":void 0},Fe=({hasStderr:e})=>{if(
|
|
3
|
-
`);export{E as a,R as b,U as c,
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import M from"node:process";import j from"pino";import pe from"pino-pretty";var O="/tmp/mcp-infra-kit.log",F=["token","*.token","serviceToken","*.serviceToken","DOPPLER_TOKEN","*.DOPPLER_TOKEN","INFRA_KIT_ENV_TOKEN","*.INFRA_KIT_ENV_TOKEN"],Dt=()=>{let e=M.argv.includes("--debug")?"debug":"info",t=j({level:e,redact:F},j.destination({dest:O}));return t.info(`Logger initialized with level: ${e}. Logging to: ${O}`),t},le=()=>{let e=M.argv.includes("--debug")?"debug":"info",t=["time","pid","hostname"];return e==="debug"&&t.push("level"),j({level:e,redact:F},pe({destination:2,ignore:t.join(","),colorize:!0}))},At=le();import*as p from"node:fs";import*as a from"node:path";function ue(e){let t=e;for(let r=0;r<10;r++){let n=a.join(t,"pnpm-workspace.yaml");if(p.existsSync(n))return t;t=a.dirname(t)}throw new Error("Could not find monorepo root (pnpm-workspace.yaml)")}function G(e,t){let r=a.join(e,"package.json");if(!p.existsSync(r))return t;try{let n=JSON.parse(p.readFileSync(r,"utf-8"));return typeof n.name=="string"?n.name:t}catch{return t}}function Tt(e){let t=a.join(e,"apps"),r=[];if(!p.existsSync(t))throw new Error(`Apps directory not found: ${t}`);let n=p.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of n){let i=a.join(t,o,"api"),c=a.join(i,"serverless.yml");p.existsSync(c)&&r.push({name:o,packageName:G(i,o),path:i})}return r}var B=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs"],fe=["@slip-stream-kit/vite","@slip-stream-kit/config/vite","infra-kit/vite"];function de(e){for(let t of B){let r=a.join(e,t);if(p.existsSync(r))try{let n=p.readFileSync(r,"utf-8");return fe.some(o=>n.includes(o))}catch{return!1}}return!1}function Nt(e){for(let t of B){let r=a.join(e,t);if(p.existsSync(r))try{return p.readFileSync(r,"utf-8").includes("infraKit(")}catch{return!1}}return!1}function ge(e){let t=a.join(e,"package.json");if(!p.existsSync(t))return!1;try{let r=JSON.parse(p.readFileSync(t,"utf-8"));return typeof r.scripts?.dev=="string"&&r.scripts.dev.length>0}catch{return!1}}function _t(e){let t=a.join(e,"apps"),r=[];if(!p.existsSync(t))return r;let n=p.readdirSync(t,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);for(let o of n){let i=a.join(t,o,"ui");p.existsSync(i)&&ge(i)&&r.push({name:o,packageName:G(i,o),path:i,managedPort:de(i)})}return r}function Lt(e){let t=e?.filter(Boolean)??[];return t.length>0?t:null}function Kt(e){let t=ue(e),r=a.relative(a.join(t,"apps"),e),n=r.split(a.sep)[0];if(r===""||r.startsWith("..")||a.isAbsolute(r)||!n)throw new Error(`--self: not inside an apps/<app> directory (cwd: ${e}). Run from an app folder or use --app=<name>.`);return n}var me=new Set(["api","ui"]),W=e=>{let t=a.join(e,"dist");return p.existsSync(t)&&p.statSync(t).isDirectory()?t:void 0},I=e=>p.existsSync(e)?p.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name):[];function Ot(e){let t=[];for(let n of I(a.join(e,"packages"))){let o=W(a.join(e,"packages",n));o!==void 0&&t.push(o)}let r=a.join(e,"apps");for(let n of I(r))for(let o of I(a.join(r,n))){if(me.has(o))continue;let i=a.join(r,n,o);if(!p.existsSync(a.join(i,"package.json")))continue;let c=W(i);c!==void 0&&t.push(c)}return t}function Mt(e){return e.map(t=>a.join(t.path,"dist")).filter(t=>p.existsSync(t))}function Ft(e,t,r){let n=a.normalize(e),o=r.find(c=>n.startsWith(a.normalize(c)));return o?{kind:"package",packageDir:o}:{kind:"app",app:t.find(c=>n.startsWith(a.normalize(c)))}}var he={"*/api":{},"*/ui":{}},V=e=>{let t=e.split("/"),[r,n]=t;return t.length!==2||!r?`devServersPresets: invalid target "${e}" (expected "<app>/api" or "<app>/ui")`:n!=="api"&&n!=="ui"?`devServersPresets: invalid target part "${n}" in "${e}" (expected "api" or "ui")`:null},ve=e=>{let t=V(e);if(t)throw new Error(t);let[r,n]=e.split("/");return{appGlob:r,part:n}},Gt=e=>{let t=[];for(let[r,n]of Object.entries(e))for(let o of Object.keys(n.apps??{})){let i=V(o);i&&t.push({preset:r,key:o,message:`preset "${r}": ${i}`})}return t},ye=(e,t)=>t==="api"?e.api:e.ui,ke=e=>[...new Set([...e.api,...e.ui])].sort(),z=(e,t)=>`${e}/${t}`,xe=e=>e?0:1,be=(e,t)=>t.watchDeps===void 0?e??{watchDeps:!0,rank:t.rank,explicitValue:!1}:!e||!e.explicitValue?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:t.rank>e.rank?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:e,we=(e,t,r)=>{let{app:n,part:o,watchDeps:i,isGlob:c}=r;if(!ye(t,o).includes(n)){c||e.unmatched.push(z(n,o));return}let l=z(n,o),u=be(e.targets.get(l),{watchDeps:i,rank:xe(c)});e.targets.set(l,{app:n,part:o,...u})},Pe=(e,t)=>{let r=Object.entries(e.apps??he),n={targets:new Map,proxy:{},unmatched:[]};for(let[c,l]of r){let{appGlob:u,part:g}=ve(c),m=u==="*",P=m?ke(t):[u];for(let C of P)we(n,t,{app:C,part:g,watchDeps:l.watchDeps,isGlob:m}),l.proxy&&(n.proxy[C]={...n.proxy[C]??{},...l.proxy})}let o=[...n.targets.values()].map(({app:c,part:l,watchDeps:u})=>({app:c,part:l,watchDeps:u})),i=[...new Set(o.filter(c=>c.part==="api").map(c=>c.app))];return{targets:o,cmux:e.cmux??!1,proxy:n.proxy,localApps:i,unmatched:n.unmatched}},Bt=e=>{if(e.preset!=null)return e.preset;if(e.running.length===0)return"nothing";let t=new Set(e.running);return e.discovered.every(n=>t.has(n))?"*":[...t].sort().join(" + ")},Re=(e,t)=>Object.keys(e).find(r=>e[r]===t),Ee=({preset:e,app:t,route:r,launchedPkgs:n,ctx:o})=>{let i=o.routePkg(t,r);if(i===void 0)return{preset:e,app:t,route:r,kind:"unknown-route",message:`preset "${e}": proxy override "${r}" on "${t}" names a route not declared in ${t}'s infra-kit.config.ts dev.proxy.routes`};if(n.has(i))return null;let c=Re(o.apiPkgByApp,i),l=c?`add "${c}/api" to the preset`:`launch the api whose package is "${i}"`;return{preset:e,app:t,route:r,pkg:i,kind:"backend-not-launched",message:`preset "${e}": proxy override "${r}" \u2192 "local" requires backend "${i}" to run locally, but the preset does not launch it \u2014 ${l}, or set "${r}" to "cloud"`}},zt=(e,t)=>{let r=[];for(let[n,o]of Object.entries(e)){let i=Pe(o,t.discovered),c=new Set(i.localApps.map(l=>t.apiPkgByApp[l]).filter(l=>l!==void 0));for(let[l,u]of Object.entries(i.proxy))for(let[g,m]of Object.entries(u)){if(m!=="local")continue;let P=Ee({preset:n,app:l,route:g,launchedPkgs:c,ctx:t});P&&r.push(P)}}return r};import L from"node:fs/promises";import ne from"node:os";import b from"node:path";import Ue from"node:process";import{z as s}from"zod";import v from"node:path";import Q from"node:process";import{$ as f}from"zx";var E=e=>{if(e===null||typeof e!="object")return;let t=e.stderr;return typeof t=="string"&&t.length>0?t:void 0},Se=(e,t)=>{let r=t.stderrExcerpt??E(e),n=[`failed to ${t.operation}`];return r&&n.push(`stderr: ${r.slice(0,200).trim()}`),t.remediation&&n.push(`try: ${t.remediation}`),n.join(" \u2014 ")},R=class extends Error{operation;remediation;constructor(t,r){super(Se(t,r),{cause:t}),this.name="OperationError",this.operation=r.operation,this.remediation=r.remediation}};var U={enabled:!1},x=()=>U.enabled;var Ce=/^v?(\d+)\.(\d+)\.(\d+)$/,je=/^(\d+)\.(\d+)\.(\d+)$/,Ie=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,S="release/",D="release/v",X="refs/heads/",De="next";var H=new Set(["dev","main","next","hotfix","regular","release"]),h=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},y=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},J=e=>e.startsWith(X)?e.slice(X.length):e,Y=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),A=e=>{if(e.length===0)throw new h('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new h(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!Ie.test(e))throw new h(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(H.has(e))throw new h(`Release name "${e}" is reserved. Reserved names: ${[...H].join(", ")}.`)},$=e=>{let t=J(e.trim());if(!t.startsWith(S))return null;if(t.startsWith(D)){let n=t.slice(D.length),o=je.exec(n);if(o)return Y(Number(o[1]),Number(o[2]),Number(o[3]))}let r=t.slice(S.length);try{A(r)}catch{return null}return{kind:"name",name:r,raw:r}},Ae=e=>{let t=e.trim();if(J(t).startsWith(S)){let o=$(t);if(!o)throw new y(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return o}let n=Ce.exec(t);if(n)return Y(Number(n[1]),Number(n[2]),Number(n[3]));if(t.toLowerCase()===De)throw new y('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{A(t)}catch(o){let i=o instanceof Error?o.message:String(o);throw new y(`Cannot parse "${e}" as a release ref: ${i}`)}return{kind:"name",name:t,raw:t}},$e=e=>e.kind==="version"?`${D}${e.raw}`:`${S}${e.name}`,Te=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},Ne=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,_e=e=>e.kind==="version"?`v${e.raw}`:e.name,Le=e=>e.raw,T=e=>e==null?!1:$(e)!==null,q=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},Ke=(e,t,r)=>{if(e.kind==="version"&&t.kind==="version")return e.semver.major!==t.semver.major?e.semver.major-t.semver.major:e.semver.minor!==t.semver.minor?e.semver.minor-t.semver.minor:e.semver.patch-t.semver.patch;if(e.kind==="version")return-1;if(t.kind==="version")return 1;let n=q(r?.a),o=q(r?.b);return n!==null&&o!==null&&n!==o?n-o:e.name<t.name?-1:e.name>t.name?1:0};var Z=async e=>{let t=await f({cwd:e})`git worktree list --porcelain`,r=[],n=null;for(let o of t.stdout.split(`
|
|
2
|
+
`)){if(o.startsWith("worktree ")){n&&r.push(n),n={path:o.slice(9),branch:null,detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o.startsWith("branch ")?n.branch=o.slice(7).replace(/^refs\/heads\//,""):o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="locked"||o.startsWith("locked ")?n.locked=!0:(o==="prunable"||o.startsWith("prunable "))&&(n.prunable=!0))}return n&&r.push(n),r},Oe=async e=>{let t=await Z(Q.cwd()),r=n=>e==="release"?T(n):n.startsWith("feature/");return t.map(n=>n.branch).filter(n=>n!==null&&r(n))},Me=e=>{let t=E(e);return t&&/not a git repository/i.test(t)?"not a git repository":void 0},Fe=({hasStderr:e})=>{if(x())return"the infra-kit MCP server resolves its project from the working directory it was launched in; the operator must relaunch the server with its working directory set to an infra-kit project repo";let t="run infra-kit from inside an infra-kit project repo (or one of its git worktrees)";return e?`${t}; if you are already in one, the stderr in this message is the real cause`:t},k=async()=>{try{return(await f({quiet:!0})`git rev-parse --show-toplevel`).stdout.trim()}catch(e){let t=Me(e)??E(e);throw new R(e,{operation:`resolve the project root from ${Q.cwd()}`,stderrExcerpt:t,remediation:Fe({hasStderr:t!==void 0})})}},N=async e=>{let t=e??await k(),r=(await f({cwd:t,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim(),n=v.resolve(t,r);return n.includes(`${v.sep}.git${v.sep}modules${v.sep}`)?t:v.dirname(n)},ee=async()=>(await f`git rev-parse --abbrev-ref HEAD`).stdout.trim(),We=async()=>(await f`git status --porcelain`).stdout.trim().length===0,Ge=async()=>{let e=await k(),[t,r]=await Promise.all([f({cwd:e})`git rev-parse --absolute-git-dir`,f({cwd:e})`git rev-parse --git-common-dir`]),n=t.stdout.trim(),o=v.resolve(e,r.stdout.trim());return n!==o},Be=async()=>{let e=await k();return v.basename(e)},ze=async e=>{(await f`git branch --list ${e}`).stdout.trim().length!==0&&await ee()!==e&&await f`git branch -D ${e}`},Ve=async e=>{(await f`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await f`git push origin --delete ${e}`};var te="infra-kit.json",oe=".infra-kit",Xe="infra-kit.json",He="projects",qe=s.object({provider:s.literal("doppler"),config:s.object({name:s.string().min(1)})}),Je=s.discriminatedUnion("provider",[qe]),Ye=s.object({workspaceConfigPath:s.string().min(1)}),Qe=s.object({provider:s.literal("cursor"),config:Ye}),Ze=s.object({}),et=s.object({provider:s.literal("zed"),config:Ze}),re=s.discriminatedUnion("provider",[Qe,et]),tt=s.union([re,s.array(re).min(1)]),rt=s.object({provider:s.literal("jira"),config:s.object({baseUrl:s.string().url(),projectId:s.number().int().positive()})}),nt=s.discriminatedUnion("provider",[rt]),ot=["two-columns","three-pane"],st=s.object({layout:s.enum(ot).optional()}),it=s.object({openInGithubDesktop:s.boolean().optional(),openInCmux:s.boolean().optional(),cmux:st.optional()}),at=s.object({port:s.number().int().positive().optional(),prefixUrl:s.string().min(1).optional()}).strict(),ct=s.record(s.string().min(1),at),pt=s.enum(["local","cloud"]),lt=s.object({watchDeps:s.boolean().optional(),proxy:s.record(s.string().min(1),pt).optional()}).strict(),ut=s.object({apps:s.record(s.string().min(1),lt).optional(),cmux:s.boolean().optional()}).strict(),ft=s.record(s.string().min(1),ut),dt=s.object({port:s.number().int().positive().optional()}).strict(),gt=s.object({trigger:s.enum(["shell-startup","cli-invocation"]),config:s.string().min(1)}).strict(),K=s.object({envManagement:Je,ide:tt.optional(),taskManager:nt.optional(),worktrees:it.optional(),envAutoLoad:gt.optional(),dev:ct.optional(),devServersPresets:ft.optional(),devProxy:dt.optional()}).strict(),mt=443,se=K.superRefine((e,t)=>{if(!Array.isArray(e.ide))return;let r=new Set;for(let n of e.ide){if(r.has(n.provider)){t.addIssue({code:"custom",message:"each IDE provider may appear at most once",path:["ide"]});return}r.add(n.provider)}}),ie=K.partial(),ht=e=>{let t=e.ide;return t?Array.isArray(t)?t:[t]:[]},vt="two-columns",yt=e=>e.worktrees?.cmux?.layout??vt,d=null,w=null,ae=()=>`${Ue.cwd()} ${ne.homedir()}`,ce=async()=>{let e=ae();if(w&&w.key===e)return w.value;let t=await k(),r=await N(t),n=b.basename(r),o=b.join(ne.homedir(),oe),i={main:b.join(t,te),userGlobal:b.join(o,Xe),userProject:b.join(o,He,n,te),projectName:n};return w={key:e,value:i},i},kt=async()=>{let e=ae(),t=await ce(),r;try{r=await L.stat(t.main)}catch{d=null;let g=t.main.replace(/\.json$/,".yml");throw await _(g)?new Error(`infra-kit.json not found at ${t.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit init\` to convert it.`):new Error(x()?`infra-kit.json not found at ${t.main} \u2014 the directory the infra-kit MCP server was launched in is not an infra-kit project. The operator must relaunch the server with its working directory set to an infra-kit project repo.`:`infra-kit.json not found at ${t.main} \u2014 this git repo is not an infra-kit project. Run \`infra-kit init\` here to create it, cd into an infra-kit project repo, or check out a branch that has infra-kit.json.`)}let[n,o]=await Promise.all([_(t.userGlobal),_(t.userProject)]),i={main:Number(r.mtimeMs),userGlobal:n?Number(n.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(d&&d.key===e&&Pt(d.mtimes,i))return d.value;let c=[{label:"infra-kit.json",path:t.main,required:!0},{label:"~/.infra-kit/infra-kit.json",path:t.userGlobal,required:!1},{label:`~/.infra-kit/projects/${t.projectName}/infra-kit.json`,path:t.userProject,required:!1}],l={};for(let g of c){let m=await Rt(g);m!==null&&(l={...l,...m})}let u=se.safeParse(l);if(!u.success)throw new Error(`Invalid merged infra-kit config: ${s.prettifyError(u.error)}`);return d={key:e,mtimes:i,value:u.data},u.data},xt=()=>{d=null},bt=()=>{d=null,w=null},_=async e=>{try{return await L.stat(e)}catch{return null}},wt=async e=>{try{return await L.readFile(e,"utf-8")}catch{return null}},Pt=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>e[n]===t[n])},Rt=async e=>{let t=await wt(e.path);if(t===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(o){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${o.message}`)}if(Et(r)&&"envTokens"in r)throw new Error(St(e));let n=ie.safeParse(r);if(!n.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${s.prettifyError(n.error)}`);return n.data},Et=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),St=e=>[`Refusing to load ${e.label} \u2014 \`envTokens\` is not a config key.`,"A service token in a config file can be committed, backed up by your editor, or shared."," 1. REVOKE the token in Doppler now \u2014 treat it as compromised.",` 2. Remove the \`envTokens\` key from ${e.path}.`," 3. Re-add it privately: `infra-kit env-token-set <env>`"," (it is written to ~/.infra-kit/projects/<repo>/tokens.json, mode 0600, never to the repo)."].join(`
|
|
3
|
+
`);export{E as a,R as b,U as c,x as d,h as e,A as f,$ as g,Ae as h,$e as i,Te as j,Ne as k,_e as l,Le as m,T as n,Ke as o,Z as p,Oe as q,k as r,N as s,ee as t,We as u,Ge as v,Be as w,ze as x,Ve as y,O as z,Dt as A,At as B,ue as C,Tt as D,Nt as E,_t as F,Lt as G,Kt as H,Ot as I,Mt as J,Ft as K,V as L,Gt as M,Pe as N,Bt as O,zt as P,oe as Q,mt as R,se as S,ie as T,ht as U,yt as V,ce as W,kt as X,xt as Y,bt as Z};
|
|
4
|
+
//# sourceMappingURL=chunk-DWZSB6O6.js.map
|