infra-kit 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-FKA65HOC.js → chunk-3UE375II.js} +2 -2
- package/dist/{chunk-FKA65HOC.js.map → chunk-3UE375II.js.map} +1 -1
- package/dist/chunk-4RZM53X7.js +7 -0
- package/dist/{chunk-EU7LD5IV.js.map → chunk-4RZM53X7.js.map} +3 -3
- package/dist/{chunk-VDBJ73LS.js → chunk-DVXTZPQ5.js} +1 -1
- package/dist/chunk-DVXTZPQ5.js.map +7 -0
- package/dist/{chunk-D76UWTR5.js → chunk-EZ4DIT5A.js} +3 -3
- package/dist/{chunk-D76UWTR5.js.map → chunk-EZ4DIT5A.js.map} +1 -1
- package/dist/chunk-I23MDR4X.js +5 -0
- package/dist/chunk-I23MDR4X.js.map +7 -0
- package/dist/{chunk-CMF7HEVU.js → chunk-IT6XJWTW.js} +2 -2
- package/dist/chunk-IT6XJWTW.js.map +7 -0
- package/dist/{chunk-BQPSXIH2.js → chunk-MH37P7W4.js} +2 -2
- package/dist/chunk-PP3ZZKB3.js +12 -0
- package/dist/chunk-PP3ZZKB3.js.map +7 -0
- package/dist/{chunk-Z4ZY2G4O.js → chunk-ZTAUGYJF.js} +2 -2
- package/dist/cli.js +117 -109
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +21 -21
- package/dist/dev-server.js.map +3 -3
- package/dist/{dev-wizard-run-SHX5YW6J.js → dev-wizard-run-6PLC5YEW.js} +2 -2
- package/dist/env-load-NURS7WNH.js +2 -0
- package/dist/mcp-proxy.js +7 -7
- package/dist/mcp-proxy.js.map +3 -3
- package/dist/{persistent-ink-dev-ui-P65EJCC6.js → persistent-ink-dev-ui-ZSOS3CF4.js} +2 -2
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/readme.md +5 -2
- package/dist/chunk-CMF7HEVU.js.map +0 -7
- package/dist/chunk-EU7LD5IV.js +0 -7
- package/dist/chunk-LR57E6IP.js +0 -10
- package/dist/chunk-LR57E6IP.js.map +0 -7
- package/dist/chunk-QSTGO43H.js +0 -4
- package/dist/chunk-QSTGO43H.js.map +0 -7
- package/dist/chunk-VDBJ73LS.js.map +0 -7
- package/dist/env-load-EYVU4TIM.js +0 -2
- /package/dist/{chunk-BQPSXIH2.js.map → chunk-MH37P7W4.js.map} +0 -0
- /package/dist/{chunk-Z4ZY2G4O.js.map → chunk-ZTAUGYJF.js.map} +0 -0
- /package/dist/{dev-wizard-run-SHX5YW6J.js.map → dev-wizard-run-6PLC5YEW.js.map} +0 -0
- /package/dist/{env-load-EYVU4TIM.js.map → env-load-NURS7WNH.js.map} +0 -0
- /package/dist/{persistent-ink-dev-ui-P65EJCC6.js.map → persistent-ink-dev-ui-ZSOS3CF4.js.map} +0 -0
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import _ from"node:fs";import V from"node:os";import E from"node:path";import p from"node:process";var h="env-load.sh",O="env-clear.sh",S="env-load.root",A="INFRA_KIT_SESSION",f=".infra-kit",d="INFRA_KIT_ENV",v="INFRA_KIT_ENV_CONFIG",x="INFRA_KIT_ENV_PROJECT",K="INFRA_KIT_ENV_PROJECT_ROOT",C="INFRA_KIT_ENV_LOADED_AT",T=/^([A-Z_]\w*)=/i,D=/^unset ([A-Z_]\w*)$/i,a=(t,e)=>{let r=e;for(let n=0;n<t.length;n++){if(!r&&t[n]==="\\"){n++;continue}t[n]==="'"&&(r=!r)}return r},L=t=>{let e=t.startsWith("'")?t.slice(1):t;return(e.endsWith("'")?e.slice(0,-1):e).split("'\\''").join("'")},l=t=>{try{return _.readFileSync(t,"utf-8")}catch{return""}},F=(t,e,r)=>{let n=t.split(`
|
|
2
|
+
`).map(o=>o.endsWith("\r")?o.slice(0,-1):o),s=0,i=!1;for(;s<n.length;){let o=n[s];if(i){i=a(o,i),s+=1;continue}let I=T.exec(o);if(!I){let c=D.exec(o);c&&r?.(c[1]),i=a(o,!1),s+=1;continue}let g=I[1],R=o.slice(I[0].length);if(!R.startsWith("'")){e({name:g,value:R}),i=a(o,!1),s+=1;continue}let u=[R],N=a(R,!1);for(;N&&s+1<n.length;){s+=1;let c=n[s];u.push(c),N=a(c,!0)}e({name:g,value:L(u.join(`
|
|
3
|
+
`))}),i=N,s+=1}},y=t=>{let e=[];return F(l(t),({name:r})=>{e.push(r)}),e},W=t=>{let e={};return F(l(t),({name:r,value:n})=>{e[r]=n}),e},w=t=>{let e=[];return F(l(t),()=>{},r=>{e.push(r)}),e},m=()=>{let t=p.env.XDG_CACHE_HOME,e=t&&t.length>0?t:E.join(V.homedir(),".cache");return E.join(e,"infra-kit")},P=()=>{let t=p.env[A];if(!t)throw new Error(`${A} is not set. Run \`infra-kit setup --skip-tools\` then \`source ~/.zshrc\`.`);return E.join(m(),t)},U=(t,e,r)=>{let n=`${t}.tmp.${p.pid}`;_.writeFileSync(n,e,{mode:r});try{_.renameSync(n,t)}catch(s){throw _.rmSync(n,{force:!0}),s}},b="-worktrees",G=(t,e)=>{let r;try{r=_.readFileSync(t,"utf-8")}catch{return!0}let n=J(e);return r.split(`
|
|
4
|
+
`).filter(Boolean).some(s=>n===s||n.startsWith(`${s}${E.sep}`))},J=t=>{try{return _.realpathSync(t)}catch{return E.resolve(t)}},$={release:"release",feature:"feature",mergeDev:"merge-dev"};export{h as a,O as b,S as c,A as d,f as e,d as f,v as g,x as h,K as i,C as j,y as k,W as l,w as m,m as n,P as o,U as p,b as q,G as r,$ as s};
|
|
5
|
+
//# sourceMappingURL=chunk-I23MDR4X.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/constants/constants.ts"],
|
|
4
|
+
"sourcesContent": ["import 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 * Sidecar of `env-load.sh`: the directories, one per line, the loaded env belongs to. The session is\n * per terminal, not per repo, so without it a shell or agent in repo A sourced repo B's env.\n */\nexport const ENV_LOAD_ROOT_FILE = 'env-load.root'\n\nexport const INFRA_KIT_SESSION_VAR = 'INFRA_KIT_SESSION'\n/**\n * Directory under the user's home that holds all machine-local infra-kit config:\n * the runtime `infra-kit.json` merge layer, per-project overrides, the factory\n * registry (`vendor.json`), and the `portless` package link. Single source of\n * truth for `.infra-kit`.\n *\n * Defined HERE, not in `lib/infra-kit-config`, because that module pulls in zod\n * and the `ik-mcp` proxy bundle must stay Node-builtins-only (guarded in\n * `entry/__tests__/dist-shebang.test.ts`); `lib/infra-kit-config` re-exports it\n * for its existing consumers.\n */\nexport const USER_CONFIG_DIR_NAME = '.infra-kit'\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, so a shell can\n * tell whose secrets it is carrying after a `cd` into another project.\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/**\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 * The `unset NAME` line env-clear.sh is made of. Anchored at both ends so a value that merely\n * starts with the word is not a match.\n */\nconst UNSET_LINE_PATTERN = /^unset ([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\n/** One `KEY=value` assignment recovered from an env file, value already unescaped. */\nexport interface EnvAssignment {\n name: string\n value: string\n}\n\n/**\n * Undo {@link shellSingleQuote}: drop the wrapping quotes, then turn each `'\\''`\n * back into a literal `'`. Order matters \u2014 unescaping first would let an embedded\n * `'\\''` be mistaken for the closing quote.\n */\nconst decodeSingleQuoted = (raw: string): string => {\n const withoutOpen = raw.startsWith(\"'\") ? raw.slice(1) : raw\n const body = withoutOpen.endsWith(\"'\") ? withoutOpen.slice(0, -1) : withoutOpen\n\n return body.split(\"'\\\\''\").join(\"'\")\n}\n\n/** File contents, or '' when the path is absent, a directory, or unreadable. */\nconst readEnvFileContent = (filePath: string): string => {\n try {\n return fs.readFileSync(filePath, 'utf-8')\n } catch {\n return ''\n }\n}\n\n/**\n * Walk every assignment in an env-load.sh body, skipping the continuation lines of\n * multiline values. {@link parseVarNamesFromEnvFile}, {@link parseVarsFromEnvFile}\n * and {@link parseUnsetNamesFromEnvFile} all go through here, so they can never\n * disagree about where a value ends \u2014 an `unset X` inside a quoted value is a\n * continuation line to every one of them.\n */\nconst forEachAssignment = (\n content: string,\n visit: (assignment: EnvAssignment) => void,\n visitUnset?: (name: string) => void,\n): void => {\n // A trailing CR is stripped per line: a CRLF file would otherwise hand back values\n // ending in '\\r' \u2014 a token that looks right in a diff and fails every request.\n const lines = content.split('\\n').map((line) => {\n return line.endsWith('\\r') ? line.slice(0, -1) : line\n })\n let index = 0\n let inQuote = false\n\n while (index < lines.length) {\n const line = lines[index]!\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 inQuote = advanceSingleQuoteState(line, inQuote)\n index += 1\n continue\n }\n\n const match = ENV_VAR_LINE_PATTERN.exec(line)\n\n if (!match) {\n const unset = UNSET_LINE_PATTERN.exec(line)\n\n if (unset) visitUnset?.(unset[1]!)\n\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const name = match[1]!\n const rest = line.slice(match[0].length)\n\n // An unquoted value cannot span lines (`CONNECTION_STRING=host=db;user=admin`).\n if (!rest.startsWith(\"'\")) {\n visit({ name, value: rest })\n inQuote = advanceSingleQuoteState(line, false)\n index += 1\n continue\n }\n\n const parts = [rest]\n let open = advanceSingleQuoteState(rest, false)\n\n while (open && index + 1 < lines.length) {\n index += 1\n const continuation = lines[index]!\n\n parts.push(continuation)\n open = advanceSingleQuoteState(continuation, true)\n }\n\n visit({ name, value: decodeSingleQuoted(parts.join('\\n')) })\n inQuote = open\n index += 1\n }\n}\n\nexport const parseVarNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(readEnvFileContent(filePath), ({ name }) => {\n names.push(name)\n })\n\n return names\n}\n\n/**\n * Same walk as {@link parseVarNamesFromEnvFile}, but keeping the values. Later\n * assignments win, matching what `source`ing the file would do.\n */\nexport const parseVarsFromEnvFile = (filePath: string): Record<string, string> => {\n const vars: Record<string, string> = {}\n\n forEachAssignment(readEnvFileContent(filePath), ({ name, value }) => {\n vars[name] = value\n })\n\n return vars\n}\n\n/**\n * The names the file `unset`s \u2014 everything env-clear.sh does. Absent file \u2192 `[]`, like\n * its siblings.\n */\nexport const parseUnsetNamesFromEnvFile = (filePath: string): string[] => {\n const names: string[] = []\n\n forEachAssignment(\n readEnvFileContent(filePath),\n () => {},\n (name) => {\n names.push(name)\n },\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 setup` (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(\n `${INFRA_KIT_SESSION_VAR} is not set. Run \\`infra-kit setup --skip-tools\\` then \\`source ~/.zshrc\\`.`,\n )\n }\n\n return path.join(getCacheRoot(), session)\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\n/**\n * Whether `cwd` is one of the directories in an {@link ENV_LOAD_ROOT_FILE}, or under one. Mirrors the\n * `~/.zshenv` check in `init.ts`, symlinks resolved on both sides. No sidecar is in scope everywhere:\n * that is an `env-load.sh` written before the sidecar existed, and it stays usable until the next load.\n */\nexport const isInEnvLoadScope = (rootFile: string, cwd: string): boolean => {\n let content: string\n\n try {\n content = fs.readFileSync(rootFile, 'utf-8')\n } catch {\n return true\n }\n\n const realCwd = safeRealpath(cwd)\n\n return content\n .split('\\n')\n .filter(Boolean)\n .some((root) => {\n return realCwd === root || realCwd.startsWith(`${root}${path.sep}`)\n })\n}\n\nconst safeRealpath = (target: string): string => {\n try {\n return fs.realpathSync(target)\n } catch {\n return path.resolve(target)\n }\n}\n\n/**\n * Canonical `<repo>-worktrees` subdirectory names, shared by every command that lays worktrees\n * out under it (`init`'s scaffold, `worktrees add`) or reasons about that layout (`worktrees\n * sync`/`remove`, `gh merge-dev`'s scratch checkout) \u2014 one literal each, not re-typed per site.\n */\nexport const WORKTREE_SUBDIRS = { release: 'release', feature: 'feature', mergeDev: 'merge-dev' } as const\n"],
|
|
5
|
+
"mappings": "AAAA,OAAOA,MAAQ,UACf,OAAOC,MAAQ,UACf,OAAOC,MAAU,YACjB,OAAOC,MAAa,eAEb,IAAMC,EAAgB,cAChBC,EAAiB,eAKjBC,EAAqB,gBAErBC,EAAwB,oBAYxBC,EAAuB,aAQvBC,EAAoB,gBACpBC,EAA2B,uBAC3BC,EAA4B,wBAK5BC,EAAiC,6BACjCC,EAA8B,0BAO9BC,EAAuB,iBAM9BC,EAAqB,uBAQrBC,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,EAaME,EAAsBC,GAAwB,CAClD,IAAMC,EAAcD,EAAI,WAAW,GAAG,EAAIA,EAAI,MAAM,CAAC,EAAIA,EAGzD,OAFaC,EAAY,SAAS,GAAG,EAAIA,EAAY,MAAM,EAAG,EAAE,EAAIA,GAExD,MAAM,OAAO,EAAE,KAAK,GAAG,CACrC,EAGMC,EAAsBC,GAA6B,CACvD,GAAI,CACF,OAAOzB,EAAG,aAAayB,EAAU,OAAO,CAC1C,MAAQ,CACN,MAAO,EACT,CACF,EASMC,EAAoB,CACxBC,EACAC,EACA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EAAU,OAAO,CAC7C,MAAQ,CACN,MAAO,EACT,CAEA,IAAME,EAAUC,EAAaF,CAAG,EAEhC,OAAO9B,EACJ,MAAM;AAAA,CAAI,EACV,OAAO,OAAO,EACd,KAAMiC,GACEF,IAAYE,GAAQF,EAAQ,WAAW,GAAGE,CAAI,GAAG1D,EAAK,GAAG,EAAE,CACnE,CACL,EAEMyD,EAAgBE,GAA2B,CAC/C,GAAI,CACF,OAAO7D,EAAG,aAAa6D,CAAM,CAC/B,MAAQ,CACN,OAAO3D,EAAK,QAAQ2D,CAAM,CAC5B,CACF,EAOaC,EAAmB,CAAE,QAAS,UAAW,QAAS,UAAW,SAAU,WAAY",
|
|
6
|
+
"names": ["fs", "os", "path", "process", "ENV_LOAD_FILE", "ENV_CLEAR_FILE", "ENV_LOAD_ROOT_FILE", "INFRA_KIT_SESSION_VAR", "USER_CONFIG_DIR_NAME", "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", "ENV_VAR_LINE_PATTERN", "UNSET_LINE_PATTERN", "advanceSingleQuoteState", "line", "startInQuote", "inQuote", "i", "decodeSingleQuoted", "raw", "withoutOpen", "readEnvFileContent", "filePath", "forEachAssignment", "content", "visit", "visitUnset", "lines", "index", "match", "unset", "name", "rest", "parts", "open", "continuation", "parseVarNamesFromEnvFile", "names", "parseVarsFromEnvFile", "vars", "value", "parseUnsetNamesFromEnvFile", "getCacheRoot", "xdg", "base", "getSessionCacheDir", "session", "atomicWriteFileSync", "mode", "tmpPath", "error", "WORKTREES_DIR_SUFFIX", "isInEnvLoadScope", "rootFile", "cwd", "realCwd", "safeRealpath", "root", "target", "WORKTREE_SUBDIRS"]
|
|
7
|
+
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{j as C,m as O,n as D}from"./chunk-AWFGP6GY.js";import{
|
|
1
|
+
import{j as C,m as O,n as D}from"./chunk-AWFGP6GY.js";import{e as S}from"./chunk-I23MDR4X.js";import k from"node:fs";import{homedir as Te}from"node:os";import{dirname as _,join as W}from"node:path";import d from"node:process";import{fileURLToPath as Fe}from"node:url";import{execFile as re}from"node:child_process";import{createHash as ne}from"node:crypto";import{existsSync as F,readFileSync as h}from"node:fs";import oe from"node:http";import se from"node:https";import ie from"node:net";import{homedir as le}from"node:os";import{dirname as N,join as p}from"node:path";import f from"node:process";import ae from"node:tls";import{fileURLToPath as ce}from"node:url";import{promisify as ue}from"node:util";var ee=/^[\w@%+=:,./-]+$/,te="'\\''",T=e=>ee.test(e)?e:`'${e.replaceAll("'",te)}'`,x=e=>e.map(T).join(" ");var de=ue(re),me=e=>{let t=JSON.parse(h(e,"utf-8")),r=typeof t.bin=="string"?t.bin:t.bin?.portless;return r==null||r===""?null:r},E=()=>{try{let e=N(ce(import.meta.url));for(;;){let t=p(e,"node_modules","portless","package.json");if(F(t)){let n=me(t);return n==null?null:p(N(t),n)}let r=N(e);if(r===e)return null;e=r}}catch{return null}},v,M=()=>(v===void 0&&(v=E()),v),U=(e,t)=>{let r=[t.execPath??f.execPath,t.bin,...e];return(t.sudo===!0?"sudo ":"")+x(r)},pe=1500,L=1500,fe="x-portless",I="127.0.0.1",ge="localhost",Pe="sh.portless.proxy",he=`/Library/LaunchDaemons/${Pe}.plist`,ye="/etc/systemd/system/portless.service",it="portless",Se=(e=F)=>{try{return f.platform==="darwin"?e(he)?"yes":"no":f.platform==="linux"?e(ye)?"yes":"no":"unknown"}catch{return"unknown"}},ke=e=>new Promise(t=>{let r=ie.connect({host:I,port:e}),n=o=>{r.destroy(),t(o)};r.setTimeout(L),r.once("connect",()=>{n(!0)}),r.once("timeout",()=>{n(!1)}),r.once("error",()=>{n(!1)})}),be=(e,t)=>new Promise(r=>{let o=(t?se.request:oe.request)({host:I,port:e,method:"HEAD",path:"/",timeout:L,...t?{rejectUnauthorized:!1,servername:ge}:{}},s=>{s.resume(),r(s.headers[fe]==="1")});o.on("error",()=>{r(!1)}),o.on("timeout",()=>{o.destroy(),r(!1)}),o.end()}),xe=async(e,{timeoutMs:t})=>{let r=M();if(r==null)throw new Error("portless is not installed (not resolvable from node_modules)");await de(f.execPath,[r,...e],{signal:AbortSignal.timeout(t),encoding:"utf-8",env:D(f.env)})},w=()=>f.env.PORTLESS_STATE_DIR??p(le(),".portless"),Ne="ca.pem",ve="ca.trusted",B=()=>p(w(),Ne),lt=()=>{try{let e=h(p(w(),ve),"utf-8").trim();return e===""?!1:ne("sha256").update(h(B())).digest("hex")===e.toLowerCase()}catch{return!1}},at=(e,t)=>new Promise(r=>{let n;try{n=h(B())}catch{r({ok:!1,code:"ENOENT"});return}let o=ae.connect({host:I,port:e,servername:t,ca:[n],rejectUnauthorized:!0},()=>{let s=o.authorizationError,i=o.authorized;o.destroy(),r(i?{ok:!0}:{ok:!1,code:s?.code??s?.message??"UNKNOWN"})});o.setTimeout(L),o.once("timeout",()=>{o.destroy(),r({ok:!1,code:"ETIMEDOUT"})}),o.once("error",s=>{o.destroy(),r({ok:!1,code:s.code??"UNKNOWN"})})}),ct=()=>{try{let e=JSON.parse(h(p(w(),"routes.json"),"utf-8"));return Array.isArray(e)?e.flatMap(t=>{let{hostname:r,port:n}=t??{};return typeof r!="string"||r===""||typeof n!="number"?[]:[{name:r,port:n}]}):[]}catch{return[]}},ut=(e={})=>{let t=e.bin===void 0?M():e.bin,r=e.run??xe,n=e.isListening??ke,o=e.isProxyServing??be,s=e.isServiceInstalled??Se,i=e.timeoutMs??pe,a=null,l=async u=>{try{return await r(u,{timeoutMs:i}),!0}catch{return!1}},c=async()=>(a??=await l(["--version"]),a);return{binPath:()=>t,isAvailable:c,isProxyServing:async(u,P)=>!await c()||!await n(u)?!1:o(u,P),probeProxy:async(u,P)=>await n(u)?await o(u,P)?"serving":"not-portless":"daemon-down",isServiceInstalled:s,registerAlias:async(u,P)=>await c()?l(["alias",u,String(P)]):!1,removeAlias:async u=>{await c()&&await l(["alias","--remove",u])}}};import y from"node:fs";import{basename as z,dirname as $,join as j}from"node:path";import G from"node:process";var R=e=>j(e,S,"node"),H=e=>`${R(e)}.source.json`,Ee=e=>{if(typeof e!="object"||e===null)return!1;let t=e,r=["version","arch","platform","source","refreshedAt","versionChangedAt"];return(t.method==="hardlink"||t.method==="copy")&&r.every(n=>typeof t[n]=="string")&&(t.sourceSize===void 0||typeof t.sourceSize=="number")},Le=y.constants.COPYFILE_FICLONE|y.constants.COPYFILE_EXCL,Ie=493,we=(e,t=y)=>{try{let r=JSON.parse(t.readFileSync(H(e),"utf8"));return Ee(r)?r:null}catch{return null}},J=(e,t)=>e.ino===t.ino&&e.dev===t.dev,K=e=>{let{home:t,execPath:r,fs:n=y}=e,o=R(t);try{let s=n.lstatSync(o,{throwIfNoEntry:!1}),i=n.statSync(r,{throwIfNoEntry:!1});return s===void 0||i===void 0||!s.isFile()?null:J(s,i)?o:null}catch{return null}},Y=(e,t)=>e.version===t.version&&e.arch===t.arch&&e.platform===t.platform,Re=(e,t,r,n)=>Y(r,n)?J(e,t)?!0:r.method==="copy"&&r.sourceSize===t.size:!1,A=(e,t)=>{try{t.unlinkSync(e)}catch{}},Ae=(e,t,r)=>{let n;try{n=r.readdirSync(e)}catch{return}for(let o of n)t.some(i=>o.startsWith(i))&&A(j(e,o),r)},_e=(e,t,r)=>{try{return r.linkSync(e,t),"hardlink"}catch{return r.copyFileSync(e,t,Le),r.chmodSync(t,Ie),"copy"}},Ce=(e,t,r)=>{let n=`${t}.tmp-${G.pid}`;try{let o=_e(e,n,r);return r.renameSync(n,t),o}catch(o){throw A(n,r),o}},Oe=(e,t,r)=>{let n=`${e}.tmp-${G.pid}`;try{r.writeFileSync(n,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`),r.renameSync(n,e)}catch(o){throw A(n,r),o}},De=(e,t,r,n,o)=>{let s=e!==null&&Y(e,n)&&(e.sourceSize===void 0||e.sourceSize===r.size);return{method:t,version:n.version,arch:n.arch,platform:n.platform,source:n.execPath,...t==="copy"?{sourceSize:r.size}:{},refreshedAt:o,versionChangedAt:s?e.versionChangedAt:o}},q=e=>{let{home:t,execPath:r,version:n,fs:o=y,now:s=()=>new Date}=e,i=R(t),a=H(t),l=(c,m)=>({kind:"node",outcome:c,node:i,source:r,version:n,method:m});if(e.platform!=="darwin"&&e.platform!=="linux")return l("skipped-platform",null);if(!e.isGlobal())return l("skipped-local",null);try{o.mkdirSync($(i),{recursive:!0});let c=o.lstatSync(i,{throwIfNoEntry:!1});if(c!==void 0&&!c.isFile())return l("failed",null);let m=o.statSync(r,{throwIfNoEntry:!1});if(m===void 0)return l("failed",null);let g=we(t,o);if(c!==void 0&&g!==null&&Re(c,m,g,e))return l("unchanged",g.method);Ae($(i),[`${z(i)}.tmp-`,`${z(a)}.tmp-`],o);let b=Ce(r,i,o);return Oe(a,De(g,b,m,e,s().toISOString()),o),l(c===void 0?"created":"refreshed",b)}catch{return l("failed",null)}};var Q=e=>W(e,S,"portless"),Me=(e,t=k.existsSync)=>{let r=W(Q(e),"dist","cli.js");return t(r)?r:null},Lt=(e,t)=>{let r=t.execPath??d.execPath,n=t.stableNode===void 0?K({home:t.home,execPath:r}):t.stableNode;return U(["service","install"],{sudo:!0,bin:Me(t.home,t.exists)??e,execPath:n??r})},X=Symbol("absent"),Z=Symbol("not-a-symlink"),Ue=(e,t)=>{let r=t.lstatSync(e,{throwIfNoEntry:!1});return r===void 0?X:r.isSymbolicLink()?t.readlinkSync(e):Z},Be=(e,t,r)=>{let n=`${t}.tmp-${d.pid}`;try{r.unlinkSync(n)}catch{}r.symlinkSync(e,n);try{r.renameSync(n,t)}catch(o){try{r.unlinkSync(n)}catch{}throw o}},ze=e=>{let{resolveBin:t,isGlobal:r,home:n,fs:o=k}=e,s=Q(n),i=t();if(i===null)return{kind:"link",outcome:"skipped-unresolved",target:null,link:s};let a=_(_(i));if(!r())return{kind:"link",outcome:"skipped-local",target:a,link:s};try{o.mkdirSync(_(s),{recursive:!0});let l=Ue(s,o);return l===a?{kind:"link",outcome:"unchanged",target:a,link:s}:l===Z?{kind:"link",outcome:"failed",target:a,link:s}:(Be(a,s,o),{kind:"link",outcome:l===X?"created":"repointed",target:a,link:s})}catch{return{kind:"link",outcome:"failed",target:a,link:s}}},$e=()=>{let e=Te(),t,r=()=>(t??=C({selfRealPath:k.realpathSync(Fe(import.meta.url)),env:d.env,realpath:O,home:e,exists:k.existsSync}),t);return{link:{resolveBin:E,isGlobal:r,home:e},node:{isGlobal:r,home:e,execPath:d.execPath,version:d.version,arch:d.arch,platform:d.platform}}},V=(e,t,r)=>{try{e(r(),t)}catch{}},It=(e,t)=>{let r=t??$e();V(e,"portless link",()=>ze(r.link)),V(e,"portless node",()=>q(r.node))};export{x as a,E as b,U as c,Pe as d,he as e,ye as f,it as g,ke as h,be as i,w as j,B as k,lt as l,at as m,ct as n,ut as o,R as p,we as q,q as r,Q as s,Me as t,Lt as u,ze as v,$e as w,It as x};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-IT6XJWTW.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/dev/proxy/portless-link.ts", "../src/dev/proxy/portless-driver.ts", "../src/lib/shell-quote/shell-quote.ts", "../src/dev/proxy/portless-node.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview\n *\n * `~/.infra-kit/portless` \u2014 a stable symlink to the portless PACKAGE directory bundled with the running\n * infra-kit, kept pointing at the current install by every process boot.\n *\n * Why it exists: `portless service install` bakes `process.execPath` and `process.argv[1]` verbatim into\n * the root launchd plist (`ProgramArguments`), and it offers no `--entry` flag to say otherwise. Under\n * pnpm 12 the script half of that pair is version-unstable \u2014 every `pnpm add -g infra-kit@x` mints a\n * fresh `global/v11/{pid}-{timestamp}/` project and removes the previous one, and the path also embeds\n * `infra-kit@<version>`. With silent auto-update on, the daemon's argv dangles after every release,\n * launchd cannot start it at the next boot, and the \"fix\" is another sudo. Node does NOT realpath\n * `argv[1]` (it keeps whatever string it was given) but DOES realpath `execPath`, so only the script half\n * can be made stable: point the plist at `<link>/dist/cli.js` and keep the link current.\n *\n * Why tmp + rename, never unlink first: `rename(2)` replaces a symlink atomically, so there is no\n * instant at which the path is absent. An unlink-then-symlink sequence has one \u2014 and a reboot inside it\n * leaves launchd with no script at all; `KeepAlive` retries the same dangling path forever, and `:443`\n * stays dark until a human runs `service install` again.\n *\n * Why the boot call must run on `version --json`: that is the exact invocation the background updater\n * spawns to verify a fresh install (`run-update-check.ts`, `readInstalledVersion`: `cwd = homedir()`,\n * `--json`, piped stdio). It is the FIRST process the new binary ever runs \u2014 and the one that re-points\n * the link after an auto-update, before any shell command does. So `bootPortlessLink` must not sit\n * behind `warnIfLocalInstall`'s `--json` guard, and it must not have an env opt-out: the link is state,\n * not advisory output.\n *\n * Every write is guarded by `isGlobalInstall`: a checkout or a project-local dependency never aims the\n * root daemon at itself (that would dangle the moment the worktree is removed). Nothing here spawns a\n * subprocess, touches stdout, or throws \u2014 the `ik-mcp` proxy calls it at boot with stdout carrying the\n * JSON-RPC transport, and the CLI calls it before Commander parses argv.\n */\nimport fs from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport process from 'node:process'\nimport { fileURLToPath } from 'node:url'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\nimport { isGlobalInstall, safeRealpath } from 'src/lib/install-manager'\n\nimport { formatPortlessCommand, resolvePortlessBin } from './portless-driver'\nimport type { ExistsCheck } from './portless-driver'\nimport { ensurePortlessNode, stableNodeCandidate } from './portless-node'\nimport type { EnsurePortlessNodeDeps, PortlessNodeResult } from './portless-node'\n\n/** `<home>/.infra-kit/portless` \u2014 the link path; the same `home` seam the rest of the config layer uses. */\nexport const portlessLinkPath = (home: string): string => {\n return join(home, USER_CONFIG_DIR_NAME, 'portless')\n}\n\n/**\n * `<link>/dist/cli.js` when the link resolves to a portless with that file, else `null` \u2014 the path the\n * printed `service install` command (and the plist it writes) should carry. `exists` follows the\n * symlink, so a dangling link answers `null` and callers fall back to the real path.\n */\nexport const portlessLinkCliPath = (\n home: string,\n exists: (target: string) => boolean = fs.existsSync,\n): string | null => {\n const cliPath = join(portlessLinkPath(home), 'dist', 'cli.js')\n\n return exists(cliPath) ? cliPath : null\n}\n\n/** Where the link is looked up and which node to print; every seam is injectable so tests never read a real `~/.infra-kit`. */\nexport interface ServiceInstallSeams {\n home: string\n exists?: ExistsCheck\n execPath?: string\n /**\n * `~/.infra-kit/node` as a health verdict: a string is \"resolved and healthy \u2014 render through it\"\n * (doctor/setup after their node row), `null` is \"resolved and unhealthy or absent \u2014 render through\n * `execPath`, the node that provably runs\", `undefined` is \"not resolved\" and the inode-only candidate\n * is checked here instead (`dev`, which never spawns on its hot path).\n */\n stableNode?: string | null\n}\n\n/**\n * The one-time, out-of-band, ROOT command that installs the `:443` daemon. infra-kit never runs it \u2014 it\n * only ever prints it (principle 3: infra-kit probes and prints, it never elevates). `doctor`, `setup`\n * and `dev` all print it from here so no two surfaces can disagree about the path that ends up as root.\n *\n * Rendered THROUGH `~/.infra-kit/portless/dist/cli.js` whenever that link resolves: portless bakes the\n * script path it was invoked with into the plist, so the command printed here decides whether the root\n * daemon survives the next `pnpm add -g infra-kit` (the link is re-pointed on every boot; the version-\n * specific path is deleted). `bin` \u2014 the resolved `dist/cli.js`, never a bare `portless` (see\n * {@link formatPortlessCommand}) \u2014 is the fallback only, for a machine where nothing has created the\n * link yet.\n */\nexport const serviceInstallCommand = (bin: string, seams: ServiceInstallSeams): string => {\n // Resolved before the candidate check: `dev` passes `{ home }` only, and the candidate must never stat `undefined`.\n const execPath = seams.execPath ?? process.execPath\n // Written out rather than `??`-chained: a `null` verdict (\"resolved, unhealthy\") must reach `execPath`\n // directly and never fall through to a candidate check that would contradict doctor's spawn.\n const stableNode =\n seams.stableNode === undefined ? stableNodeCandidate({ home: seams.home, execPath }) : seams.stableNode\n\n return formatPortlessCommand(['service', 'install'], {\n sudo: true,\n bin: portlessLinkCliPath(seams.home, seams.exists) ?? bin,\n execPath: stableNode ?? execPath,\n })\n}\n\nexport type PortlessLinkOutcome =\n 'created' | 'repointed' | 'unchanged' | 'skipped-local' | 'skipped-unresolved' | 'failed'\n\nexport interface PortlessLinkResult {\n kind: 'link'\n outcome: PortlessLinkOutcome\n /** The portless package dir the link should point at; `null` only for `'skipped-unresolved'`. */\n target: string | null\n link: string\n}\n\n/**\n * The six fs calls the link needs, as an OBJECT seam. Named `node:fs` imports cannot be intercepted by\n * `vi.spyOn` (the binding is a live import, not a property), so the default export is the injectable\n * shape and tests hand in an in-memory fake instead of touching a real `~/.infra-kit`.\n */\nexport interface PortlessLinkFs {\n mkdirSync: (dir: string, options: { recursive: true }) => unknown\n lstatSync: (target: string, options: { throwIfNoEntry: false }) => { isSymbolicLink: () => boolean } | undefined\n readlinkSync: (target: string) => string\n symlinkSync: (target: string, linkPath: string) => void\n renameSync: (from: string, to: string) => void\n unlinkSync: (target: string) => void\n}\n\nexport interface EnsurePortlessLinkDeps {\n /** `resolvePortlessBin` \u2014 the bundled portless's `dist/cli.js`, or `null` when it is not installed. */\n resolveBin: () => string | null\n /** `isGlobalInstall` bound to this process \u2014 the ONLY gate between a checkout and the root daemon. */\n isGlobal: () => boolean\n home: string\n fs?: PortlessLinkFs\n}\n\n/** What currently sits at the link path, beyond \"a symlink to X\". */\nconst ABSENT = Symbol('absent')\nconst NOT_A_SYMLINK = Symbol('not-a-symlink')\n\nconst readCurrentLink = (link: string, linkFs: PortlessLinkFs): string | typeof ABSENT | typeof NOT_A_SYMLINK => {\n const stat = linkFs.lstatSync(link, { throwIfNoEntry: false })\n\n if (stat === undefined) return ABSENT\n if (!stat.isSymbolicLink()) return NOT_A_SYMLINK\n\n return linkFs.readlinkSync(link)\n}\n\n/**\n * Publish `target` at `link` through a pid-suffixed sibling and one `rename`, so the path never goes\n * absent (see the file header). The sibling is cleared BEFORE the symlink as well as after a failed\n * rename: a crash between the two calls leaves `.tmp-<pid>` behind forever, and pid reuse would then\n * turn a later boot's `symlinkSync` into EEXIST \u2014 a `'failed'` for a link that is fine. The name is\n * ours alone, never user data, so removing whatever sits there is safe; `ENOENT` is the normal case.\n */\nconst writeLink = (target: string, link: string, linkFs: PortlessLinkFs): void => {\n const tmp = `${link}.tmp-${process.pid}`\n\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Nothing to clear \u2014 the ordinary path.\n }\n\n linkFs.symlinkSync(target, tmp)\n\n try {\n linkFs.renameSync(tmp, link)\n } catch (error) {\n try {\n linkFs.unlinkSync(tmp)\n } catch {\n // Best effort: the failed rename is the error worth surfacing, not the leftover sibling.\n }\n\n throw error\n }\n}\n\n/**\n * Converge `~/.infra-kit/portless` on the portless bundled with THIS install. Never throws; every\n * outcome is a value so callers can log it without a try/catch of their own.\n *\n * A non-symlink at the link path is `'failed'` and left exactly as found: this code owns a symlink, not\n * whatever a user or another tool put there, and removing a directory to make room would be the one\n * destructive action a boot hook must never take.\n *\n * @example\n * ensurePortlessLink({ resolveBin: () => '/g/node_modules/portless/dist/cli.js', isGlobal: () => true, home: '/Users/x' })\n * // => { kind: 'link', outcome: 'created', target: '/g/node_modules/portless', link: '/Users/x/.infra-kit/portless' }\n */\nexport const ensurePortlessLink = (deps: EnsurePortlessLinkDeps): PortlessLinkResult => {\n const { resolveBin, isGlobal, home, fs: linkFs = fs } = deps\n const link = portlessLinkPath(home)\n const bin = resolveBin()\n\n if (bin === null) return { kind: 'link', outcome: 'skipped-unresolved', target: null, link }\n\n const target = dirname(dirname(bin))\n\n if (!isGlobal()) return { kind: 'link', outcome: 'skipped-local', target, link }\n\n try {\n linkFs.mkdirSync(dirname(link), { recursive: true })\n\n const current = readCurrentLink(link, linkFs)\n\n if (current === target) return { kind: 'link', outcome: 'unchanged', target, link }\n if (current === NOT_A_SYMLINK) return { kind: 'link', outcome: 'failed', target, link }\n\n writeLink(target, link, linkFs)\n\n return { kind: 'link', outcome: current === ABSENT ? 'created' : 'repointed', target, link }\n } catch {\n return { kind: 'link', outcome: 'failed', target, link }\n }\n}\n\n/**\n * `(fields, message)` \u2014 the shape of `logger.debug`, so the CLI can pass it straight through. The two\n * boot results are a union on `kind`: a caller that reads `link`/`target` (the `ik-mcp` stderr line)\n * narrows first.\n */\nexport type PortlessLinkLog = (result: PortlessLinkResult | PortlessNodeResult, message: string) => void\n\n/** The link's seams and the node's, sharing ONE `isGlobal` \u2014 the two are converged together at every boot. */\nexport interface PortlessStableDeps {\n link: EnsurePortlessLinkDeps\n node: EnsurePortlessNodeDeps\n}\n\n/**\n * The real seams. Shared with `setup`, which needs the RESULTS back to report its steps, so the writers\n * can never disagree about which install is \"global\" or where the files go. `isGlobal` is memoised\n * per deps object: it costs a `realpathSync` plus the `.git` walk, and both steps ask it.\n */\nexport const realPortlessStableDeps = (): PortlessStableDeps => {\n const home = homedir()\n let global: boolean | undefined\n\n const isGlobal = (): boolean => {\n global ??= isGlobalInstall({\n selfRealPath: fs.realpathSync(fileURLToPath(import.meta.url)),\n env: process.env,\n realpath: safeRealpath,\n home,\n exists: fs.existsSync,\n })\n\n return global\n }\n\n return {\n link: { resolveBin: resolvePortlessBin, isGlobal, home },\n node: {\n isGlobal,\n home,\n execPath: process.execPath,\n version: process.version,\n arch: process.arch,\n platform: process.platform,\n },\n }\n}\n\nconst logStep = (log: PortlessLinkLog, message: string, run: () => PortlessLinkResult | PortlessNodeResult): void => {\n try {\n log(run(), message)\n } catch {\n // A file that could not be converged is `doctor`'s to report; it must never be a boot failure.\n }\n}\n\n/**\n * The process-boot entry for both bins: the link, then the node \u2014 independent state, so the node step\n * runs whatever the link reported. fs-only, no subprocess, never throws, never exits, never writes to\n * stdout; each outcome goes to `log` and nowhere else. `deps` is injectable so the \"`'failed'` is\n * logged\" contract is testable without a real disk.\n */\nexport const bootPortlessLink = (log: PortlessLinkLog, deps?: PortlessStableDeps): void => {\n const stable = deps ?? realPortlessStableDeps()\n\n logStep(log, 'portless link', () => {\n return ensurePortlessLink(stable.link)\n })\n logStep(log, 'portless node', () => {\n return ensurePortlessNode(stable.node)\n })\n}\n", "/**\n * @fileoverview\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>.<repo>.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, an Orca pane, 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'\nimport { shellLine } from 'src/lib/shell-quote'\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/** 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 * Prints what the driver itself runs (see {@link defaultRun}): the current interpreter, by absolute path,\n * invoking portless's `dist/cli.js`, by absolute path. Nothing is resolved from `PATH`, so the command\n * works under `sudo`, from any cwd, and however `infra-kit` was launched.\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 */\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\n// service install` hands the user a command that dies with `sudo: portless: command not found`. `sudo`\n// makes it strictly worse: it replaces `PATH` with `secure_path`, so even a shell that *could* resolve\n// `portless` loses it the moment the command is elevated.\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\n// root.\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 + shellLine(words)\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_LABEL = 'sh.portless.proxy'\nexport const DARWIN_SERVICE_PLIST_PATH = `/Library/LaunchDaemons/${DARWIN_SERVICE_LABEL}.plist`\nexport const LINUX_SERVICE_UNIT_PATH = '/etc/systemd/system/portless.service'\n/** The systemd unit name `service install` registers on Linux \u2014 the `systemctl` argument, not a path. */\nexport const LINUX_SERVICE_UNIT_NAME = 'portless'\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 * `rejectUnauthorized: false` is deliberate and load-bearing: this probe answers *\"is portless serving\n * here?\"*, **never** *\"is its CA trusted?\"*. Trust is a separate, explicitly-validating probe (doctor's\n * CA check).\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// Validating the chain here would collapse two different failures \u2014 a daemon that is down, and a CA that\n// was never trusted \u2014 into one indistinguishable error, with two different fixes (a root `service install`\n// vs the sudo-free `trust`).\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.hulyo-monorepo.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>.<repo>`). 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", "/**\n * Render an argv array as a line a POSIX shell runs back verbatim.\n *\n * Every surface that PRINTS a command for a human to paste has the same obligation, and `join(' ')` does\n * not meet it. The load-bearing case is `lib/dependency-install`'s refusals: a recipe we decline to run\n * is printed precisely so the human can run it, and joining\n * `['/bin/bash', '-c', 'curl -fsSL \u2026 | bash']` on spaces yields\n * `/bin/bash -c curl -fsSL \u2026 | bash` \u2014 which loses the argument boundary and runs `curl` with `-fsSL`\n * as `$0`, no URL, and the rest piped into a second shell. It fails, and it fails in a way that reads\n * like the tool's fault rather than the transcription's.\n *\n * The implementation began inside `dev/proxy/portless-driver`, which needed it first and is still a\n * caller; a second copy beside the recipes would drift from it.\n */\n\n/**\n * Characters that survive a POSIX shell unquoted. Anything outside this set \u2014 a space, a pipe, a paren,\n * all of which appear in real recipes and real install paths \u2014 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. */\nexport const shellQuote = (value: string): string => {\n return SHELL_SAFE.test(value) ? value : `'${value.replaceAll(\"'\", SINGLE_QUOTE_ESCAPE)}'`\n}\n\n/** One pasteable shell line from an argv array, each word quoted only when it needs to be. */\nexport const shellLine = (argv: readonly string[]): string => {\n return argv.map(shellQuote).join(' ')\n}\n", "/**\n * @fileoverview\n *\n * `~/.infra-kit/node` \u2014 a stable, regular-file name for the Node binary the global infra-kit runs, kept\n * current by every process boot beside `~/.infra-kit/portless` (see that module's header for the link).\n *\n * Why a HARDLINK: `portless service install` bakes `process.execPath` into the root plist, and Node\n * realpaths `execPath` (measured: a hardlink of node prints its own path from `-p process.execPath`;\n * a symlink prints the target), so no symlink in front of the binary survives into the plist. Under\n * pnpm 12 the binary lives in `global/v11/{pid}-{ts}/\u2026/node@runtime/\u2026`, a directory every `pnpm add -g`\n * re-mints \u2014 with no Node bump. A hardlink is a regular file, costs 0.3 ms and 0 bytes, and its inode\n * outlives the manager's directory, so the name cannot dangle across a re-mint + reboot the way a\n * symlink would. `copyFile(COPYFILE_FICLONE)` is a full 134 MB copy on APFS here, so it is the FALLBACK\n * only: root-owned `/usr/bin/node` under `protected_hardlinks`, a cross-volume home (macOS answers\n * `EPERM`, not `EXDEV`), exFAT/SMB/NFS (`ENOTSUP`), dataless iCloud (`EDEADLK`) \u2014 the failure set of\n * `link(2)` is not enumerable, so ANY throw takes the copy. The daemon never consults `execPath` again\n * after boot (`proxy start --foreground` spawns nothing), so that one plist word is the whole contract.\n *\n * T-1 \u2014 the hardlink SHARES an inode with the package manager's node, and macOS enforces no `ETXTBSY`:\n * a write through this name lands in the developer's real node and, on Apple Silicon, kills every\n * process mapping it by signature invalidation. Rename-only discipline is the ONLY guard: every byte\n * goes to a `node.tmp-<pid>` sibling and is published by `rename(2)`; the node path is never opened\n * for writing, never chmod'ed (that too mutates the shared inode) and never unlinked. `chmod` runs on\n * the copy branch's tmp alone \u2014 the source is executable already, this process executed it.\n *\n * Staleness is one inode compare against `process.execPath`, never a version or byte compare: after a\n * re-mint the source is a new inode with identical bytes and relinking is free. The sidecar keeps two\n * clocks \u2014 `refreshedAt` (the file) and `versionChangedAt` (the Node behind it, carried over on a\n * same-version relink) \u2014 because doctor's \"daemon predates Node \u2026\" advisory must not nag after every\n * global install. Neither is an fs timestamp: a hardlink's mtime is the source's install time.\n *\n * Same gate and contract as the link: `isGlobalInstall` is the only thing between a checkout and the\n * root daemon; nothing here spawns, writes stdout, or throws.\n */\nimport fs from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\nimport process from 'node:process'\n\nimport { USER_CONFIG_DIR_NAME } from 'src/lib/constants'\n\n/** `<home>/.infra-kit/node` \u2014 the file the plist's first argv word names. */\nexport const portlessNodePath = (home: string): string => {\n return join(home, USER_CONFIG_DIR_NAME, 'node')\n}\n\n/** `<node>.source.json` \u2014 what the file is (method, Node triple, source) and the two clocks. */\nexport const portlessNodeSidecar = (home: string): string => {\n return `${portlessNodePath(home)}.source.json`\n}\n\n// Hand-checked, not zod: this module is reached from the `ik-mcp` bundle, which must stay free of every\n// node_modules input (`dist-shebang.test.ts`). A sidecar is eight scalars \u2014 a validator is cheaper than\n// the dependency.\nexport interface PortlessNodeSidecar {\n method: 'hardlink' | 'copy'\n version: string\n arch: string\n platform: string\n source: string\n sourceSize?: number\n refreshedAt: string\n versionChangedAt: string\n}\n\nconst isSidecar = (value: unknown): value is PortlessNodeSidecar => {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Record<string, unknown>\n const strings = ['version', 'arch', 'platform', 'source', 'refreshedAt', 'versionChangedAt']\n\n return (\n (record.method === 'hardlink' || record.method === 'copy') &&\n strings.every((key) => {\n return typeof record[key] === 'string'\n }) &&\n (record.sourceSize === undefined || typeof record.sourceSize === 'number')\n )\n}\n\n/** The subset of `fs.Stats` the inode compare and the copy-path size witness need. */\nexport interface PortlessNodeStat {\n ino: number\n dev: number\n size: number\n isFile: () => boolean\n}\n\n/**\n * Every fs call the file needs, as an OBJECT seam: `vi.spyOn` cannot intercept named `node:fs` imports,\n * so tests hand in an in-memory fake and the call log \u2014 not the final state \u2014 carries the rename-only\n * contract (T-1). `copyFileSync` takes the mode so the FICLONE flag is visible in that log.\n */\nexport interface PortlessNodeFs {\n mkdirSync: (dir: string, options: { recursive: true }) => unknown\n lstatSync: (target: string, options: { throwIfNoEntry: false }) => PortlessNodeStat | undefined\n statSync: (target: string, options: { throwIfNoEntry: false }) => PortlessNodeStat | undefined\n readFileSync: (target: string, encoding: 'utf8') => string\n writeFileSync: (target: string, data: string) => void\n readdirSync: (dir: string) => string[]\n linkSync: (existing: string, newPath: string) => void\n copyFileSync: (src: string, dest: string, mode: number) => void\n chmodSync: (target: string, mode: number) => void\n renameSync: (from: string, to: string) => void\n unlinkSync: (target: string) => void\n}\n\nexport type PortlessNodeOutcome =\n 'created' | 'refreshed' | 'unchanged' | 'skipped-local' | 'skipped-platform' | 'failed'\n\nexport interface PortlessNodeResult {\n kind: 'node'\n outcome: PortlessNodeOutcome\n node: string\n /** The `execPath` the file was (or would have been) made from. */\n source: string\n version: string\n /** How the file relates to `source`; `null` when nothing was published and nothing converged was found. */\n method: 'hardlink' | 'copy' | null\n}\n\nexport interface EnsurePortlessNodeDeps {\n /** The SAME memoised closure the link uses \u2014 the ONLY gate between a checkout and the root daemon. */\n isGlobal: () => boolean\n home: string\n execPath: string\n version: string\n arch: string\n platform: NodeJS.Platform\n fs?: PortlessNodeFs\n now?: () => Date\n}\n\n// EXCL is load-bearing, not hygiene: a stale `node.tmp-<pid>` from a boot that died before its `rename`\n// can be a HARDLINK of the live node, and a reused pid would hand the copy branch that name \u2014 an\n// `O_TRUNC` open of it is the T-1 write-through. With EXCL the copy refuses (`EEXIST` \u2192 `'failed'`) and\n// the next boot's sweep clears the name.\nconst COPY_FLAGS = fs.constants.COPYFILE_FICLONE | fs.constants.COPYFILE_EXCL\nconst COPY_MODE = 0o755\n\n/** `null` when the sidecar is absent, unreadable or does not parse \u2014 every one of those forces a refresh. */\nexport const readPortlessNodeSidecar = (home: string, nodeFs: PortlessNodeFs = fs): PortlessNodeSidecar | null => {\n try {\n const parsed: unknown = JSON.parse(nodeFs.readFileSync(portlessNodeSidecar(home), 'utf8'))\n\n return isSidecar(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\nconst sameInode = (a: PortlessNodeStat, b: PortlessNodeStat): boolean => {\n return a.ino === b.ino && a.dev === b.dev\n}\n\n/**\n * `<home>/.infra-kit/node` when it is a regular file on the SAME inode as `execPath`, else `null`.\n * Inode equality is proof of runnability \u2014 the asking process IS that inode \u2014 so this needs no sidecar\n * and no spawn, which is what lets `dev` render the short `service install` line on its hot path. A\n * copy-path file is never a candidate: nothing short of running it proves it runs (doctor's job).\n */\nexport const stableNodeCandidate = (input: { home: string; execPath: string; fs?: PortlessNodeFs }): string | null => {\n const { home, execPath, fs: nodeFs = fs } = input\n const node = portlessNodePath(home)\n\n try {\n const current = nodeFs.lstatSync(node, { throwIfNoEntry: false })\n const exec = nodeFs.statSync(execPath, { throwIfNoEntry: false })\n\n if (current === undefined || exec === undefined || !current.isFile()) return null\n\n return sameInode(current, exec) ? node : null\n } catch {\n return null\n }\n}\n\ntype NodeTriple = Pick<EnsurePortlessNodeDeps, 'version' | 'arch' | 'platform'>\n\nconst describesProcess = (sidecar: PortlessNodeSidecar, deps: NodeTriple): boolean => {\n return sidecar.version === deps.version && sidecar.arch === deps.arch && sidecar.platform === deps.platform\n}\n\n/**\n * The fast path. Inode equality is the strongest signal for the FILE; the version clause is for the\n * SIDECAR: a crash between the two renames after a Node bump leaves the new inode described as the old\n * version with a pre-bump `versionChangedAt`, and without this clause that would be `'unchanged'` forever\n * (doctor printing the wrong version, the restart advisory keyed on a clock that is too old). On the copy\n * path the inode can never match, so the size is the second witness beside the version triple.\n */\nconst isConverged = (\n current: PortlessNodeStat,\n exec: PortlessNodeStat,\n sidecar: PortlessNodeSidecar,\n deps: NodeTriple,\n): boolean => {\n if (!describesProcess(sidecar, deps)) return false\n if (sameInode(current, exec)) return true\n\n return sidecar.method === 'copy' && sidecar.sourceSize === exec.size\n}\n\nconst discard = (tmp: string, nodeFs: PortlessNodeFs): void => {\n try {\n nodeFs.unlinkSync(tmp)\n } catch {\n // Best effort: the failure that got us here is the one worth surfacing, not a leftover sibling.\n }\n}\n\n/**\n * A SIGKILL mid-copy leaves a 134 MB `node.tmp-<pid>` under a pid that may never recur; the sidecar\n * orphan is ~250 B, but one pass covers both. Only these two prefixes are ours to remove. A concurrent\n * boot's live tmp may go too \u2014 its `rename` then fails into `'failed'` and the next boot converges;\n * the published name always holds a complete file.\n */\nconst sweepOrphans = (dir: string, prefixes: string[], nodeFs: PortlessNodeFs): void => {\n let names: string[]\n\n try {\n names = nodeFs.readdirSync(dir)\n } catch {\n return\n }\n\n for (const name of names) {\n const orphan = prefixes.some((prefix) => {\n return name.startsWith(prefix)\n })\n\n if (orphan) discard(join(dir, name), nodeFs)\n }\n}\n\n/** Hardlink first; on ANY throw, the copy (see the header for why the error set is not filtered). */\nconst stageNode = (execPath: string, tmp: string, nodeFs: PortlessNodeFs): 'hardlink' | 'copy' => {\n try {\n nodeFs.linkSync(execPath, tmp)\n\n return 'hardlink'\n } catch {\n nodeFs.copyFileSync(execPath, tmp, COPY_FLAGS)\n // The copy branch ONLY: on a hardlink this would chmod the manager's inode. 0755 is what the source\n // carries and what root needs to exec a file under a 0700 home \u2014 no secret lives in a node binary.\n // eslint-disable-next-line sonarjs/file-permissions -- an executable's mode, not a data file's\n nodeFs.chmodSync(tmp, COPY_MODE)\n\n return 'copy'\n }\n}\n\n/**\n * Stage under the pid-suffixed sibling, publish by ONE `rename` (T-1). The old inode stays mapped by a\n * running daemon; `rename` touches no byte of it. On any throw the sibling is removed and the old file\n * is exactly as it was.\n */\nconst publishNode = (execPath: string, node: string, nodeFs: PortlessNodeFs): 'hardlink' | 'copy' => {\n const tmp = `${node}.tmp-${process.pid}`\n\n try {\n const method = stageNode(execPath, tmp, nodeFs)\n\n nodeFs.renameSync(tmp, node)\n\n return method\n } catch (error) {\n discard(tmp, nodeFs)\n throw error\n }\n}\n\nconst publishSidecar = (sidecarPath: string, sidecar: PortlessNodeSidecar, nodeFs: PortlessNodeFs): void => {\n const tmp = `${sidecarPath}.tmp-${process.pid}`\n\n try {\n nodeFs.writeFileSync(tmp, `${JSON.stringify(sidecar, null, 2)}\\n`)\n nodeFs.renameSync(tmp, sidecarPath)\n } catch (error) {\n discard(tmp, nodeFs)\n throw error\n }\n}\n\n/**\n * `versionChangedAt` is carried over only when the Node behind the file is the same one the previous\n * sidecar described: the triple, plus the size whenever the previous sidecar recorded one (a copy of a\n * same-version different build IS a different Node). A same-version relink after a re-mint must not\n * look like a Node bump to doctor's restart advisory. No parsable previous sidecar \u2192 `now`, which errs\n * towards one advisory too many, never too few.\n */\nconst nextSidecar = (\n previous: PortlessNodeSidecar | null,\n method: 'hardlink' | 'copy',\n exec: PortlessNodeStat,\n deps: EnsurePortlessNodeDeps,\n now: string,\n): PortlessNodeSidecar => {\n const sameNode =\n previous !== null &&\n describesProcess(previous, deps) &&\n (previous.sourceSize === undefined || previous.sourceSize === exec.size)\n\n return {\n method,\n version: deps.version,\n arch: deps.arch,\n platform: deps.platform,\n source: deps.execPath,\n ...(method === 'copy' ? { sourceSize: exec.size } : {}),\n refreshedAt: now,\n versionChangedAt: sameNode ? previous.versionChangedAt : now,\n }\n}\n\n/**\n * Converge `~/.infra-kit/node` on the Node running THIS install. Never throws; every outcome is a value.\n *\n * A symlink or directory at the path is `'failed'` and left exactly as found \u2014 this code owns a regular\n * file, and removing whatever someone else put there is the one destructive act a boot hook must never\n * take. A converged machine pays one `lstat`, one `stat` and a ~250-byte read: no write, no subprocess.\n *\n * @example\n * ensurePortlessNode({ isGlobal: () => true, home: '/Users/x', execPath: process.execPath, version: process.version, arch: process.arch, platform: process.platform })\n * // => { kind: 'node', outcome: 'created', node: '/Users/x/.infra-kit/node', source: process.execPath, version: process.version, method: 'hardlink' }\n */\nexport const ensurePortlessNode = (deps: EnsurePortlessNodeDeps): PortlessNodeResult => {\n const {\n home,\n execPath,\n version,\n fs: nodeFs = fs,\n now = () => {\n return new Date()\n },\n } = deps\n const node = portlessNodePath(home)\n const sidecarPath = portlessNodeSidecar(home)\n const result = (outcome: PortlessNodeOutcome, method: PortlessNodeResult['method']): PortlessNodeResult => {\n return { kind: 'node', outcome, node, source: execPath, version, method }\n }\n\n if (deps.platform !== 'darwin' && deps.platform !== 'linux') return result('skipped-platform', null)\n if (!deps.isGlobal()) return result('skipped-local', null)\n\n try {\n nodeFs.mkdirSync(dirname(node), { recursive: true })\n\n const current = nodeFs.lstatSync(node, { throwIfNoEntry: false })\n\n if (current !== undefined && !current.isFile()) return result('failed', null)\n\n const exec = nodeFs.statSync(execPath, { throwIfNoEntry: false })\n\n if (exec === undefined) return result('failed', null)\n\n const previous = readPortlessNodeSidecar(home, nodeFs)\n\n if (current !== undefined && previous !== null && isConverged(current, exec, previous, deps)) {\n return result('unchanged', previous.method)\n }\n\n sweepOrphans(dirname(node), [`${basename(node)}.tmp-`, `${basename(sidecarPath)}.tmp-`], nodeFs)\n\n const method = publishNode(execPath, node, nodeFs)\n\n publishSidecar(sidecarPath, nextSidecar(previous, method, exec, deps, now().toISOString()), nodeFs)\n\n return result(current === undefined ? 'created' : 'refreshed', method)\n } catch {\n return result('failed', null)\n }\n}\n"],
|
|
5
|
+
"mappings": "8FAgCA,OAAOA,MAAQ,UACf,OAAS,WAAAC,OAAe,UACxB,OAAS,WAAAC,EAAS,QAAAC,MAAY,YA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GAAc,YAAY,GAAG,CAAC,EAC5D,IAAKxB,EAAQ,IACb,SAAUyB,EACV,KAAApC,EACA,OAAQK,EAAG,UACb,CAAC,EAEM4B,GAGT,MAAO,CACL,KAAM,CAAE,WAAYI,EAAoB,SAAAT,EAAU,KAAA5B,CAAK,EACvD,KAAM,CACJ,SAAA4B,EACA,KAAA5B,EACA,SAAUW,EAAQ,SAClB,QAASA,EAAQ,QACjB,KAAMA,EAAQ,KACd,SAAUA,EAAQ,QACpB,CACF,CACF,EAEM2B,EAAU,CAACC,EAAsBC,EAAiBC,IAA6D,CACnH,GAAI,CACFF,EAAIE,EAAI,EAAGD,CAAO,CACpB,MAAQ,CAER,CACF,EAQaE,GAAmB,CAACH,EAAsBb,IAAoC,CACzF,IAAMiB,EAASjB,GAAQK,GAAuB,EAE9CO,EAAQC,EAAK,gBAAiB,IACrBd,GAAmBkB,EAAO,IAAI,CACtC,EACDL,EAAQC,EAAK,gBAAiB,IACrBK,EAAmBD,EAAO,IAAI,CACtC,CACH",
|
|
6
|
+
"names": ["fs", "homedir", "dirname", "join", "process", "fileURLToPath", "execFile", "createHash", "existsSync", "readFileSync", "http", "https", "net", "homedir", "dirname", "join", "process", "tls", "fileURLToPath", "promisify", "SHELL_SAFE", "SINGLE_QUOTE_ESCAPE", "shellQuote", "value", "shellLine", "argv", "execFileAsync", "promisify", "execFile", "readBinRel", "pkgJsonPath", "pkg", "readFileSync", "rel", "resolvePortlessBin", "dir", "dirname", "fileURLToPath", "join", "existsSync", "parent", "cachedBin", "portlessBin", "formatPortlessCommand", "args", "options", "words", "process", "shellLine", "DEFAULT_TIMEOUT_MS", "PROBE_TIMEOUT_MS", "PORTLESS_HEADER", "LOOPBACK", "PROBE_SERVERNAME", "DARWIN_SERVICE_LABEL", "DARWIN_SERVICE_PLIST_PATH", "LINUX_SERVICE_UNIT_PATH", "LINUX_SERVICE_UNIT_NAME", "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", "fs", "basename", "dirname", "join", "process", "portlessNodePath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessNodeSidecar", "isSidecar", "value", "record", "strings", "key", "COPY_FLAGS", "fs", "COPY_MODE", "readPortlessNodeSidecar", "nodeFs", "parsed", "sameInode", "a", "b", "stableNodeCandidate", "input", "execPath", "node", "current", "exec", "describesProcess", "sidecar", "deps", "isConverged", "discard", "tmp", "sweepOrphans", "dir", "prefixes", "names", "name", "prefix", "stageNode", "publishNode", "process", "method", "error", "publishSidecar", "sidecarPath", "nextSidecar", "previous", "now", "sameNode", "ensurePortlessNode", "version", "result", "outcome", "dirname", "basename", "portlessLinkPath", "home", "join", "USER_CONFIG_DIR_NAME", "portlessLinkCliPath", "exists", "fs", "cliPath", "serviceInstallCommand", "bin", "seams", "execPath", "process", "stableNode", "stableNodeCandidate", "formatPortlessCommand", "ABSENT", "NOT_A_SYMLINK", "readCurrentLink", "link", "linkFs", "stat", "writeLink", "target", "tmp", "error", "ensurePortlessLink", "deps", "resolveBin", "isGlobal", "dirname", "current", "realPortlessStableDeps", "homedir", "global", "isGlobalInstall", "fileURLToPath", "safeRealpath", "resolvePortlessBin", "logStep", "log", "message", "run", "bootPortlessLink", "stable", "ensurePortlessNode"]
|
|
7
|
+
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as P,h as _,l as b,m as A,n as M,o as L}from"./chunk-AWFGP6GY.js";import{
|
|
1
|
+
import{a as P,h as _,l as b,m as A,n as M,o as L}from"./chunk-AWFGP6GY.js";import{n as f,p as N}from"./chunk-I23MDR4X.js";import{spawnSync as Q}from"node:child_process";import{homedir as X}from"node:os";import y from"node:process";import u from"node:fs";import j from"node:path";import oe from"node:process";var se="update-check.lock",ie=1800*1e3,le=()=>j.join(f(),se),ae=(t,e)=>{try{e-u.statSync(t).mtimeMs>ie&&u.rmSync(t,{force:!0})}catch{}},T=(t={})=>{let e=t.nowMs??Date.now(),n=t.lockPath??le();try{u.mkdirSync(j.dirname(n),{recursive:!0})}catch{return null}let r=()=>{try{return u.openSync(n,"wx",384)}catch{return null}},o=r();if(o===null&&(ae(n,e),o=r()),o===null)return null;try{u.writeFileSync(o,String(oe.pid))}catch{}return()=>{try{u.closeSync(o)}catch{}try{u.rmSync(n,{force:!0})}catch{}}};var ce="https://registry.npmjs.org",ue=5e3,pe=t=>Object.entries(t).find(([n,r])=>/^npm_config_registry$/i.test(n)&&r!=null&&r!=="")?.[1],de=t=>{let e=pe(t),n=e!=null&&e!==""?e:ce;for(;n.endsWith("/");)n=n.slice(0,-1);return n},D=async(t,e=fetch)=>{let n=new AbortController,r=setTimeout(()=>{n.abort()},ue);try{let o=await e(`${de(t)}/${P}/latest`,{signal:n.signal,headers:{accept:"application/json"}});if(!o.ok)return null;let i=(await o.json())?.version;return typeof i=="string"&&i!==""?i:null}catch{return null}finally{clearTimeout(r)}};var me=/^(\d+)\.(\d+)\.(\d+)$/,O=t=>{let[e=""]=t.trim().split("+"),[n="",...r]=e.split("-"),o=me.exec(n);if(!o)return null;let[s,i,l]=[o[1],o[2],o[3]].map(Number);return{release:[s,i,l],prerelease:r.length>0?r.join("-").split("."):[]}},V=/^\d+$/,fe=(t,e)=>{let n=V.test(t),r=V.test(e);return n&&r?Number(t)-Number(e):n!==r?n?-1:1:t<e?-1:1},ge=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n+=1){let r=t[n],o=e[n];if(r===void 0)return-1;if(o===void 0)return 1;if(r!==o)return fe(r,o)}return 0},U=(t,e)=>{let n=O(t),r=O(e);if(!n||!r)return!1;for(let i=0;i<3;i+=1){let l=n.release[i],h=r.release[i];if(l!==h)return l>h}let o=n.prerelease.length===0,s=r.prerelease.length===0;return o!==s?o:ge(n.prerelease,r.prerelease)>0};import G from"node:fs";import F from"node:path";var J="update-check.json",he=1200*1e3,Pe=()=>F.join(f(),J),ke=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),Ce=t=>{if(typeof t!="object"||t===null)return!1;let{outcome:e,checkedMs:n}=t;return typeof e=="string"&&typeof n=="number"&&Number.isFinite(n)},we=t=>{if(typeof t!="object"||t===null)return!1;let{lastCheckMs:e,latestVersion:n,updateCommand:r,outcome:o,plugin:s}=t;return typeof e=="number"&&Number.isFinite(e)&&(n===null||typeof n=="string")&&(r===null||ke(r))&&(o==null||typeof o=="string")&&(s===void 0||Ce(s))},st=(t=e=>G.readFileSync(e,"utf8"))=>{try{let e=JSON.parse(t(Pe()));return we(e)?e:null}catch{return null}},S=t=>{let e=f();G.mkdirSync(e,{recursive:!0}),N(F.join(e,J),JSON.stringify(t),384)},it=(t,e)=>{if(!t)return!0;let n=e-t.lastCheckMs;return n<0?!0:n>=he};import{spawnSync as Re}from"node:child_process";import Ne from"node:fs";import q from"node:process";import{spawnSync as ye}from"node:child_process";var k="infra-kit",g="infra-kit@infra-kit",at="ArthurSaenz/infra-kit";var I="claude",Ee=12e4,K=["--version"],$=["plugin","update",g,"--scope","project","-y"],H=t=>{let e=ye(I,[...t.args],{cwd:t.cwd,encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:Ee});if(e.error!==void 0)return{ok:!1,output:e.error.message};let n=`${e.stderr??""}
|
|
2
2
|
${e.stdout??""}`.trim();return{ok:e.status===0,output:n}};import z from"node:fs";import Ue from"node:os";import C from"node:path";var Se=[".claude","plugins"],w=t=>{try{return JSON.parse(z.readFileSync(t,"utf-8"))}catch{return}},d=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),p=(t,e)=>{let n=t[e];return typeof n=="string"?n:null},v=(t,e=Ue.homedir())=>C.join(e,...Se,t),Pt=t=>{let e=w(v("known_marketplaces.json",t));return d(e)&&k in e},Ie=t=>d(t)?{scope:p(t,"scope"),projectPath:p(t,"projectPath"),installPath:p(t,"installPath"),version:p(t,"version")}:null,B=t=>{let e=w(v("installed_plugins.json",t));if(!d(e)||!d(e.plugins))return[];let n=e.plugins[g];return Array.isArray(n)?n.flatMap(r=>{let o=Ie(r);return o===null?[]:[o]}):[]},x=t=>{try{return z.realpathSync(t)}catch{return C.resolve(t)}},ve=(t,e)=>t.scope==="user"?!0:e===null||t.projectPath===null?!1:x(t.projectPath)===e,kt=(t={})=>{let e=B(t.home);if(e.length===0)return{kind:"absent"};let n=t.projectPath===void 0?null:x(t.projectPath),r=e.find(o=>ve(o,n));return r===void 0?{kind:"elsewhere",installations:e}:{kind:"installed",installation:r}},W=t=>{let e=new Set;return B(t).filter(n=>{if(n.scope==="user"||n.projectPath===null)return!1;let r=x(n.projectPath);return e.has(r)?!1:(e.add(r),!0)})},Ct=t=>{if(t.installPath===null)return t.version;let e=w(C.join(t.installPath,".claude-plugin","plugin.json"));return(d(e)?p(e,"version"):null)??t.version},[xe=k]=g.split("@"),wt=({home:t}={})=>{let e=v(C.join("marketplaces",k,"plugins",xe,".claude-plugin","plugin.json"),t),n=w(e);return d(n)?p(n,"version"):null};var _e=300*1e3,be=6e4,Ae=t=>{let e=M(t);return delete e.CLAUDECODE,e},Me=t=>t.code==="ENOENT",Le=(t,e)=>{let n=t.projectPath;if(n===null||!e.pathExists(n))return"skipped";let r=e.deadlineMs-e.clock();if(r<=0)return"failed";let o=e.spawn(I,[...$],{cwd:n,stdio:"ignore",shell:q.platform==="win32",env:e.env,timeout:Math.min(be,r),windowsHide:!0});return o.error?Me(o.error)?"skipped":"failed":o.signal===null&&o.status===0?"ok":"failed"},je=t=>{let e=t.clock??Date.now,n=e()+_e;if(!(t.runClaude??H)({args:K}).ok)return"claude-missing";let o=(t.listPluginInstallations??W)();if(o.length===0)return"skipped";let s={spawn:t.spawnPluginUpdate??Re,env:Ae(t.env??q.env),clock:e,deadlineMs:n,pathExists:t.pathExists??Ne.existsSync},i=o.map(l=>Le(l,s));return i.includes("failed")?"failed":i.includes("ok")?"updated":"skipped"},Y=(t={})=>{try{return je(t)}catch{return"failed"}};var Te=200,De=300*1e3,Oe=15e3,Ve=t=>{let e=Q(P,["version","--json"],{stdio:["ignore","pipe","ignore"],shell:y.platform==="win32",cwd:X(),env:t,timeout:Oe,windowsHide:!0,encoding:"utf8"});if(e.error||e.signal||e.status!==0)return null;try{let r=JSON.parse(e.stdout)?.version;return typeof r=="string"&&r!==""?r:null}catch{return null}},Ge=t=>{try{return y.kill(t,0),!0}catch{return!1}},Fe=t=>new Promise(e=>{setTimeout(e,t)}),Je=async(t,e)=>{let n=e.clock()+De;for(;e.clock()<n;){if(!e.isProcessAlive(t))return!0;await e.sleep(Te)}return!e.isProcessAlive(t)},Vt=async(t,e)=>{let n=e.acquireLock??T,r=e.writeCache??S,o=n();if(!o)return"already-running";let s={last:null},i=l=>{s.last=l,r(l)};try{let l=await He(t,{...e,writeCache:i});return $e(e,s.last,t,r),l}finally{o()}},Ke=(t,e)=>t!==null&&U(t,e),$e=(t,e,n,r)=>{let o=Ke(e?.latestVersion??null,n)?"skipped-cli-stale":Y(t),s=(t.clock??Date.now)();if(e!==null)try{r({...e,plugin:{outcome:o,checkedMs:s}})}catch{}},He=async(t,e)=>{let n=e.env??y.env,r=e.nowMs??Date.now(),o=e.fetchLatest??D,s=e.writeCache??S,i=e.isProcessAlive??Ge,l=e.sleep??Fe,h=e.clock??Date.now,Z=e.lazyNpmRoot??b,ee=e.spawnSync??Q,te=e.installedVersion??Ve,a=await o(n),c=(R,re)=>(s({lastCheckMs:r,...re,outcome:R}),R);if(a===null)return c("fetch-failed",{latestVersion:null,updateCommand:null});if(!U(a,t))return c("up-to-date",{latestVersion:a,updateCommand:null});let{canSelfSpawn:ne,updateCommand:m}=_({selfRealPath:e.selfRealPath,env:n,realpath:A,lazyNpmRoot:Z,version:a});if(!ne)return c("cannot-self-spawn",{latestVersion:a,updateCommand:m});if(e.parentPid==null)return c("parent-unknown",{latestVersion:a,updateCommand:null});if(s({lastCheckMs:r,latestVersion:a,updateCommand:null,outcome:"installing"}),!await Je(e.parentPid,{isProcessAlive:i,sleep:l,clock:h}))return c("parent-still-running",{latestVersion:a,updateCommand:null});let E=ee(m[0],m.slice(1),{stdio:"ignore",shell:y.platform==="win32",cwd:X(),env:L(n),windowsHide:!0});return E.error||E.signal||E.status!==0?c("install-failed",{latestVersion:a,updateCommand:m}):te(n)!==a?c("install-stale",{latestVersion:a,updateCommand:m}):c("installed",{latestVersion:null,updateCommand:null})};export{k as a,g as b,at as c,I as d,K as e,$ as f,H as g,Pt as h,kt as i,Ct as j,wt as k,U as l,st as m,it as n,D as o,Vt as p,Ke as q};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-MH37P7W4.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{a as x,e as ne,h as S,i as se,j as p}from"./chunk-4RZM53X7.js";import{P as c,S as oe,d,da as b,e as _,f as re,ga as m,h as D,i as te,w as P}from"./chunk-EZ4DIT5A.js";import{a as Z,c as U,d as T,f as G,g as H,h as B,i as Y,j as Q,o as X,p as K,q as ee}from"./chunk-I23MDR4X.js";import He from"@inquirer/select";import{readRepoIdentity as Be}from"@slip-stream-kit/config/internal";import{Buffer as Ye}from"node:buffer";import Qe from"node:fs";import J from"node:path";import $ from"node:process";import{z as k}from"zod";import{$ as I}from"zx";var _e="Could not find requested project",De="Could not find requested config",ie="Invalid Auth token",ae="does not have access to requested config",A=e=>e.includes(ie)||e.includes(ae)?"auth":e.includes(_e)?"project":e.includes(De)?"config":"unknown",R=e=>e.includes(ae)?"mis-scoped":e.includes(ie)?"revoked":null;var ce=e=>[`Doppler rejected the service token for env "${e}" \u2014 it is invalid, revoked, or scoped to a different config.`,`Fix: run \`infra-kit env-token-set ${e}\` with a token scoped to that config.`,"CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config."].join(`
|
|
2
|
+
`),f=class extends S{authKind;constructor(r,t=null,o){super(o??ce(r),r),this.name="DopplerAuthError",this.authKind=t}};var L=({kind:e,project:r,config:t,available:o})=>{let n=e==="project"?[`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${t}" not found in project "${r}".`];if(o&&o.length>0){let s=e==="project"?"Available projects":`Available configs in "${r}"`;n.push(`${s}: ${o.join(", ")}.`)}return n.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: pass an existing config, or create it in Doppler."),n.join(`
|
|
3
|
+
`)};import{$ as N}from"zx";var be=5e3,xe="DOPPLER_CONFIG",g=async()=>{let{envManagement:e}=await b();return e.config.name},Se=async({childEnv:e,project:r,config:t})=>{let o=N.quiet;N.quiet=!0;try{let s=(await N({env:e})`doppler secrets get ${xe} --plain --project ${r} --config ${t}`.timeout(be)).stdout.trim();return s!==t?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(n){return{outcome:Ne(n)}}finally{N.quiet=o}},Ne=e=>{let r=D(e)??(e instanceof Error?e.message:String(e));return A(r)!=="auth"?"unreachable":R(r)??"unreachable"};import Oe from"node:process";var l="INFRA_KIT_ENV_TOKEN",C=async e=>{let r=Oe.env[l];if(r)return{token:r,source:"env"};let o=(await p())?.envs[e];if(o)return{token:o,source:"store"};throw new S(je(e,await se()),e)},je=(e,r)=>[`No Doppler service token for env "${e}".`,`Mint one at https://dashboard.doppler.com \u2014 this project \u2192 config "${e}" \u2192 Access tab \u2192 "Generate Service Token".`,`Fix: run \`infra-kit env-token-set ${e}\` and paste it.`,`It is stored in ${oe(r)} (mode 0600, never in the repo).`,`CI / agents: set ${l} instead \u2014 it takes precedence and needs no home config.`].join(`
|
|
4
|
+
`);import Ee from"node:process";import{z as ve}from"zod";import ze from"node:process";import{z as u}from"zod";var le=["prod"],v={allowed:!1,reason:"disallow"},h=e=>le.includes(e),Fe=["dev","stage"],Ie=e=>Fe.includes(e)||h(e),$e=(e,r=v)=>r.allowed?e:e.filter(t=>!h(t)),Ke=(e,r,t=v)=>{if(!t.allowed&&h(e))throw t.reason==="agent-blocked"?new m({status:"refused",env:e,agentMode:d.source},2,{operation:r,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e}" is withheld from agents in this project (protectedEnvs: "cli-only")`}):new te(void 0,{operation:r,remediation:`use \`infra-kit release deliver\` \u2014 it merges the release to main, opens the RC PR, deploys from main, and releases the Jira version. To allow ad-hoc deploys to "${e}" in this project, set \`protectedEnvs\` to "allow" or "cli-only" in infra-kit.json`,stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})};var Le=async()=>{let e;try{e=(await b()).protectedEnvs??"disallow"}catch{return v}return e==="disallow"?v:e==="cli-only"&&_()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var Ce=e=>{let{env:r,branch:t}=e;h(r)&&c.warn([`\u26A0\uFE0F "${r}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${t}" ships ${r} from a ref that is not merged to main, and skips:`," \u2022 the squash-merge of the release branch into main"," \u2022 the RC pull request"," \u2022 the Jira fix-version release","Run `infra-kit release deliver` instead if you want those."].join(`
|
|
5
|
+
`))};import pe from"node:fs/promises";import M from"node:path";import Me from"yaml";var ue=".github/workflows",Ve=async e=>{let r=await P();return de(M.resolve(r,ue,e))},V=async()=>{let e=await P(),r=M.resolve(e,ue),t;try{t=await pe.readdir(r)}catch{return[]}let o=t.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),n=await Promise.all(o.map(s=>de(M.resolve(r,s))));return[...new Set(n.flat())]},de=async e=>{let r;try{r=Me.parse(await pe.readFile(e,"utf-8"))}catch{return[]}let t=E(r,"on")??E(r,"true"),o=E(E(E(E(t,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(o)?o.filter(n=>typeof n=="string"&&n.length>0):[]},E=(e,r)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[r]};var w=async()=>{let e=await V(),r=await p(),t=e.map(s=>({env:s,source:"gh-workflow"})),o=new Set(e),n=Object.keys(r?.envs??{}).filter(s=>!o.has(s)).sort().map(s=>({env:s,source:"token-only"}));return[...t,...n]},z=async()=>(await w()).map(r=>r.env);var O=e=>[{type:"text",text:e}],j=e=>e;var F=(e,r,t)=>e.map(({env:o,source:n})=>({env:o,source:n,hasToken:!!(t||r[o])})),me=["Environment","Source","Token"],qe=e=>{let r=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),t=me.map((s,i)=>Math.max(s.length,...r.map(a=>(a[i]??"").length))),o=s=>s.map((i,a)=>i.padEnd(t[a]??0)).join(" | ").trimEnd(),n=t.map(s=>"\u2500".repeat(s)).join("\u2500\u253C\u2500");return["Environments:","",o(me),n,...r.map(o)]},ge=async()=>{let e=await g(),r=await w(),t=await p(),o=ze.env[l],n=F(r,t?.envs??{},o);if(c.info(`Doppler project: ${e}
|
|
6
|
+
`),n.length===0)return c.info("No environments found."),c.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),c.info(" or add a token for one manually."),fe({project:e,envs:n});for(let s of qe(n))c.info(s);return fe({project:e,envs:n})},fe=({project:e,envs:r})=>{let t={project:e,configs:r.map(o=>o.env),tokens:r};return{content:O(JSON.stringify(t,null,2)),structuredContent:t}},Je=j({name:"env-list",description:"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.",inputSchema:{},outputSchema:{project:u.string().describe("Detected Doppler project name"),configs:u.array(u.string()).describe("Every environment name known to this project"),tokens:u.array(u.object({env:u.string().describe("Environment / Doppler config name"),source:u.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:u.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:ge});var he=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),We=async e=>{try{return await e}catch{return[]}},Ze=async e=>{let r=await p().catch(()=>null);return F(e,r?.envs??{},Ee.env[l]).filter(t=>!t.hasToken).map(t=>t.env)},q=()=>({get message(){return`Choose the environment to load into terminal session ${Ee.env[T]??`UNKNOWN \u2014 ${T} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>he(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await We(w());if(e.length===0)return c.info({msg:"Tool execution form options empty: env-load"}),null;let r=e.map(o=>o.env),t=await Ze(e);return ve.object({config:ve.enum(r).describe(`The environment to load. ${t.length===0?"A service token is stored for every one of them.":`NO stored token for: ${t.join(", ")} \u2014 choosing one of those fails until you run \`infra-kit env-token-set <env>\`.`} The list is what env-list knows: workflow-declared environments first, then token-only ones.`)})},toArgs:(e,r)=>{let{config:t}=e;return typeof t!="string"||t.length===0?null:{...he(r)?r:{},config:t}}});import{z as Ue}from"zod";var Ge=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(r){return c.debug({err:r,operation:e.operation},"argument form builder threw; refusing without choices"),null}},we=async e=>{if(!re()||!e.provider.isFormable(e.params))return;let r=await Ge(e),t=typeof e.params=="object"&&e.params!==null?e.params:{},o=(r===null?[]:Object.keys(r.shape)).filter(i=>t[i]===void 0||t[i]===""),n=typeof e.argument=="string"?e.argument:e.argument(o),s=r===null?void 0:Ue.toJSONSchema(r);throw new m({status:"argument_required",argument:n,...s===void 0?{}:{choices:s},agentMode:d.source},2,{operation:e.operation,remediation:s===void 0?`pass --${n} on the re-run \u2014 nothing could be listed to choose from`:`ask the human to pick from "choices", then pass --${n} on the re-run`,stderrExcerpt:`--${n} was not given and there is no human to ask`})};var Xe="DOPPLER_CONFIG",ke=new Set(["DOPPLER_TOKEN",l]),ye=!1,er=e=>{e.length===0||ye||(ye=!0,c.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},rr=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:n})=>{let s=e.filter(([i])=>!ke.has(i));return er(e.filter(([i])=>ke.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${y(a)}`),`${G}=${y(r)}`,`${H}=${y(r)}`,`${B}=${y(t)}`,`${Y}=${y(o)}`,`${Q}=${y(n)}`,"set +a"]},tr=async()=>{try{return await P()}catch{return""}},or=(e,r=$.cwd())=>{if(e==="")return[J.resolve(r)];let t=Be(e).root??e;return[...new Set([t,`${t}${ee}`,e])]},nr=async({config:e})=>{let r=await g(),t=await tr(),o=await Ae(r,e),n=new Date().toISOString(),i=`${rr({pairs:o,config:e,project:r,projectRoot:t,loadedAt:n}).join(`
|
|
7
|
+
`)}
|
|
8
|
+
`,a=X(),W=J.resolve(a,Z);Qe.mkdirSync(a,{recursive:!0,mode:448});let Re=or(t);return K(J.resolve(a,U),`${Re.join(`
|
|
9
|
+
`)}
|
|
10
|
+
`,384),K(W,i,384),{filePath:W,variableCount:o.length,project:r,config:e}},Pe=q(),sr=async e=>{let{config:r}=e;await we({provider:Pe,params:e,operation:"env-load",argument:"config"});let t="";if(r)t=r;else{if(_())throw new m({status:"argument_required",argument:"config",agentMode:d.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let s=await z();x.setInteractive(),t=await ne(i=>He({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:$.stderr,whenHeadless:"refuse"})}x.addOption("--config",t);let o=await nr({config:t});x.print();let n={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config,sessionId:$.env[T]??null};return{content:O(JSON.stringify(n,null,2)),structuredContent:n}},Te=1024*1024,ir=3e4,ar=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],cr=(e,r=$.env)=>{let t={...r};for(let o of ar)delete t[o];return t.DOPPLER_TOKEN=e,t},eo=async e=>new Map(await Ae(await g(),e)),Ae=async(e,r)=>{let{token:t}=await C(r),o=cr(t),n=I.quiet;I.quiet=!0;try{let s;try{s=await I({env:o})`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(ir)}catch(a){throw pr(a,e,r)}ur(s.stdout);let i=mr(s.stdout);return lr(i,r),i}finally{I.quiet=n}},lr=(e,r)=>{let t=e.find(([o])=>o===Xe)?.[1];if(!(t===void 0||t===r))throw new f(r,null,`Doppler returned secrets for config "${t}" but "${r}" was requested \u2014 the service token for env "${r}" is scoped to the wrong config. Refusing to load another environment's secrets.
|
|
11
|
+
Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},pr=(e,r,t)=>{let o=D(e)??(e instanceof Error?e.message:String(e)),n=A(o);return n==="auth"?new f(t,R(o)):n==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(L({kind:n,project:r,config:t,available:null}))},ur=e=>{let r=Ye.byteLength(e,"utf-8");if(r>Te)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Te}) \u2014 refusing to write to disk`)},y=e=>`'${e.replaceAll("'","'\\''")}'`,dr=/^[A-Z_]\w*$/i,mr=e=>{let r;try{r=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let t=[];for(let[o,n]of Object.entries(r)){if(!dr.test(o))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(o.slice(0,80))})`);if(typeof n!="string")throw new TypeError(`doppler returned a non-string value for "${o}" (got ${typeof n})`);t.push([o,n])}if(t.length===0)throw new Error("doppler returned empty output for env-load");return t},ro=j({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit "config" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess.',inputSchema:{config:k.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:Pe,outputSchema:{filePath:k.string().describe("Path to the file that must be sourced to apply variables"),variableCount:k.number().describe("Number of variables loaded"),project:k.string().describe("Doppler project name"),config:k.string().describe("Doppler config name"),sessionId:k.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:sr});export{O as a,j as b,A as c,R as d,g as e,Se as f,l as g,C as h,h as i,Ie as j,$e as k,Ke as l,Le as m,Ce as n,Ve as o,w as p,z as q,ge as r,Je as s,we as t,rr as u,or as v,nr as w,sr as x,Te as y,cr as z,eo as A,lr as B,pr as C,ur as D,y as E,mr as F,ro as G};
|
|
12
|
+
//# sourceMappingURL=chunk-PP3ZZKB3.js.map
|