infra-kit 0.1.134 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{boot-YCABHUPP.js → boot-MTVHM4N7.js} +2 -2
- package/dist/{chunk-TFHVQOVF.js → chunk-4MRYIYJP.js} +2 -2
- package/dist/chunk-E2NWNNC6.js +2 -0
- package/dist/chunk-E2NWNNC6.js.map +7 -0
- package/dist/{chunk-3OMHS5RE.js → chunk-E2SEBLGJ.js} +2 -2
- package/dist/chunk-KZP2SY37.js +4 -0
- package/dist/chunk-KZP2SY37.js.map +7 -0
- package/dist/{chunk-27PDA2PN.js → chunk-NC2TIQ3M.js} +2 -2
- package/dist/chunk-RLZ5IB2E.js +238 -0
- package/dist/chunk-RLZ5IB2E.js.map +7 -0
- package/dist/chunk-TI33V5G2.js +6 -0
- package/dist/chunk-TI33V5G2.js.map +7 -0
- package/dist/{chunk-FAR2L74S.js → chunk-TPVXMJ7N.js} +1 -1
- package/dist/cli.js +10 -8
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +23 -20
- package/dist/dev-server.js.map +4 -4
- package/dist/dev-wizard-run-5HQOGE3R.js +2 -0
- package/dist/dev-wizard-run-5HQOGE3R.js.map +7 -0
- package/dist/mcp.js +1 -1
- package/dist/mcp.js.map +3 -3
- package/dist/persistent-ink-dev-ui-KOI44ZVT.js +2 -0
- package/dist/persistent-ink-dev-ui-KOI44ZVT.js.map +7 -0
- package/dist/safe-stderr-HXDR2DNJ.js +2 -0
- package/dist/update-check.js +1 -1
- package/package.json +3 -14
- package/dist/chunk-2YHPK2VY.js +0 -221
- package/dist/chunk-2YHPK2VY.js.map +0 -7
- package/dist/chunk-3F7XYJWY.js +0 -3
- package/dist/chunk-3F7XYJWY.js.map +0 -7
- package/dist/chunk-DOG3OPNW.js +0 -2
- package/dist/chunk-DOG3OPNW.js.map +0 -7
- package/dist/chunk-JD5T4VCB.js +0 -6
- package/dist/chunk-JD5T4VCB.js.map +0 -7
- package/dist/chunk-LTKR3F4N.js +0 -2
- package/dist/chunk-LTKR3F4N.js.map +0 -7
- package/dist/chunk-TUVUKM4K.js +0 -2
- package/dist/chunk-TUVUKM4K.js.map +0 -7
- package/dist/chunk-Z6KTUVIC.js +0 -2
- package/dist/chunk-Z6KTUVIC.js.map +0 -7
- package/dist/dev-wizard-run-HGQO6FZV.js +0 -2
- package/dist/dev-wizard-run-HGQO6FZV.js.map +0 -7
- package/dist/entry/index.d.ts +0 -4
- package/dist/entry/vite.d.ts +0 -2
- package/dist/index.js +0 -2
- package/dist/lib/package-config/package-config-schema.d.ts +0 -35
- package/dist/lib/package-config/package-config.d.ts +0 -99
- package/dist/lib/release-slug/release-slug.d.ts +0 -43
- package/dist/lib/vendor/config-schema.d.ts +0 -58
- package/dist/lib/vite/vite.d.ts +0 -168
- package/dist/persistent-ink-dev-ui-FUJQDFNY.js +0 -8
- package/dist/persistent-ink-dev-ui-FUJQDFNY.js.map +0 -7
- package/dist/vite.js +0 -2
- package/dist/vite.js.map +0 -7
- /package/dist/{boot-YCABHUPP.js.map → boot-MTVHM4N7.js.map} +0 -0
- /package/dist/{chunk-TFHVQOVF.js.map → chunk-4MRYIYJP.js.map} +0 -0
- /package/dist/{chunk-3OMHS5RE.js.map → chunk-E2SEBLGJ.js.map} +0 -0
- /package/dist/{chunk-27PDA2PN.js.map → chunk-NC2TIQ3M.js.map} +0 -0
- /package/dist/{chunk-FAR2L74S.js.map → chunk-TPVXMJ7N.js.map} +0 -0
- /package/dist/{index.js.map → safe-stderr-HXDR2DNJ.js.map} +0 -0
package/dist/chunk-3F7XYJWY.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import _ from"node:process";import C from"pino";import te from"pino-pretty";var T="/tmp/mcp-infra-kit.log",Pt=()=>{let e=_.argv.includes("--debug")?"debug":"info",t=C({level:e},C.destination({dest:T}));return t.info(`Logger initialized with level: ${e}. Logging to: ${T}`),t},re=()=>{let e=_.argv.includes("--debug")?"debug":"info",t=["time","pid","hostname"];return e==="debug"&&t.push("level"),C({level:e},te({destination:2,ignore:t.join(","),colorize:!0}))},kt=re();import*as p from"node:fs";import*as a from"node:path";function ne(e){let t=e;for(let r=0;r<10;r++){let n=a.join(t,"pnpm-workspace.yaml");if(p.existsSync(n))return t;t=a.dirname(t)}throw new Error("Could not find monorepo root (pnpm-workspace.yaml)")}function O(e,t){let r=a.join(e,"package.json");if(!p.existsSync(r))return t;try{let n=JSON.parse(p.readFileSync(r,"utf-8"));return typeof n.name=="string"?n.name:t}catch{return t}}function Rt(e){let t=a.join(e,"apps"),r=[];if(!p.existsSync(t))throw new Error(`Apps directory not found: ${t}`);let n=p.readdirSync(t,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name);for(let s of n){let i=a.join(t,s,"api"),c=a.join(i,"serverless.yml");p.existsSync(c)&&r.push({name:s,packageName:O(i,s),path:i})}return r}var se=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs"];function oe(e){for(let t of se){let r=a.join(e,t);if(p.existsSync(r))try{return p.readFileSync(r,"utf-8").includes("infra-kit/vite")}catch{return!1}}return!1}function ie(e){let t=a.join(e,"package.json");if(!p.existsSync(t))return!1;try{let r=JSON.parse(p.readFileSync(t,"utf-8"));return typeof r.scripts?.dev=="string"&&r.scripts.dev.length>0}catch{return!1}}function bt(e){let t=a.join(e,"apps"),r=[];if(!p.existsSync(t))return r;let n=p.readdirSync(t,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name);for(let s of n){let i=a.join(t,s,"ui");p.existsSync(i)&&ie(i)&&r.push({name:s,packageName:O(i,s),path:i,managedPort:oe(i)})}return r}function Ct(e){let t=e?.filter(Boolean)??[];return t.length>0?t:null}function St(e){let t=ne(e),r=a.relative(a.join(t,"apps"),e),n=r.split(a.sep)[0];if(r===""||r.startsWith("..")||a.isAbsolute(r)||!n)throw new Error(`--self: not inside an apps/<app> directory (cwd: ${e}). Run from an app folder or use --app=<name>.`);return n}var ae=new Set(["api","ui"]),K=e=>{let t=a.join(e,"dist");return p.existsSync(t)&&p.statSync(t).isDirectory()?t:void 0},S=e=>p.existsSync(e)?p.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name):[];function It(e){let t=[];for(let n of S(a.join(e,"packages"))){let s=K(a.join(e,"packages",n));s!==void 0&&t.push(s)}let r=a.join(e,"apps");for(let n of S(r))for(let s of S(a.join(r,n))){if(ae.has(s))continue;let i=a.join(r,n,s);if(!p.existsSync(a.join(i,"package.json")))continue;let c=K(i);c!==void 0&&t.push(c)}return t}function Dt(e){return e.map(t=>a.join(t.path,"dist")).filter(t=>p.existsSync(t))}function jt(e,t,r){let n=a.normalize(e),s=r.find(c=>n.startsWith(a.normalize(c)));return s?{kind:"package",packageDir:s}:{kind:"app",app:t.find(c=>n.startsWith(a.normalize(c)))}}var ce={"*/api":{},"*/ui":{}},F=e=>{let t=e.split("/"),[r,n]=t;return t.length!==2||!r?`devServersPresets: invalid target "${e}" (expected "<app>/api" or "<app>/ui")`:n!=="api"&&n!=="ui"?`devServersPresets: invalid target part "${n}" in "${e}" (expected "api" or "ui")`:null},pe=e=>{let t=F(e);if(t)throw new Error(t);let[r,n]=e.split("/");return{appGlob:r,part:n}},Et=e=>{let t=[];for(let[r,n]of Object.entries(e))for(let s of Object.keys(n.apps??{})){let i=F(s);i&&t.push({preset:r,key:s,message:`preset "${r}": ${i}`})}return t},le=(e,t)=>t==="api"?e.api:e.ui,ue=e=>[...new Set([...e.api,...e.ui])].sort(),M=(e,t)=>`${e}/${t}`,fe=e=>e?0:1,ge=(e,t)=>t.watchDeps===void 0?e??{watchDeps:!0,rank:t.rank,explicitValue:!1}:!e||!e.explicitValue?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:t.rank>e.rank?{watchDeps:t.watchDeps,rank:t.rank,explicitValue:!0}:e,de=(e,t,r)=>{let{app:n,part:s,watchDeps:i,isGlob:c}=r;if(!le(t,s).includes(n)){c||e.unmatched.push(M(n,s));return}let l=M(n,s),u=ge(e.targets.get(l),{watchDeps:i,rank:fe(c)});e.targets.set(l,{app:n,part:s,...u})},me=(e,t)=>{let r=Object.entries(e.apps??ce),n={targets:new Map,proxy:{},unmatched:[]};for(let[c,l]of r){let{appGlob:u,part:h}=pe(c),k=u==="*",w=k?ue(t):[u];for(let b of w)de(n,t,{app:b,part:h,watchDeps:l.watchDeps,isGlob:k}),l.proxy&&(n.proxy[b]={...n.proxy[b]??{},...l.proxy})}let s=[...n.targets.values()].map(({app:c,part:l,watchDeps:u})=>({app:c,part:l,watchDeps:u})),i=[...new Set(s.filter(c=>c.part==="api").map(c=>c.app))];return{targets:s,cmux:e.cmux??!1,proxy:n.proxy,localApps:i,unmatched:n.unmatched}},$t=e=>{if(e.preset!=null)return e.preset;if(e.running.length===0)return"nothing";let t=new Set(e.running);return e.discovered.every(n=>t.has(n))?"*":[...t].sort().join(" + ")},he=(e,t)=>Object.keys(e).find(r=>e[r]===t),ve=({preset:e,app:t,route:r,launchedPkgs:n,ctx:s})=>{let i=s.routePkg(t,r);if(i===void 0)return{preset:e,app:t,route:r,kind:"unknown-route",message:`preset "${e}": proxy override "${r}" on "${t}" names a route not declared in ${t}'s infra-kit.config.ts dev.proxy.routes`};if(n.has(i))return null;let c=he(s.apiPkgByApp,i),l=c?`add "${c}/api" to the preset`:`launch the api whose package is "${i}"`;return{preset:e,app:t,route:r,pkg:i,kind:"backend-not-launched",message:`preset "${e}": proxy override "${r}" \u2192 "local" requires backend "${i}" to run locally, but the preset does not launch it \u2014 ${l}, or set "${r}" to "cloud"`}},Nt=(e,t)=>{let r=[];for(let[n,s]of Object.entries(e)){let i=me(s,t.discovered),c=new Set(i.localApps.map(l=>t.apiPkgByApp[l]).filter(l=>l!==void 0));for(let[l,u]of Object.entries(i.proxy))for(let[h,k]of Object.entries(u)){if(k!=="local")continue;let w=ve({preset:n,app:l,route:h,launchedPkgs:c,ctx:t});w&&r.push(w)}}return r};import N from"node:fs/promises";import J from"node:os";import x from"node:path";import Ke from"node:process";import{z as o}from"zod";import d from"node:path";import{$ as f}from"zx";var ye=/^v?(\d+)\.(\d+)\.(\d+)$/,xe=/^(\d+)\.(\d+)\.(\d+)$/,Pe=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,R="release/",I="release/v",B="refs/heads/",ke="next";var G=new Set(["dev","main","next","hotfix","regular","release"]),g=class extends Error{constructor(t){super(t),this.name="InvalidReleaseNameError"}},v=class extends Error{constructor(t){super(t),this.name="InvalidReleaseRefError"}},W=e=>e.startsWith(B)?e.slice(B.length):e,U=(e,t,r)=>({kind:"version",semver:{major:e,minor:t,patch:r},raw:`${e}.${t}.${r}`}),D=e=>{if(e.length===0)throw new g('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new g(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!Pe.test(e))throw new g(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(G.has(e))throw new g(`Release name "${e}" is reserved. Reserved names: ${[...G].join(", ")}.`)},j=e=>{let t=W(e.trim());if(!t.startsWith(R))return null;if(t.startsWith(I)){let n=t.slice(I.length),s=xe.exec(n);if(s)return U(Number(s[1]),Number(s[2]),Number(s[3]))}let r=t.slice(R.length);try{D(r)}catch{return null}return{kind:"name",name:r,raw:r}},we=e=>{let t=e.trim();if(W(t).startsWith(R)){let s=j(t);if(!s)throw new v(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return s}let n=ye.exec(t);if(n)return U(Number(n[1]),Number(n[2]),Number(n[3]));if(t.toLowerCase()===ke)throw new v('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{D(t)}catch(s){let i=s instanceof Error?s.message:String(s);throw new v(`Cannot parse "${e}" as a release ref: ${i}`)}return{kind:"name",name:t,raw:t}},Re=e=>e.kind==="version"?`${I}${e.raw}`:`${R}${e.name}`,be=(e,t)=>{let r=t==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${r} v${e.raw}`:`${r} ${e.name}`},Ce=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,Se=e=>e.kind==="version"?`v${e.raw}`:e.name,Ie=e=>e.raw,A=e=>e==null?!1:j(e)!==null,z=e=>{if(e===void 0)return null;let t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(t)?null:t},De=(e,t,r)=>{if(e.kind==="version"&&t.kind==="version")return e.semver.major!==t.semver.major?e.semver.major-t.semver.major:e.semver.minor!==t.semver.minor?e.semver.minor-t.semver.minor:e.semver.patch-t.semver.patch;if(e.kind==="version")return-1;if(t.kind==="version")return 1;let n=z(r?.a),s=z(r?.b);return n!==null&&s!==null&&n!==s?n-s:e.name<t.name?-1:e.name>t.name?1:0};var je=async e=>{let r=(await f`git worktree list`).stdout.split(`
|
|
2
|
-
`).filter(Boolean),n={release:Ae,feature:Ee};return r.map(n[e]).filter(s=>s!==null)},V=e=>{let t=e.trimEnd();if(!t.endsWith("]"))return null;let r=t.lastIndexOf("[");if(r===-1)return null;let n=t.slice(r+1,-1);return n.length>0?n:null},Ae=e=>{let t=V(e);return A(t)?t:null},Ee=e=>{let t=V(e);return t?.startsWith("feature/")?t:null},y=async()=>(await f`git rev-parse --show-toplevel`).stdout.trim(),E=async e=>{let t=e??await y(),r=(await f({cwd:t})`git rev-parse --git-common-dir`).stdout.trim(),n=d.resolve(t,r);return n.includes(`${d.sep}.git${d.sep}modules${d.sep}`)?t:d.dirname(n)},H=async()=>(await f`git rev-parse --abbrev-ref HEAD`).stdout.trim(),$e=async()=>(await f`git status --porcelain`).stdout.trim().length===0,Ne=async()=>{let e=await y(),[t,r]=await Promise.all([f({cwd:e})`git rev-parse --absolute-git-dir`,f({cwd:e})`git rev-parse --git-common-dir`]),n=t.stdout.trim(),s=d.resolve(e,r.stdout.trim());return n!==s},Le=async()=>{let e=await y();return d.basename(e)},Te=async e=>{(await f`git branch --list ${e}`).stdout.trim().length!==0&&await H()!==e&&await f`git branch -D ${e}`},_e=async e=>{(await f`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await f`git push origin --delete ${e}`};var X="infra-kit.json",Y=".infra-kit",Oe="infra-kit.json",Me="projects",Fe=o.object({provider:o.literal("doppler"),config:o.object({name:o.string().min(1)})}),Be=o.discriminatedUnion("provider",[Fe]),Ge=o.object({workspaceConfigPath:o.string().min(1)}),ze=o.object({provider:o.literal("cursor"),config:Ge}),We=o.object({}),Ue=o.object({provider:o.literal("zed"),config:We}),q=o.discriminatedUnion("provider",[ze,Ue]),Ve=o.union([q,o.array(q).min(1)]),He=o.object({provider:o.literal("jira"),config:o.object({baseUrl:o.string().url(),projectId:o.number().int().positive()})}),Xe=o.discriminatedUnion("provider",[He]),qe=["two-columns","three-pane"],Je=o.object({layout:o.enum(qe).optional()}),Ye=o.object({openInGithubDesktop:o.boolean().optional(),openInCmux:o.boolean().optional(),cmux:Je.optional()}),Qe=o.object({port:o.number().int().positive().optional(),prefixUrl:o.string().min(1).optional()}).strict(),Ze=o.record(o.string().min(1),Qe),et=o.enum(["local","cloud"]),tt=o.object({watchDeps:o.boolean().optional(),proxy:o.record(o.string().min(1),et).optional()}).strict(),rt=o.object({apps:o.record(o.string().min(1),tt).optional(),cmux:o.boolean().optional()}).strict(),nt=o.record(o.string().min(1),rt),st=o.object({port:o.number().int().positive().optional()}).strict(),ot=o.object({trigger:o.enum(["shell-startup","cli-invocation"]),config:o.string().min(1)}).strict(),L=o.object({environments:o.array(o.string().min(1)).min(1),envManagement:Be,ide:Ve.optional(),taskManager:Xe.optional(),worktrees:Ye.optional(),envAutoLoad:ot.optional(),dev:Ze.optional(),devServersPresets:nt.optional(),devProxy:st.optional()}).strict(),it=443,Q=L.superRefine((e,t)=>{if(!Array.isArray(e.ide))return;let r=new Set;for(let n of e.ide){if(r.has(n.provider)){t.addIssue({code:"custom",message:"each IDE provider may appear at most once",path:["ide"]});return}r.add(n.provider)}}),Z=L.partial(),at=e=>{let t=e.ide;return t?Array.isArray(t)?t:[t]:[]},ct="two-columns",pt=e=>e.worktrees?.cmux?.layout??ct,m=null,P=null,lt=()=>`${Ke.cwd()} ${J.homedir()}`,ee=async()=>{let e=lt();if(P&&P.key===e)return P.value;let t=await y(),r=await E(t),n=x.basename(r),s=x.join(J.homedir(),Y),i={main:x.join(t,X),userGlobal:x.join(s,Oe),userProject:x.join(s,Me,n,X),projectName:n};return P={key:e,value:i},i},ut=async()=>{let e=await ee(),t;try{t=await N.stat(e.main)}catch{m=null;let u=e.main.replace(/\.json$/,".yml");throw await $(u)?new Error(`infra-kit.json not found at ${e.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit init\` to convert it.`):new Error(`infra-kit.json not found at ${e.main}`)}let[r,n]=await Promise.all([$(e.userGlobal),$(e.userProject)]),s={main:Number(t.mtimeMs),userGlobal:r?Number(r.mtimeMs):null,userProject:n?Number(n.mtimeMs):null};if(m&&mt(m.mtimes,s))return m.value;let i=[{label:"infra-kit.json",path:e.main,required:!0},{label:"~/.infra-kit/infra-kit.json",path:e.userGlobal,required:!1},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,path:e.userProject,required:!1}],c={};for(let u of i){let h=await ht(u);h!==null&&(c={...c,...h})}let l=Q.safeParse(c);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${o.prettifyError(l.error)}`);return m={mtimes:s,value:l.data},l.data},ft=()=>{m=null},gt=()=>{m=null,P=null},$=async e=>{try{return await N.stat(e)}catch{return null}},dt=async e=>{try{return await N.readFile(e,"utf-8")}catch{return null}},mt=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(n=>e[n]===t[n])},ht=async e=>{let t=await dt(e.path);if(t===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${s.message}`)}let n=Z.safeParse(r);if(!n.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${o.prettifyError(n.error)}`);return n.data};export{g as a,D as b,j as c,we as d,Re as e,be as f,Ce as g,Se as h,Ie as i,A as j,De as k,je as l,y as m,H as n,$e as o,Ne as p,Le as q,Te as r,_e as s,T as t,Pt as u,kt as v,ne as w,Rt as x,bt as y,Ct as z,St as A,It as B,Dt as C,jt as D,F as E,Et as F,me as G,$t as H,Nt as I,Y as J,it as K,Q as L,Z as M,at as N,pt as O,ee as P,ut as Q,ft as R,gt as S};
|
|
3
|
-
//# sourceMappingURL=chunk-3F7XYJWY.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/logger/index.ts", "../src/dev/discovery.ts", "../src/dev/presets.ts", "../src/lib/infra-kit-config/infra-kit-config.ts", "../src/lib/git-utils/git-utils.ts", "../src/lib/release-id/release-id.ts"],
|
|
4
|
-
"sourcesContent": ["import process from 'node:process'\nimport pino from 'pino'\nimport pretty from 'pino-pretty'\n\n// eslint-disable-next-line sonarjs/publicly-writable-directories\nexport const LOG_FILE_PATH = '/tmp/mcp-infra-kit.log'\n\nexport const initLoggerMcp = () => {\n const logLevel = process.argv.includes('--debug') ? 'debug' : 'info'\n\n const logger = pino({ level: logLevel }, pino.destination({ dest: LOG_FILE_PATH }))\n\n logger.info(`Logger initialized with level: ${logLevel}. Logging to: ${LOG_FILE_PATH}`)\n\n return logger\n}\n\nexport const initLoggerCLI = () => {\n const logLevel = process.argv.includes('--debug') ? 'debug' : 'info'\n\n const ignoreFields = ['time', 'pid', 'hostname']\n\n if (logLevel === 'debug') {\n ignoreFields.push('level')\n }\n\n const logger = pino(\n { level: logLevel },\n pretty({\n destination: 2,\n ignore: ignoreFields.join(','),\n colorize: true,\n }),\n )\n\n return logger\n}\n\n// Singleton logger instance for CLI usage\nexport const logger = initLoggerCLI()\n", "/**\n * Filesystem discovery helpers for the dev-server.\n *\n * These functions read the filesystem (walking for the monorepo root, scanning\n * `apps/` and `packages/`) but never `chdir` and never resolve ports / prefixes \u2014\n * that stays with the pure {@link file://./ports.ts} layer. The starting directory\n * is passed in so discovery is testable against a fixture root.\n */\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\n/** Bare metadata for a discovered API app (no resolved port / prefix). */\nexport interface DiscoveredApiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** Package name from package.json (e.g. sls-trvl-client), or the folder name as fallback. */\n packageName: string\n path: string\n}\n\n/** Walk up from `startDir` (max 10 levels) to the dir containing `pnpm-workspace.yaml`. */\nexport function findMonorepoRoot(startDir: string): string {\n let currentDir = startDir\n\n for (let i = 0; i < 10; i++) {\n const workspaceFile = path.join(currentDir, 'pnpm-workspace.yaml')\n\n if (fs.existsSync(workspaceFile)) {\n return currentDir\n }\n currentDir = path.dirname(currentDir)\n }\n\n throw new Error('Could not find monorepo root (pnpm-workspace.yaml)')\n}\n\n/** Read the `name` field from `<apiPath>/package.json`, falling back to `appName`. */\nexport function getPackageName(apiPath: string, appName: string): string {\n const pkgPath = path.join(apiPath, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return appName\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { name?: string }\n\n return typeof pkg.name === 'string' ? pkg.name : appName\n } catch {\n return appName\n }\n}\n\n/** Discover every `apps/<app>` that has an `api/serverless.yml` (bare metadata only). */\nexport function discoverApiApps(root: string): DiscoveredApiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredApiApp[] = []\n\n if (!fs.existsSync(appsDir)) {\n throw new Error(`Apps directory not found: ${appsDir}`)\n }\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const apiPath = path.join(appsDir, appName, 'api')\n const serverlessPath = path.join(apiPath, 'serverless.yml')\n\n if (fs.existsSync(serverlessPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(apiPath, appName),\n path: apiPath,\n })\n }\n }\n\n return apps\n}\n\n/** Bare metadata for a discovered UI app (a frontend with its own framework `dev` script). */\nexport interface DiscoveredUiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** package.json `name` \u2014 used as the exact `turbo run dev --filter` target. */\n packageName: string\n /** Absolute path to `apps/<app>/ui`. */\n path: string\n /**\n * True when this UI's vite config wires `infra-kit/vite`'s `infraKitDev()` helper \u2014 the ONLY thing\n * that makes it honor the runner-assigned `INFRA_KIT_UI_PORTS` port (which it binds with `strictPort`).\n *\n * The runner treats frameworks opaquely, so it cannot assume a pre-assigned port is the port the child\n * will bind. Without this signal it would print a confident, wrong URL for any UI that picks its own\n * port (vike, astro, a hand-rolled vite config). Unwired \u2192 the runner claims no port and the UI keeps\n * its honest \"vite prints its URL below\" reference line.\n */\n managedPort: boolean\n}\n\n/** Vite config filenames checked for the `infra-kit/vite` import, in vite's own resolution order. */\nconst VITE_CONFIG_FILES = [\n 'vite.config.ts',\n 'vite.config.mts',\n 'vite.config.cts',\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.cjs',\n]\n\n/**\n * True when `<dir>`'s vite config references the `infra-kit/vite` helper module. A text match, not a\n * module load: the config is TypeScript the runner must not execute, and importing it would run the\n * consumer's own side effects. False negatives (a config that re-exports the helper from a shared\n * preset) cost only the reference line, never a wrong URL \u2014 the safe direction to be wrong in.\n */\nexport function usesInfraKitVite(dir: string): boolean {\n for (const file of VITE_CONFIG_FILES) {\n const configPath = path.join(dir, file)\n\n if (!fs.existsSync(configPath)) continue\n\n try {\n return fs.readFileSync(configPath, 'utf-8').includes('infra-kit/vite')\n } catch {\n return false\n }\n }\n\n return false\n}\n\n/** True when `<dir>/package.json` declares a non-empty `scripts.dev`. */\nfunction hasDevScript(dir: string): boolean {\n const pkgPath = path.join(dir, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return false\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { scripts?: Record<string, string> }\n\n return typeof pkg.scripts?.dev === 'string' && pkg.scripts.dev.length > 0\n } catch {\n return false\n }\n}\n\n/**\n * Discover every `apps/<app>/ui` whose package.json declares a `dev` script \u2014 the frontends\n * `infra-kit dev --ui` runs (via one delegated `turbo run dev`). Lenient: no `apps/` dir \u2192 `[]`\n * (UIs are optional), unlike {@link discoverApiApps} which requires it.\n */\nexport function discoverUiApps(root: string): DiscoveredUiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredUiApp[] = []\n\n if (!fs.existsSync(appsDir)) return apps\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const uiPath = path.join(appsDir, appName, 'ui')\n\n if (fs.existsSync(uiPath) && hasDevScript(uiPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(uiPath, appName),\n path: uiPath,\n managedPort: usesInfraKitVite(uiPath),\n })\n }\n }\n\n return apps\n}\n\n/** Normalize the `--app` include list: drop empties, and collapse an empty list to `null`. */\nexport function normalizeAppInclude(include?: string[] | null): string[] | null {\n const filtered = include?.filter(Boolean) ?? []\n\n return filtered.length > 0 ? filtered : null\n}\n\n/**\n * Infer the current app's folder name from `startDir`, so a per-app script can\n * run `infra-kit dev --self` without hardcoding its own app name. Walks up to the\n * monorepo root (via {@link findMonorepoRoot}), then takes the first path segment\n * of `startDir` relative to `<root>/apps` \u2014 e.g. `apps/config-handler/api` and\n * `apps/config-handler` both resolve to `config-handler`. Throws when `startDir`\n * isn't inside `<root>/apps/<app>/...` (repo root, or an unrelated path).\n *\n * @example\n * resolveSelfAppName('/repo/apps/config-handler/api') // => 'config-handler'\n */\nexport function resolveSelfAppName(startDir: string): string {\n const root = findMonorepoRoot(startDir)\n const relative = path.relative(path.join(root, 'apps'), startDir)\n const firstSegment = relative.split(path.sep)[0]\n const isOutsideApps = relative === '' || relative.startsWith('..') || path.isAbsolute(relative)\n\n if (isOutsideApps || !firstSegment) {\n throw new Error(\n `--self: not inside an apps/<app> directory (cwd: ${startDir}). Run from an app folder or use --app=<name>.`,\n )\n }\n\n return firstSegment\n}\n\n/** App-part directory names that are apps in their own right, never shared packages. See {@link getPackageDistDirs}. */\nconst APP_PART_DIRS = new Set(['api', 'ui'])\n\n/** `<dir>/dist` when it exists and is a directory, else `undefined`. */\nconst existingDistDir = (dir: string): string | undefined => {\n const distDir = path.join(dir, 'dist')\n\n return fs.existsSync(distDir) && fs.statSync(distDir).isDirectory() ? distDir : undefined\n}\n\n/** Immediate subdirectory names of `dir`, or `[]` when `dir` does not exist. */\nconst subdirNames = (dir: string): string[] => {\n if (!fs.existsSync(dir)) return []\n\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .filter((d) => {\n return d.isDirectory()\n })\n .map((d) => {\n return d.name\n })\n}\n\n/**\n * Existing dist directories of every SHARED workspace package \u2014 the compiled outputs `turbo watch`\n * rewrites. Watched (alongside app dist) because editing a shared lib rewrites only the lib's `dist`,\n * never the dependent app's, so a package-dist change is the only signal that a lib was rebuilt.\n *\n * Two homes, because the pnpm workspace globs cover `packages/<pkg>` as well as `apps/<app>/<part>`:\n * - `packages/<pkg>/dist` \u2014 the obvious one.\n * - `apps/<app>/<part>/dist` where `<part>` is neither `api` nor `ui` and the dir is a real workspace\n * member (it has a `package.json`). A shared library may legally live beside the app that owns it \u2014\n * hulyo's `@pkg/ai-mcp` is `apps/ai/mcp`, and two backends depend on it. Scanning only `packages`\n * left such a package watched by nobody: turbo rebuilt its dist, the runner never saw the change, and\n * every dependent backend kept serving stale code.\n *\n * `api`/`ui` parts are excluded deliberately: an api's dist is already covered by {@link getAppDistDirs},\n * and treating a frontend's dist as a shared package would bounce every backend on a UI rebuild.\n */\nexport function getPackageDistDirs(root: string): string[] {\n const dirs: string[] = []\n\n for (const name of subdirNames(path.join(root, 'packages'))) {\n const distDir = existingDistDir(path.join(root, 'packages', name))\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n\n const appsDir = path.join(root, 'apps')\n\n for (const app of subdirNames(appsDir)) {\n for (const part of subdirNames(path.join(appsDir, app))) {\n if (APP_PART_DIRS.has(part)) continue\n\n const partDir = path.join(appsDir, app, part)\n\n // A workspace member, not a stray build artifact directory.\n if (!fs.existsSync(path.join(partDir, 'package.json'))) continue\n\n const distDir = existingDistDir(partDir)\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n }\n\n return dirs\n}\n\n/** Existing `<app.path>/dist` directories for the given apps (order preserved). */\nexport function getAppDistDirs(apps: Array<{ path: string }>): string[] {\n return apps\n .map((app) => {\n return path.join(app.path, 'dist')\n })\n .filter((dir) => {\n return fs.existsSync(dir)\n })\n}\n\n/** How a watched dist change should be routed. */\nexport interface ChangeClassification {\n kind: 'app' | 'package'\n /** For app changes: the matched app dist dir (undefined when nothing matched). */\n app?: string\n /** For package changes: the matched `packages/<pkg>/dist` dir (the change identity used to scope restarts). */\n packageDir?: string\n}\n\n/**\n * Route a changed compiled-output path: a `packages/<pkg>/dist` change is a shared-package\n * rebuild \u2014 the matched package dist dir is returned so the caller can restart only the apps\n * whose dependency closure includes it. An `<app>/dist` change restarts only that app (the\n * matched app dist dir is returned; `undefined` when the path matches neither). Package matches\n * take precedence.\n */\nexport function classifyDistChange(\n changedPath: string,\n appDistDirs: string[],\n packageDistDirs: string[],\n): ChangeClassification {\n const normalized = path.normalize(changedPath)\n\n const matchedPackageDir = packageDistDirs.find((dir) => {\n return normalized.startsWith(path.normalize(dir))\n })\n\n if (matchedPackageDir) {\n return { kind: 'package', packageDir: matchedPackageDir }\n }\n\n const matchedDir = appDistDirs.find((dir) => {\n return normalized.startsWith(path.normalize(dir))\n })\n\n return { kind: 'app', app: matchedDir }\n}\n", "/**\n * Pure resolution of a named dev preset into a concrete run plan.\n *\n * A preset (declared under `devServersPresets` in the per-project infra-kit.json) names\n * launch targets (`client/api`, `client/ui`, with `*` allowed in the app position), optional\n * per-target `watchDeps` (api + ui), per-route proxy-source overrides, and a `cmux` layout\n * flag. This module turns that declarative shape into a flat {@link ResolvedPreset}\n * the runner consumes. Side-effect free: the discovered app parts are passed in\n * (never read from disk here), so resolution is fully unit-testable.\n *\n * Every target key names exactly one workspace package \u2014 the app folder plus the part\n * (`apps/<app>/api` or `apps/<app>/ui`). A bare `<app>` is not a package and is rejected.\n */\nimport type { DevPreset, DevPresets, ProxySource } from 'src/lib/infra-kit-config'\n\n/** The two launchable halves of an `apps/<app>` folder. */\nexport type AppPart = 'api' | 'ui'\n\n/** One concrete thing to launch: a single part of a single app. */\nexport interface ResolvedTarget {\n /** App folder name (e.g. `client`). */\n app: string\n /** Which half of the app to launch. */\n part: AppPart\n /**\n * Participate in dependency-closure watching (uniform for api + ui): react to a change in\n * this target's own workspace-dependency closure. Default `true` (opt-in participation).\n * Resolution is specificity-ordered: an explicit value on a more-specific key (a concrete\n * app, or an explicit `/part`) wins over a `*` glob; at equal specificity an explicit\n * `false` wins over `true` (order-independent opt-out). See {@link resolveWatch}.\n */\n watchDeps: boolean\n}\n\n/** Which apps have an `api` / `ui` part on disk \u2014 the resolver's view of discovery. */\nexport interface DiscoveredParts {\n /** App names that have `apps/<app>/api`. */\n api: string[]\n /** App names that have `apps/<app>/ui`. */\n ui: string[]\n}\n\n/** A fully-resolved preset: the flat run plan derived from its declarative shape. */\nexport interface ResolvedPreset {\n /** Every (app, part) to launch, de-duplicated. */\n targets: ResolvedTarget[]\n /** Run each target in its own cmux pane. */\n cmux: boolean\n /** app \u2192 (route path \u2192 source) overrides, threaded to the proxy resolver. */\n proxy: Record<string, Record<string, ProxySource>>\n /** Apps whose `api` part is launched \u2014 their backends are local (derived). */\n localApps: string[]\n /** Concretely-named `<app>/<part>` targets that matched no discovered app/part (for a warning). */\n unmatched: string[]\n}\n\n/** The target keys resolution falls back to when a preset omits `apps`: every discovered package. */\nconst ALL_TARGETS_KEYS: NonNullable<DevPreset['apps']> = { '*/api': {}, '*/ui': {} }\n\n/** A preset target key that does not name an `<app>/<part>` package. */\nexport interface PresetKeyIssue {\n /** Preset name the bad key is under. */\n preset: string\n /** The offending key, verbatim. */\n key: string\n /** Human-readable, actionable explanation (already prefixed with the preset name). */\n message: string\n}\n\ninterface ParsedKey {\n /** App name or `*` (all discovered apps). */\n appGlob: string\n /** The single part the key selects. */\n part: AppPart\n}\n\n/**\n * Explain why `key` is not a valid target, or null when it parses. Keys name one workspace\n * package, so the `/api`|`/ui` part is mandatory \u2014 a bare `client` names a folder, not a package.\n */\nexport const explainTargetKey = (key: string): string | null => {\n const segments = key.split('/')\n const [appGlob, part] = segments\n\n if (segments.length !== 2 || !appGlob) {\n return `devServersPresets: invalid target \"${key}\" (expected \"<app>/api\" or \"<app>/ui\")`\n }\n\n if (part !== 'api' && part !== 'ui') {\n return `devServersPresets: invalid target part \"${part}\" in \"${key}\" (expected \"api\" or \"ui\")`\n }\n\n return null\n}\n\n/**\n * Parse a preset target key into an app glob + its part. Throws when the key is not an\n * `<app>/<part>` package identity (see {@link explainTargetKey}).\n *\n * A `*` app glob is legal (`*` plus a part), and expands to every discovered app.\n *\n * @example\n * parseTargetKey('client/api') // => { appGlob: 'client', part: 'api' }\n */\nexport const parseTargetKey = (key: string): ParsedKey => {\n const error = explainTargetKey(key)\n\n if (error) {\n throw new Error(error)\n }\n\n const [appGlob, part] = key.split('/') as [string, AppPart]\n\n return { appGlob, part }\n}\n\n/** Every `preset \u2192 invalid target key` in the map, with the reason (empty when all keys parse). */\nexport const validatePresetKeys = (presets: DevPresets): PresetKeyIssue[] => {\n const issues: PresetKeyIssue[] = []\n\n for (const [preset, def] of Object.entries(presets)) {\n for (const key of Object.keys(def.apps ?? {})) {\n const error = explainTargetKey(key)\n\n if (error) {\n issues.push({ preset, key, message: `preset \"${preset}\": ${error}` })\n }\n }\n }\n\n return issues\n}\n\n/** App names that have `part` on disk, per the discovery result. */\nconst appsWithPart = (discovered: DiscoveredParts, part: AppPart): string[] => {\n return part === 'api' ? discovered.api : discovered.ui\n}\n\n/** Every discovered app name (union of api + ui halves), sorted for deterministic output. */\nconst allApps = (discovered: DiscoveredParts): string[] => {\n return [...new Set([...discovered.api, ...discovered.ui])].sort()\n}\n\n/** Stable `app/part` identity key for de-duplicating targets across preset keys. */\nconst targetId = (app: string, part: AppPart): string => {\n return `${app}/${part}`\n}\n\n/** A resolved target plus the provenance the merge needs to order later keys by specificity. */\ninterface ResolvedTargetInternal extends ResolvedTarget {\n /** Specificity rank of the key that set `watchDeps` (see {@link keyRank}) \u2014 a higher rank wins. */\n rank: number\n /** Whether `watchDeps` came from an explicit preset value (vs the participate-default). */\n explicitValue: boolean\n}\n\ninterface ResolveState {\n targets: Map<string, ResolvedTargetInternal>\n proxy: Record<string, Record<string, ProxySource>>\n unmatched: string[]\n}\n\n/**\n * Specificity rank of a preset key, higher = more specific. Every key names a part, so the\n * only axis left is the app: a concrete `client/api` (1) beats a `*` glob key (0).\n */\nconst keyRank = (isGlob: boolean): number => {\n return isGlob ? 0 : 1\n}\n\n/**\n * Merge a preset key's `watchDeps` into any prior resolution for the same target. A key that\n * omits `watchDeps` never clobbers a prior explicit value (and, absent any explicit value,\n * seeds the participate-default `true`). A more-specific key ({@link keyRank}) wins in either\n * direction, so a `*` glob cannot override a concrete `client/api` and vice-versa. Two explicit\n * keys can never tie: each target is named by at most one key per rank (one glob, one concrete),\n * so the merge is order-independent.\n */\nconst resolveWatch = (\n prior: ResolvedTargetInternal | undefined,\n next: { watchDeps: boolean | undefined; rank: number },\n): { watchDeps: boolean; rank: number; explicitValue: boolean } => {\n // This key configured nothing \u2192 keep the prior resolution, or seed the participate-default.\n if (next.watchDeps === undefined) {\n return prior ?? { watchDeps: true, rank: next.rank, explicitValue: false }\n }\n\n // No prior explicit value (fresh, or only a default) \u2192 this explicit value takes it.\n if (!prior || !prior.explicitValue) {\n return { watchDeps: next.watchDeps, rank: next.rank, explicitValue: true }\n }\n\n // Two explicit values: the more-specific key wins, in either direction.\n return next.rank > prior.rank ? { watchDeps: next.watchDeps, rank: next.rank, explicitValue: true } : prior\n}\n\n/**\n * Fold one (app, part) into the accumulator: record a target when the part exists,\n * merge `watchDeps` with any prior target of the same identity by specificity\n * ({@link resolveWatch}), and flag a named-but-missing package as unmatched\n * (glob-expanded misses are silent).\n */\nconst addTarget = (\n state: ResolveState,\n discovered: DiscoveredParts,\n spec: { app: string; part: AppPart; watchDeps: boolean | undefined; isGlob: boolean },\n): void => {\n const { app, part, watchDeps, isGlob } = spec\n\n if (!appsWithPart(discovered, part).includes(app)) {\n // A glob expands over discovery, so its misses are expected; a concretely-named\n // `<app>/<part>` that can't be found is a mistake worth surfacing.\n if (!isGlob) {\n state.unmatched.push(targetId(app, part))\n }\n\n return\n }\n\n const id = targetId(app, part)\n const merged = resolveWatch(state.targets.get(id), { watchDeps, rank: keyRank(isGlob) })\n\n state.targets.set(id, { app, part, ...merged })\n}\n\n/**\n * Resolve a preset against the discovered app parts. Expands `*` app globs,\n * de-duplicates targets, derives the local-backend set from the launched `api`\n * targets, and collects per-app proxy overrides. Unknown app/route names are\n * tolerated (a missing named target lands in `unmatched`, not an exception) so a\n * stale preset degrades gracefully \u2014 but a key that is not an `<app>/<part>`\n * package identity throws, since it can't be resolved at all.\n *\n * @example\n * resolvePreset(\n * { apps: { 'client/ui': {}, 'client/api': { watchDeps: false } } },\n * { api: ['client'], ui: ['client'] },\n * )\n * // => {\n * // targets: [{ app: 'client', part: 'ui', watchDeps: true }, // default participate\n * // { app: 'client', part: 'api', watchDeps: false }], // explicit opt-out\n * // cmux: false, proxy: {}, localApps: ['client'], unmatched: [],\n * // }\n */\nexport const resolvePreset = (preset: DevPreset, discovered: DiscoveredParts): ResolvedPreset => {\n const entries = Object.entries(preset.apps ?? ALL_TARGETS_KEYS)\n const state: ResolveState = { targets: new Map(), proxy: {}, unmatched: [] }\n\n for (const [key, cfg] of entries) {\n const { appGlob, part } = parseTargetKey(key)\n const isGlob = appGlob === '*'\n const apps = isGlob ? allApps(discovered) : [appGlob]\n\n for (const app of apps) {\n addTarget(state, discovered, { app, part, watchDeps: cfg.watchDeps, isGlob })\n\n if (cfg.proxy) {\n state.proxy[app] = { ...(state.proxy[app] ?? {}), ...cfg.proxy }\n }\n }\n }\n\n const targets: ResolvedTarget[] = [...state.targets.values()].map(({ app, part, watchDeps }) => {\n return { app, part, watchDeps }\n })\n const localApps = [\n ...new Set(\n targets\n .filter((t) => {\n return t.part === 'api'\n })\n .map((t) => {\n return t.app\n }),\n ),\n ]\n\n return { targets, cmux: preset.cmux ?? false, proxy: state.proxy, localApps, unmatched: state.unmatched }\n}\n\n/** What the run launched, as passed to {@link deriveTargetLabel}. */\nexport interface TargetLabelInput {\n /** Named preset (`infra-kit dev <preset>`) \u2014 its name is the label when present. */\n preset?: string\n /** The `<app>/<part>` package keys actually being launched, after preset resolution and `--app`. */\n running: string[]\n /** Every `<app>/<part>` package key discovered in the monorepo. */\n discovered: string[]\n}\n\n/**\n * The header's target label. A named preset labels itself; otherwise the label is the set of\n * `<app>/<part>` packages actually launching, collapsing to `*` when that set is everything\n * discovered. Never a bare app name: `client` is not a target anywhere in this system (see\n * {@link parseTargetKey}) and would hide which half of the app is running \u2014 the whole point of\n * the wizard's part-level selection.\n *\n * @example\n * deriveTargetLabel({ running: ['client/ui', 'client/api'], discovered: ['client/api', 'client/ui', 'seo/ui'] })\n * // => 'client/api + client/ui'\n * deriveTargetLabel({ running: ['client/api'], discovered: ['client/api'] }) // => '*'\n * deriveTargetLabel({ preset: 'full', running: ['client/api'], discovered: ['client/api', 'seo/ui'] }) // => 'full'\n */\nexport const deriveTargetLabel = (input: TargetLabelInput): string => {\n if (input.preset != null) {\n return input.preset\n }\n if (input.running.length === 0) {\n return 'nothing'\n }\n\n const running = new Set(input.running)\n const isEverything = input.discovered.every((key) => {\n return running.has(key)\n })\n\n return isEverything ? '*' : [...running].sort().join(' + ')\n}\n\n/** A devServersPresets proxy-locality violation surfaced by the audit. */\nexport interface PresetProxyIssue {\n /** Preset name the violation is in. */\n preset: string\n /** Frontend app folder the override is under (e.g. `client`). */\n app: string\n /** Route path forced to a source (e.g. `/api`). */\n route: string\n /** Backend pkg the route maps to; undefined when the route is not declared in the frontend config. */\n pkg?: string\n /** `unknown-route` = route absent from the frontend config; `backend-not-launched` = local target not launched. */\n kind: 'unknown-route' | 'backend-not-launched'\n /** Human-readable, actionable explanation. */\n message: string\n}\n\n/**\n * Cross-file lookups the proxy validator needs, kept injectable so the rule stays\n * filesystem-free (and unit-testable). The impure side (audit) builds these from\n * discovery + each frontend's loaded `infra-kit.config.ts`.\n */\nexport interface PresetProxyContext {\n /** Discovered app parts, for resolving each preset's launch set. */\n discovered: DiscoveredParts\n /** App folder name \u2192 its `apps/<app>/api` package name. */\n apiPkgByApp: Record<string, string>\n /** (frontend app folder, route path) \u2192 backend pkg from that frontend's config; undefined when the route is absent. */\n routePkg: (app: string, route: string) => string | undefined\n}\n\ninterface CheckLocalRouteArgs {\n preset: string\n app: string\n route: string\n launchedPkgs: ReadonlySet<string>\n ctx: PresetProxyContext\n}\n\n/** App folder whose `api` package is `pkg` (for the remediation hint), or undefined. */\nconst ownerApp = (apiPkgByApp: Record<string, string>, pkg: string): string | undefined => {\n return Object.keys(apiPkgByApp).find((app) => {\n return apiPkgByApp[app] === pkg\n })\n}\n\n/**\n * Validate one `route \u2192 'local'` override: the route must be declared in the\n * frontend config, and the backend pkg it maps to must be in the preset's launched\n * set. Returns the issue, or null when the override is satisfiable.\n */\nconst checkLocalRoute = ({ preset, app, route, launchedPkgs, ctx }: CheckLocalRouteArgs): PresetProxyIssue | null => {\n const pkg = ctx.routePkg(app, route)\n\n if (pkg === undefined) {\n return {\n preset,\n app,\n route,\n kind: 'unknown-route',\n message: `preset \"${preset}\": proxy override \"${route}\" on \"${app}\" names a route not declared in ${app}'s infra-kit.config.ts dev.proxy.routes`,\n }\n }\n\n if (launchedPkgs.has(pkg)) {\n return null\n }\n\n const owner = ownerApp(ctx.apiPkgByApp, pkg)\n const hint = owner ? `add \"${owner}/api\" to the preset` : `launch the api whose package is \"${pkg}\"`\n\n return {\n preset,\n app,\n route,\n pkg,\n kind: 'backend-not-launched',\n message: `preset \"${preset}\": proxy override \"${route}\" \u2192 \"local\" requires backend \"${pkg}\" to run locally, but the preset does not launch it \u2014 ${hint}, or set \"${route}\" to \"cloud\"`,\n }\n}\n\n/**\n * Audit every preset's per-route proxy overrides: a route pinned to `local` is only\n * valid when the backend package it resolves to (per the frontend's\n * `infra-kit.config.ts`) is actually launched by that same preset. Catches the\n * `{ \"client/ui\": { \"proxy\": { \"/api\": \"local\" } } }` case where no local backend\n * is running to serve `/api`. `cloud` overrides are always satisfiable and skipped.\n *\n * @example\n * validatePresetProxy(\n * { 'client-remote': { apps: { 'client/ui': { proxy: { '/api': 'local' } } } } },\n * { discovered: { api: ['client'], ui: ['client'] }, apiPkgByApp: { client: 'backend-api' },\n * routePkg: () => 'backend-api' },\n * )\n * // => [{ preset: 'client-remote', app: 'client', route: '/api', pkg: 'backend-api',\n * // kind: 'backend-not-launched', message: '\u2026' }]\n */\nexport const validatePresetProxy = (presets: DevPresets, ctx: PresetProxyContext): PresetProxyIssue[] => {\n const issues: PresetProxyIssue[] = []\n\n for (const [preset, def] of Object.entries(presets)) {\n const resolved = resolvePreset(def, ctx.discovered)\n const launchedPkgs = new Set(\n resolved.localApps\n .map((app) => {\n return ctx.apiPkgByApp[app]\n })\n .filter((pkg): pkg is string => {\n return pkg !== undefined\n }),\n )\n\n for (const [app, routes] of Object.entries(resolved.proxy)) {\n for (const [route, source] of Object.entries(routes)) {\n if (source !== 'local') {\n continue\n }\n\n const issue = checkLocalRoute({ preset, app, route, launchedPkgs, ctx })\n\n if (issue) {\n issues.push(issue)\n }\n }\n }\n }\n\n return issues\n}\n", "import fs from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { z } from 'zod'\n\nimport { getMainRepoRoot, getProjectRoot } from 'src/lib/git-utils'\n\nconst INFRA_KIT_CONFIG_FILE = 'infra-kit.json'\n\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, and the factory\n * registry (`vendor.json`). Single source of truth for `.infra-kit`, reused\n * by the vendor factory-config loader (no import cycle \u2014 this module imports no\n * `lib/vendor` code).\n */\nexport const USER_CONFIG_DIR_NAME = '.infra-kit'\nconst USER_GLOBAL_CONFIG_FILE = 'infra-kit.json'\nconst USER_PROJECTS_DIR = 'projects'\n\n// envManagement\nconst dopplerEnvManagementSchema = z.object({\n provider: z.literal('doppler'),\n config: z.object({\n name: z.string().min(1),\n }),\n})\n\nconst envManagementSchema = z.discriminatedUnion('provider', [dopplerEnvManagementSchema])\n\n// ide\n// There is one attach style: each worktree is added to the configured editor's\n// workspace and opened (no per-window mode). Cursor needs a `.code-workspace`\n// path to reconcile its `folders` array against.\nconst cursorIdeConfigSchema = z.object({\n workspaceConfigPath: z.string().min(1),\n})\n\nconst cursorIdeSchema = z.object({\n provider: z.literal('cursor'),\n config: cursorIdeConfigSchema,\n})\n\n// Zed has no portable workspace file (no `.code-workspace`) and no folder-remove\n// CLI: a multi-worktree workspace is realized by a single `zed <root> <wt...>`\n// invocation. So `config` carries no settings \u2014 there's no path to point at.\nconst zedIdeConfigSchema = z.object({})\n\nconst zedIdeSchema = z.object({\n provider: z.literal('zed'),\n config: zedIdeConfigSchema,\n})\n\nconst ideSchema = z.discriminatedUnion('provider', [cursorIdeSchema, zedIdeSchema])\n\n// `ide` accepts a single provider (back-compat) OR an array to drive multiple\n// editors at once (e.g. Cursor + Zed). Normalized to an array everywhere via\n// `resolveConfiguredIdes`. Uniqueness-by-provider is enforced at parse time by a\n// `.superRefine` on the full config schema (see below) \u2014 not here, so the message\n// survives `z.union` error aggregation.\nconst idesSchema = z.union([ideSchema, z.array(ideSchema).min(1)])\n\n// taskManager\nconst jiraTaskManagerSchema = z.object({\n provider: z.literal('jira'),\n config: z.object({\n baseUrl: z.string().url(),\n projectId: z.number().int().positive(),\n }),\n})\n\nconst taskManagerSchema = z.discriminatedUnion('provider', [jiraTaskManagerSchema])\n\n// cmux pane layout for opened worktree workspaces. Named presets keep the config\n// typo-proof (an enum, not a free string) and let the opener switch on a single\n// value; extend the enum + the opener's switch to add a layout.\n// two-columns \u2014 left | right, both full-height (default)\n// three-pane \u2014 left split top/bottom + full-height right (legacy layout)\nconst cmuxLayouts = ['two-columns', 'three-pane'] as const\n\nconst cmuxConfigSchema = z.object({\n layout: z.enum(cmuxLayouts).optional(),\n})\n\n// worktrees prompt defaults\nconst worktreesConfigSchema = z.object({\n openInGithubDesktop: z.boolean().optional(),\n openInCmux: z.boolean().optional(),\n cmux: cmuxConfigSchema.optional(),\n})\n\n// dev-server per-app overrides. Maps an app folder name (e.g. `client`) to its\n// local dev port and/or URL prefix. Both keys optional. An app absent from the\n// map falls back to env (`{APP}_PORT` / `PORT`) then the built-in defaults, so\n// the map is intentionally NOT validated against the discovered apps here \u2014 an\n// unknown app name is simply ignored at resolve time (lib/dev), never a parse\n// error that would brick every command.\nconst devAppConfigSchema = z\n .object({\n port: z.number().int().positive().optional(),\n prefixUrl: z.string().min(1).optional(),\n })\n .strict()\n\nconst devConfigSchema = z.record(z.string().min(1), devAppConfigSchema)\n\n// devServersPresets: named local-dev sessions, declared in the per-project infra-kit.json\n// (team presets committed; personal ones layered via the user-project override).\n// Each preset names launch targets (apps/<app>/{api,ui}), optional per-backend\n// `watchDeps`, per-route proxy-source overrides, and a `cmux` layout flag; it is\n// consumed by `infra-kit dev <preset>` and resolved by src/dev/presets. Each target key\n// names exactly one workspace package (`<app>/api` or `<app>/ui`) \u2014 a bare `<app>` is a\n// folder, not a package, and is rejected. The SHAPE is strict (typos in a preset surface\n// as parse errors), but unknown app/route NAMES are intentionally NOT validated here \u2014\n// they resolve at run time against the discovered apps, so a stale preset never bricks\n// every command.\nconst proxySourceSchema = z.enum(['local', 'cloud'])\n\nconst devPresetAppSchema = z\n .object({\n // api targets only: watch the backend's dist + shared-package subdeps and restart on change.\n watchDeps: z.boolean().optional(),\n // route path (e.g. `/api`) \u2192 source, overriding that route's config.ts default for this session.\n proxy: z.record(z.string().min(1), proxySourceSchema).optional(),\n })\n .strict()\n\nconst devPresetSchema = z\n .object({\n // Launch-target key \u2014 one package: `client/ui`, `client/api`, `*/api`. Omit `apps` = all.\n apps: z.record(z.string().min(1), devPresetAppSchema).optional(),\n // Run each launched target in its own cmux pane (one workspace, N panes).\n cmux: z.boolean().optional(),\n })\n .strict()\n\nconst devPresetsSchema = z.record(z.string().min(1), devPresetSchema)\n\n// DEPRECATED (accepted and ignored). Layer-B local-dev proxy (portless).\n//\n// The proxy port is no longer negotiable: every dev URL is `https://<release>.<packageName>.localhost`\n// with NO port, and the only port that can serve a port-free HTTPS URL is 443. A configurable port would\n// put the port straight back into the URL \u2014 the exact thing this design removes.\n//\n// The key is still PARSED so it does not brick anything: `infraKitConfigObject` is `.strict()` and\n// `getInfraKitConfig` THROWS on an unknown key, so simply deleting it would hard-fail EVERY infra-kit\n// command (not just `dev`) on any machine whose config still carries it \u2014 arriving unannounced, because\n// the CLI self-updates. It is read by nothing and silently ignored. Remove one release from now.\nconst devProxyConfigSchema = z\n .object({\n port: z.number().int().positive().optional(),\n })\n .strict()\n\n// env auto-load: opt-in convenience that primes Doppler env when you work inside\n// this project / a worktree. Absent => disabled. `trigger` selects the moment\n// (pick one):\n// shell-startup \u2014 when a new shell opens inside the project\n// cli-invocation \u2014 before each `infra-kit` command (primes SUBSEQUENT commands)\n// `config` names which environment to load. It is intentionally NOT validated\n// against `environments` here: an invalid name must DISABLE the feature at\n// resolve time (lib/env-autoload), never throw inside the merged-config parse and\n// brick every command.\nconst envAutoLoadSchema = z\n .object({\n trigger: z.enum(['shell-startup', 'cli-invocation']),\n config: z.string().min(1),\n })\n .strict()\n\n// Base object shape, kept separate so `.partial()` (which only works on a plain\n// ZodObject, not the `.superRefine`-wrapped full schema) can derive the override\n// schema from it.\n//\n// `.strict()` for the same reason every leaf schema below is: this is the one config file humans\n// hand-edit, and a non-strict top level silently swallows the typo that matters most. `devServersPreset`\n// (missing `s`) or `dev-proxy` would parse clean and turn the feature off with no message. The `dev` and\n// `devServersPresets` values stay open `z.record`s \u2014 app and preset NAMES are user-chosen \u2014 so strictness\n// applies to the key set, not the contents.\nexport const infraKitConfigObject = z\n .object({\n environments: z.array(z.string().min(1)).min(1),\n envManagement: envManagementSchema,\n ide: idesSchema.optional(),\n taskManager: taskManagerSchema.optional(),\n worktrees: worktreesConfigSchema.optional(),\n envAutoLoad: envAutoLoadSchema.optional(),\n dev: devConfigSchema.optional(),\n devServersPresets: devPresetsSchema.optional(),\n devProxy: devProxyConfigSchema.optional(),\n })\n .strict()\n\n/**\n * The portless proxy's listen port. `443` \u2014 the implicit HTTPS port \u2014 because that is the ONLY port that\n * can serve a port-free `https://<release>.<packageName>.localhost` URL, which is the whole point.\n *\n * It is privileged, so the daemon must already be running: `infra-kit dev` PROBES it and never elevates\n * (portless binds `:443` by re-execing through `sudo` with an inherited stdio, which a detached child can\n * never answer). One-time, out-of-band: a root `portless service install`, which `dev` and `doctor` print\n * for the user as an absolute-path command (portless is not on `PATH`; see `formatPortlessCommand`). There\n * is deliberately no unprivileged fallback \u2014 a fallback puts the port back in the URL.\n *\n * Not a constant of convenience: it is the single value that decides the scheme, and TLS on 443 is\n * portless's own default (our previous `--no-tls` was the deviation).\n */\nexport const DEFAULT_DEV_PROXY_PORT = 443\n\n// Full schema = base object + a parse-time uniqueness check on the `ide` array.\n// This runs inside the *merged* `safeParse` in getInfraKitConfig, so it's the\n// gate for the final config. (The override layers use the `.partial()` form\n// below, which drops this object-level refinement \u2014 acceptable, the merged\n// parse is authoritative.)\nexport const infraKitConfigSchema = infraKitConfigObject.superRefine((cfg, ctx) => {\n if (!Array.isArray(cfg.ide)) return\n\n const seen = new Set<string>()\n\n for (const entry of cfg.ide) {\n if (seen.has(entry.provider)) {\n ctx.addIssue({\n code: 'custom',\n message: 'each IDE provider may appear at most once',\n path: ['ide'],\n })\n\n return\n }\n\n seen.add(entry.provider)\n }\n})\n\nexport const infraKitOverrideConfigSchema = infraKitConfigObject.partial()\n\nexport type InfraKitConfig = z.infer<typeof infraKitConfigSchema>\n\n/** Resolved env auto-load config (`{ trigger, config }`), or `undefined` when off. */\nexport type EnvAutoLoadConfig = z.infer<typeof envAutoLoadSchema>\n\n/** Per-app dev-server overrides (`{ port?, prefixUrl? }`). */\nexport type DevAppConfig = z.infer<typeof devAppConfigSchema>\n\n/** The full `dev` section: a map of app folder name to its {@link DevAppConfig}. */\nexport type DevConfig = z.infer<typeof devConfigSchema>\n\n/** A proxy route's resolved source in a preset override (`'local' | 'cloud'`). */\nexport type ProxySource = z.infer<typeof proxySourceSchema>\n\n/** A single dev preset (`{ apps?, cmux? }`) from the `devServersPresets` map. */\nexport type DevPreset = z.infer<typeof devPresetSchema>\n\n/** The `devServersPresets` map: preset name \u2192 {@link DevPreset}. */\nexport type DevPresets = z.infer<typeof devPresetsSchema>\n\n/** A single resolved IDE entry (`{ provider, config }`). */\nexport type ConfiguredIde = z.infer<typeof ideSchema>\n\n/**\n * Normalize the `ide` config (single object, array, or unset) into a flat list.\n * Validation-free: assumes already-parsed input (uniqueness is enforced by the\n * schema). The one source of truth for \"which editors are configured.\"\n *\n * @example\n * resolveConfiguredIdes({ ide: { provider: 'cursor', config: {...} } }) // => [cursor]\n * resolveConfiguredIdes({ ide: [cursor, zed] }) // => [cursor, zed]\n * resolveConfiguredIdes({}) // => []\n */\nexport const resolveConfiguredIdes = (config: InfraKitConfig): ConfiguredIde[] => {\n const ide = config.ide\n\n if (!ide) return []\n\n return Array.isArray(ide) ? ide : [ide]\n}\n\n/** A cmux pane layout preset (see {@link cmuxLayouts}). */\nexport type CmuxLayout = (typeof cmuxLayouts)[number]\n\n/** The layout applied when `worktrees.cmux.layout` is left unset. */\nexport const DEFAULT_CMUX_LAYOUT: CmuxLayout = 'two-columns'\n\n/**\n * Resolve the cmux pane layout for opened worktree workspaces, falling back to\n * {@link DEFAULT_CMUX_LAYOUT} when unconfigured. The one source of truth for\n * \"which layout should the cmux opener build.\"\n *\n * @example\n * resolveCmuxLayout({ worktrees: { cmux: { layout: 'three-pane' } } }) // => 'three-pane'\n * resolveCmuxLayout({}) // => 'two-columns'\n */\nexport const resolveCmuxLayout = (config: InfraKitConfig): CmuxLayout => {\n return config.worktrees?.cmux?.layout ?? DEFAULT_CMUX_LAYOUT\n}\n\nexport interface InfraKitConfigPaths {\n /** Committed project config (required). */\n main: string\n /** User-scope global overrides applied to every project. */\n userGlobal: string\n /** User-scope per-project overrides \u2014 `<userProjectsDir>/<projectName>/infra-kit.json`. */\n userProject: string\n /** Repo basename (`path.basename(projectRoot)`) used to namespace the user-project file. */\n projectName: string\n}\n\ninterface CacheEntry {\n mtimes: Record<keyof Omit<InfraKitConfigPaths, 'projectName'>, number | null>\n value: InfraKitConfig\n}\n\nlet cached: CacheEntry | null = null\n\ninterface PathsCacheEntry {\n key: string\n value: InfraKitConfigPaths\n}\n\n/**\n * Memo slot for {@link getInfraKitConfigPaths}. SINGLE-ENTRY, not a `Map`: the resolver's only\n * inputs are `process.cwd()` and `os.homedir()`, and production never mutates either (there is zero\n * `process.chdir` outside tests), so one key covers the whole process lifetime. A `Map` would buy\n * nothing there and could hand a chdir'ing test file a stale sibling entry; a single slot that\n * recomputes on key mismatch is strictly safer and identically fast.\n */\nlet cachedPaths: PathsCacheEntry | null = null\n\n/**\n * Cache key for {@link cachedPaths}. `homedir` is load-bearing, not decoration: the resolver reads\n * it directly, and a dozen test files swap it for a fresh `mkdtemp` home WITHOUT chdir'ing \u2014 a\n * cwd-only key would hand test B test A's already-deleted temp home.\n *\n * @example\n * pathsCacheKey() // => '/Users/arthur/projects/api /Users/arthur'\n */\nconst pathsCacheKey = (): string => {\n return `${process.cwd()} ${os.homedir()}`\n}\n\n/**\n * Resolve every file path that participates in the config merge chain. Always\n * returns paths even for files that don't yet exist, so callers can use them\n * for \"where would my override go?\" prompts.\n *\n * Memoized on `cwd + homedir` (see {@link cachedPaths}) because the two `git rev-parse` spawns below\n * run BEFORE the mtime cache in `getInfraKitConfig`, so without this every call paid for both. The\n * memo is populated on success only \u2014 `getProjectRoot` rejects outside a git repo and callers depend\n * on that rejection, so a cached rejection would be a stateful negative path. Cleared by\n * {@link resetInfraKitConfigCache}.\n *\n * Safe to memoize: this is a pure path resolver (inputs = cwd + homedir; it returns paths, never\n * file contents), so filesystem mutation cannot invalidate it.\n *\n * @example\n * const paths = await getInfraKitConfigPaths()\n * // {\n * // main: '/Users/arthur/projects/api/infra-kit.json',\n * // userGlobal: '/Users/arthur/.infra-kit/infra-kit.json',\n * // userProject: '/Users/arthur/.infra-kit/projects/api/infra-kit.json',\n * // projectName: 'api',\n * // }\n */\nexport const getInfraKitConfigPaths = async (): Promise<InfraKitConfigPaths> => {\n const key = pathsCacheKey()\n\n if (cachedPaths && cachedPaths.key === key) {\n return cachedPaths.value\n }\n\n const projectRoot = await getProjectRoot()\n // Namespace the per-project override on the MAIN repo root, not `projectRoot`.\n // Inside a linked worktree `projectRoot` is the worktree's own path, so its\n // basename is the worktree's leaf dir (e.g. `feature-x`), which would key the\n // override to a different, per-worktree file. `getMainRepoRoot` resolves the\n // shared git common dir so every worktree of a repo converges on one key. The\n // second `git rev-parse` this costs is fine \u2014 the merged config is mtime-cached.\n const mainRepoRoot = await getMainRepoRoot(projectRoot)\n const projectName = path.basename(mainRepoRoot)\n const userConfigDir = path.join(os.homedir(), USER_CONFIG_DIR_NAME)\n\n const value: InfraKitConfigPaths = {\n main: path.join(projectRoot, INFRA_KIT_CONFIG_FILE),\n userGlobal: path.join(userConfigDir, USER_GLOBAL_CONFIG_FILE),\n userProject: path.join(userConfigDir, USER_PROJECTS_DIR, projectName, INFRA_KIT_CONFIG_FILE),\n projectName,\n }\n\n // Populate only after both git calls RESOLVED \u2014 never cache a rejection.\n cachedPaths = { key, value }\n\n return value\n}\n\n/**\n * Read and validate `infra-kit.json`, with optional override layers shallow-merged\n * on top in this order (later wins):\n * 1. project `infra-kit.json` \u2014 committed source of truth\n * 2. `~/.infra-kit/infra-kit.json` \u2014 user-global defaults\n * 3. `~/.infra-kit/projects/<repo-name>/infra-kit.json` \u2014 user-scope per-project overrides\n *\n * Top-level keys (entire capability sections like `ide`, `envManagement`)\n * replace wholesale. Results are cached per file mtimes so the long-running\n * MCP server picks up edits without a restart.\n *\n * @example\n * // infra-kit.json: { \"environments\": [\"dev\"], \"envManagement\": { \"provider\": \"doppler\", \"config\": { \"name\": \"p\" } } }\n * // ~/.infra-kit/infra-kit.json: { \"ide\": { \"provider\": \"cursor\", \"config\": { \"workspaceConfigPath\": \"./ws.code-workspace\" } } }\n * const cfg = await getInfraKitConfig()\n * // => { environments: ['dev'], envManagement: {...}, ide: { provider: 'cursor', config: { workspaceConfigPath: './ws.code-workspace' } } }\n */\nexport const getInfraKitConfig = async (): Promise<InfraKitConfig> => {\n const paths = await getInfraKitConfigPaths()\n\n let mainStat: Awaited<ReturnType<typeof fs.stat>>\n\n try {\n mainStat = await fs.stat(paths.main)\n } catch {\n cached = null\n\n // Bridge the YAML\u2192JSON cutover: if a legacy infra-kit.yml is sitting where\n // the JSON config should be, point the user at the one-shot migration.\n const legacyYmlPath = paths.main.replace(/\\.json$/, '.yml')\n\n if (await statIfExists(legacyYmlPath)) {\n throw new Error(\n `infra-kit.json not found at ${paths.main}. A legacy infra-kit.yml exists \u2014 run \\`infra-kit init\\` to convert it.`,\n )\n }\n\n throw new Error(`infra-kit.json not found at ${paths.main}`)\n }\n\n const [userGlobalStat, userProjectStat] = await Promise.all([\n statIfExists(paths.userGlobal),\n statIfExists(paths.userProject),\n ])\n\n const mtimes = {\n main: Number(mainStat.mtimeMs),\n userGlobal: userGlobalStat ? Number(userGlobalStat.mtimeMs) : null,\n userProject: userProjectStat ? Number(userProjectStat.mtimeMs) : null,\n }\n\n if (cached && shallowEqual(cached.mtimes, mtimes)) {\n return cached.value\n }\n\n const layers: ConfigLayer[] = [\n { label: 'infra-kit.json', path: paths.main, required: true },\n { label: '~/.infra-kit/infra-kit.json', path: paths.userGlobal, required: false },\n {\n label: `~/.infra-kit/projects/${paths.projectName}/infra-kit.json`,\n path: paths.userProject,\n required: false,\n },\n ]\n\n let merged: Record<string, unknown> = {}\n\n for (const layer of layers) {\n const data = await loadLayer(layer)\n\n if (data === null) continue\n\n merged = { ...merged, ...data }\n }\n\n const finalResult = infraKitConfigSchema.safeParse(merged)\n\n if (!finalResult.success) {\n throw new Error(`Invalid merged infra-kit config: ${z.prettifyError(finalResult.error)}`)\n }\n\n cached = { mtimes, value: finalResult.data }\n\n return finalResult.data\n}\n\n/**\n * Drop ONLY the merged-config cache ({@link cached}), keeping the path memo ({@link cachedPaths})\n * intact. For writers of a merge layer \u2014 the config bootstrap, which creates the layer-3\n * `~/.infra-kit/projects/<repo>/infra-kit.json`.\n *\n * WHY this exists separately from {@link resetInfraKitConfigCache}: writing the layer-3 file changes\n * the MERGE RESULT (a stale merged config would miss the new layer) but it cannot change the\n * RESOLVED PATHS \u2014 those are a pure function of `cwd + homedir`, and creating a file mutates\n * neither. Blowing away the path memo there would just make the very run that creates the file\n * re-spawn both `git rev-parse` processes for nothing: 4 spawns instead of 2.\n *\n * @example\n * await fs.writeFile(paths.userProject, '{}\\n', 'utf-8')\n * resetMergedConfigCache()\n * await getInfraKitConfig() // sees the new layer-3 layer\n * await getInfraKitConfigPaths() // still served from the memo \u2014 zero extra git spawns\n */\nexport const resetMergedConfigCache = (): void => {\n cached = null\n}\n\n/**\n * For tests \u2014 drops BOTH in-memory caches: the mtime-fingerprinted merged config and the\n * `cwd + homedir`-keyed path memo ({@link cachedPaths}). The next read re-spawns `git rev-parse`\n * and re-hits disk. Production writers want the narrower {@link resetMergedConfigCache}.\n *\n * @example\n * resetInfraKitConfigCache()\n * await getInfraKitConfig() // re-resolves paths and re-reads files even if mtimes look unchanged\n */\nexport const resetInfraKitConfigCache = (): void => {\n cached = null\n cachedPaths = null\n}\n\n/**\n * `fs.stat` that returns `null` instead of throwing on ENOENT. Used so the\n * resolver can probe optional files in the merge chain without try/catch noise.\n *\n * @example\n * const stat = await statIfExists('/does/not/exist') // => null\n */\nconst statIfExists = async (filePath: string): Promise<Awaited<ReturnType<typeof fs.stat>> | null> => {\n try {\n return await fs.stat(filePath)\n } catch {\n return null\n }\n}\n\n/**\n * `fs.readFile` that returns `null` instead of throwing on ENOENT.\n *\n * @example\n * const raw = await readIfExists('/missing.json') // => null\n * const raw = await readIfExists('/exists.json') // => '{ \"environments\": [\"dev\"] }\\n'\n */\nconst readIfExists = async (filePath: string): Promise<string | null> => {\n try {\n return await fs.readFile(filePath, 'utf-8')\n } catch {\n return null\n }\n}\n\n/**\n * Reference-equality comparison of every key in two flat records. Used to\n * cheaply detect whether the cached mtime fingerprint still matches.\n *\n * @example\n * shallowEqual({ a: 1, b: 2 }, { a: 1, b: 2 }) // => true\n * shallowEqual({ a: 1 }, { a: 1, b: 2 }) // => false\n * shallowEqual({ a: 1 }, { a: 2 }) // => false\n */\nconst shallowEqual = <T extends Record<string, unknown>>(a: T, b: T): boolean => {\n const keys = Object.keys(a)\n\n if (keys.length !== Object.keys(b).length) return false\n\n return keys.every((k) => {\n return a[k] === b[k]\n })\n}\n\ninterface ConfigLayer {\n label: string\n path: string\n required: boolean\n}\n\n/**\n * Read a single layer of the merge chain: parse the JSON if the file exists\n * and validate it against the override schema. Returns `null` if an optional\n * layer is missing; throws if the layer is required, malformed, or invalid.\n * An empty/whitespace-only file is treated as `{}` (JSON.parse would throw).\n *\n * @example\n * await loadLayer({ label: '~/.infra-kit/infra-kit.json', path: '/missing.json', required: false })\n * // => null\n *\n * @example\n * // /home/me/.infra-kit/infra-kit.json: '{ \"ide\": { \"provider\": \"cursor\", \"config\": { \"workspaceConfigPath\": \"./ws.code-workspace\" } } }'\n * await loadLayer({ label: '~/.infra-kit/infra-kit.json', path: '/home/me/.infra-kit/infra-kit.json', required: false })\n * // => { ide: { provider: 'cursor', config: { workspaceConfigPath: './ws.code-workspace' } } }\n */\nconst loadLayer = async (layer: ConfigLayer): Promise<Record<string, unknown> | null> => {\n const raw = await readIfExists(layer.path)\n\n if (raw === null) {\n if (layer.required) {\n throw new Error(`${layer.label} not found at ${layer.path}`)\n }\n\n return null\n }\n\n let parsedRaw: unknown\n\n try {\n parsedRaw = raw.trim() === '' ? {} : JSON.parse(raw)\n } catch (err) {\n throw new Error(`Invalid JSON in ${layer.label} at ${layer.path}: ${(err as Error).message}`)\n }\n\n const result = infraKitOverrideConfigSchema.safeParse(parsedRaw)\n\n if (!result.success) {\n throw new Error(`Invalid ${layer.label} at ${layer.path}: ${z.prettifyError(result.error)}`)\n }\n\n return result.data as Record<string, unknown>\n}\n", "import path from 'node:path'\nimport { $ } from 'zx'\n\nimport { isReleaseBranch } from 'src/lib/release-id'\n\n/**\n * Get current git worktrees\n *\n * @returns [release/v1.18.22, release/v1.18.23, release/v1.18.24] or [feature/mobile-app, feature/explore-page, feature/login-page]\n */\nexport const getCurrentWorktrees = async (type: 'release' | 'feature'): Promise<string[]> => {\n const worktreesOutput = await $`git worktree list`\n\n const worktreeLines = worktreesOutput.stdout.split('\\n').filter(Boolean)\n\n const worktreePredicateMap = {\n release: releaseWorktreePredicate,\n feature: featureWorktreePredicate,\n }\n\n return worktreeLines.map(worktreePredicateMap[type]).filter((branch) => {\n return branch !== null\n })\n}\n\n/**\n * Extract the branch name from a `git worktree list` output line.\n *\n * `git worktree list` formats each line as:\n * <path> <hash> [<branch>]\n *\n * Reads the branch from the trailing `[branch]` token so it works for the\n * main checkout too (whose path does not encode the branch name).\n */\nconst parseWorktreeBranch = (line: string): string | null => {\n const trimmed = line.trimEnd()\n\n if (!trimmed.endsWith(']')) return null\n\n const open = trimmed.lastIndexOf('[')\n\n if (open === -1) return null\n\n const branch = trimmed.slice(open + 1, -1)\n\n return branch.length > 0 ? branch : null\n}\n\n/**\n * Extract a release branch name from a `git worktree list` output line.\n *\n * Returns `null` for lines that are not release worktrees.\n *\n * @example\n * releaseWorktreePredicate('/path/to/release/v1.18.22 abc1234 [release/v1.18.22]')\n * // => 'release/v1.18.22'\n *\n * @example\n * releaseWorktreePredicate('/path/to/feature/login abc1234 [feature/login]')\n * // => null\n */\nconst releaseWorktreePredicate = (line: string): string | null => {\n const branch = parseWorktreeBranch(line)\n\n return isReleaseBranch(branch) ? branch : null\n}\n\n/**\n * Extract a feature branch name from a `git worktree list` output line.\n *\n * Returns `null` for lines that are not feature worktrees.\n *\n * @example\n * featureWorktreePredicate('/path/to/feature/login-page abc1234 [feature/login-page]')\n * // => 'feature/login-page'\n *\n * @example\n * featureWorktreePredicate('/path/to/release/v1.18.22 abc1234 [release/v1.18.22]')\n * // => null\n */\nconst featureWorktreePredicate = (line: string): string | null => {\n const branch = parseWorktreeBranch(line)\n\n return branch?.startsWith('feature/') ? branch : null\n}\n\n/**\n * Get the current project root directory\n */\nexport const getProjectRoot = async (): Promise<string> => {\n const result = await $`git rev-parse --show-toplevel`\n\n return result.stdout.trim()\n}\n\n/**\n * Absolute path to the MAIN repository root \u2014 invariant across the main checkout\n * and all of its linked worktrees. A linked worktree's `--show-toplevel` is the\n * worktree's own path, but its `--git-common-dir` still points at the shared\n * `<main>/.git`, so the parent of the resolved common dir is always the main repo.\n * This is the stable identity to key per-repo state on (unlike `getProjectRoot`,\n * whose basename is the worktree's leaf directory inside a worktree).\n *\n * Submodules are the one exception: their common dir is\n * `<super>/.git/modules/<name>`, whose parent (`.../.git/modules`) is not a repo\n * root \u2014 there is no meaningful \"main repo\" to converge on \u2014 so we fall back to\n * the caller-supplied toplevel unchanged. Callers must pass a git toplevel as\n * `cwd` (e.g. the result of {@link getProjectRoot}); the fallback assumes it.\n *\n * @example\n * // main checkout: common dir '.git' \u2192 resolve \u2192 '<main>/.git' \u2192 dirname \u2192 '<main>'\n * await getMainRepoRoot('/Users/me/projects/hulyo') // => '/Users/me/projects/hulyo'\n * // linked worktree: common dir '<main>/.git' \u2192 dirname \u2192 '<main>'\n * await getMainRepoRoot('/Users/me/projects/hulyo-worktrees/feature/x') // => '/Users/me/projects/hulyo'\n */\nexport const getMainRepoRoot = async (cwd?: string): Promise<string> => {\n const root = cwd ?? (await getProjectRoot())\n const commonDir = (await $({ cwd: root })`git rev-parse --git-common-dir`).stdout.trim()\n const resolved = path.resolve(root, commonDir)\n\n // Submodule: common dir sits under `<super>/.git/modules/<name>` \u2014 no stable\n // main-repo root to key on, so keep the caller's own toplevel.\n if (resolved.includes(`${path.sep}.git${path.sep}modules${path.sep}`)) return root\n\n return path.dirname(resolved)\n}\n\n/**\n * Get the current git branch name (e.g. `dev`, `main`, `release/v1.2.3`).\n */\nexport const getCurrentBranch = async (): Promise<string> => {\n const result = await $`git rev-parse --abbrev-ref HEAD`\n\n return result.stdout.trim()\n}\n\n/**\n * Whether the working tree has no staged, unstaged, or untracked changes.\n */\nexport const isWorkingTreeClean = async (): Promise<boolean> => {\n const result = await $`git status --porcelain`\n\n return result.stdout.trim().length === 0\n}\n\n/**\n * Whether the current checkout is a linked git worktree rather than the main\n * repository checkout.\n *\n * A linked worktree's git dir lives under `<main>/.git/worktrees/<name>`, so it\n * differs from the shared common dir; in the main checkout the two resolve to\n * the same path. Both are anchored to the toplevel so `--git-common-dir` (which\n * git may report relative to cwd) resolves consistently.\n */\nexport const isInsideLinkedWorktree = async (): Promise<boolean> => {\n const cwd = await getProjectRoot()\n\n const [gitDirResult, commonDirResult] = await Promise.all([\n $({ cwd })`git rev-parse --absolute-git-dir`,\n $({ cwd })`git rev-parse --git-common-dir`,\n ])\n\n const gitDir = gitDirResult.stdout.trim()\n const commonDir = path.resolve(cwd, commonDirResult.stdout.trim())\n\n return gitDir !== commonDir\n}\n\n/**\n * Get the current repository name (basename of the project root)\n */\nexport const getRepoName = async (): Promise<string> => {\n const projectRoot = await getProjectRoot()\n\n return path.basename(projectRoot)\n}\n\n/**\n * Delete a local branch if it exists and is not the current checkout.\n *\n * Idempotent: a no-op when the branch is absent (`git branch --list` prints\n * nothing). Uses force `-D` because a delivered release branch was\n * squash-merged \u2014 its tip is unreachable from the base, so `-d` would refuse\n * with \"not fully merged\". The delete itself still rejects if the branch is\n * checked out in another worktree; callers decide how to handle that.\n */\nexport const deleteLocalBranch = async (branch: string): Promise<void> => {\n const listed = await $`git branch --list ${branch}`\n\n if (listed.stdout.trim().length === 0) return\n\n if ((await getCurrentBranch()) === branch) return\n\n await $`git branch -D ${branch}`\n}\n\n/**\n * Delete a branch on the `origin` remote if it exists.\n *\n * Idempotent: a no-op when the branch is absent on the remote. Existence is\n * probed with `git ls-remote --heads` (empty stdout = absent) rather than\n * `--exit-code`, so a genuine network/auth failure rejects and propagates to\n * the caller instead of being silently misread as \"branch absent\".\n */\nexport const deleteRemoteBranch = async (branch: string): Promise<void> => {\n const refs = await $`git ls-remote --heads origin ${branch}`\n\n if (refs.stdout.trim().length === 0) return\n\n await $`git push origin --delete ${branch}`\n}\n", "/**\n * A release identity is either a semantic version or a free-form kebab-case\n * name. `raw` is the canonical token for the id: the no-`v` semver string for\n * versions (e.g. `1.2.3`) and the name itself for named releases.\n */\nexport type ReleaseId =\n | { kind: 'version'; semver: { major: number; minor: number; patch: number }; raw: string }\n | { kind: 'name'; name: string; raw: string }\n\n/** Matches a bare or `v`-prefixed semver token, e.g. `1.2.3` or `v1.2.3`. */\nconst VERSION_RE = /^v?(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/** Matches the semver core after the `v` in a `release/v\u2026` branch. */\nconst BRANCH_SEMVER_RE = /^(\\d+)\\.(\\d+)\\.(\\d+)$/\n\n/** Kebab-case: lowercase alphanumeric segments joined by single hyphens. */\nconst KEBAB_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\nconst RELEASE_BRANCH_PREFIX = 'release/'\nconst VERSION_BRANCH_PREFIX = 'release/v'\nconst REFS_HEADS_PREFIX = 'refs/heads/'\n\nconst NEXT_TOKEN = 'next'\nconst MAX_NAME_LENGTH = 50\n\n/**\n * Names that would collide with branch/release semantics or read as a special\n * token. Banned regardless of kebab-case validity.\n */\nconst RESERVED_NAMES: ReadonlySet<string> = new Set(['dev', 'main', 'next', 'hotfix', 'regular', 'release'])\n\n/** Thrown by {@link validateName} when a release name is not acceptable. */\nexport class InvalidReleaseNameError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'InvalidReleaseNameError'\n }\n}\n\n/** Thrown by {@link parseReleaseRef} when a release ref cannot be parsed. */\nexport class InvalidReleaseRefError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'InvalidReleaseRefError'\n }\n}\n\nconst stripRefsHeads = (input: string): string => {\n return input.startsWith(REFS_HEADS_PREFIX) ? input.slice(REFS_HEADS_PREFIX.length) : input\n}\n\nconst makeVersion = (major: number, minor: number, patch: number): ReleaseId => {\n return {\n kind: 'version',\n semver: { major, minor, patch },\n raw: `${major}.${minor}.${patch}`,\n }\n}\n\n/**\n * Validate a release name. Throws {@link InvalidReleaseNameError} with a\n * specific message unless the name is kebab-case, at most 50 characters, and\n * not a reserved word. Semver-looking tokens (e.g. `1.2.3`) are already\n * excluded by the kebab-case rule since they contain dots.\n */\nexport const validateName = (name: string): void => {\n if (name.length === 0) {\n throw new InvalidReleaseNameError('Release name is empty. Provide a kebab-case name like \"checkout-redesign\".')\n }\n\n if (name.length > MAX_NAME_LENGTH) {\n throw new InvalidReleaseNameError(\n `Release name \"${name}\" is ${name.length} characters; the maximum is ${MAX_NAME_LENGTH}.`,\n )\n }\n\n if (!KEBAB_RE.test(name)) {\n throw new InvalidReleaseNameError(\n `Release name \"${name}\" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. \"checkout-redesign\".`,\n )\n }\n\n if (RESERVED_NAMES.has(name)) {\n throw new InvalidReleaseNameError(\n `Release name \"${name}\" is reserved. Reserved names: ${[...RESERVED_NAMES].join(', ')}.`,\n )\n }\n}\n\n/**\n * Lenient parse of a git branch name into a {@link ReleaseId}. Tolerates a\n * leading `refs/heads/`. Returns `null` for anything that is not a valid\n * `release/v<semver>` or `release/<name>` branch. Never throws.\n *\n * Precedence is version-first: `release/v<semver>` is a version, but if the\n * segment after `release/v` is not a valid semver (e.g. `release/vnext`), the\n * whole token after `release/` is treated as a candidate name instead.\n */\nexport const parseBranchName = (branch: string): ReleaseId | null => {\n const stripped = stripRefsHeads(branch.trim())\n\n if (!stripped.startsWith(RELEASE_BRANCH_PREFIX)) return null\n\n if (stripped.startsWith(VERSION_BRANCH_PREFIX)) {\n const semverPart = stripped.slice(VERSION_BRANCH_PREFIX.length)\n const match = BRANCH_SEMVER_RE.exec(semverPart)\n\n if (match) {\n return makeVersion(Number(match[1]), Number(match[2]), Number(match[3]))\n }\n }\n\n const namePart = stripped.slice(RELEASE_BRANCH_PREFIX.length)\n\n try {\n validateName(namePart)\n } catch {\n return null\n }\n\n return { kind: 'name', name: namePart, raw: namePart }\n}\n\n/**\n * Strict parse of a release ref into a {@link ReleaseId}. Throws\n * {@link InvalidReleaseRefError} on invalid input. Precedence (order matters):\n * 1. `release/\u2026` (or `refs/heads/release/\u2026`) \u2192 delegate to parseBranchName.\n * 2. semver token (`1.2.3` / `v1.2.3`) \u2192 version.\n * 3. `next` \u2192 throws; callers must resolve `next` to a concrete version\n * via computeNextVersion before calling this.\n * 4. otherwise \u2192 validateName, returning a named release.\n */\nexport const parseReleaseRef = (input: string): ReleaseId => {\n const trimmed = input.trim()\n const branchCandidate = stripRefsHeads(trimmed)\n\n if (branchCandidate.startsWith(RELEASE_BRANCH_PREFIX)) {\n const parsed = parseBranchName(trimmed)\n\n if (!parsed) {\n throw new InvalidReleaseRefError(\n `\"${input}\" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`,\n )\n }\n\n return parsed\n }\n\n const versionMatch = VERSION_RE.exec(trimmed)\n\n if (versionMatch) {\n return makeVersion(Number(versionMatch[1]), Number(versionMatch[2]), Number(versionMatch[3]))\n }\n\n if (trimmed.toLowerCase() === NEXT_TOKEN) {\n throw new InvalidReleaseRefError(\n 'The \"next\" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.',\n )\n }\n\n try {\n validateName(trimmed)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n\n throw new InvalidReleaseRefError(`Cannot parse \"${input}\" as a release ref: ${reason}`)\n }\n\n return { kind: 'name', name: trimmed, raw: trimmed }\n}\n\n/** Render the branch name for a release id: `release/v1.2.3` | `release/<name>`. */\nexport const formatBranchName = (id: ReleaseId): string => {\n if (id.kind === 'version') return `${VERSION_BRANCH_PREFIX}${id.raw}`\n\n return `${RELEASE_BRANCH_PREFIX}${id.name}`\n}\n\n/**\n * Render a PR title: `Release v1.2.3` / `Hotfix v1.2.3` for versions,\n * `Release <name>` / `Hotfix <name>` for names.\n */\nexport const formatPrTitle = (id: ReleaseId, type: 'regular' | 'hotfix'): string => {\n const prefix = type === 'hotfix' ? 'Hotfix' : 'Release'\n\n if (id.kind === 'version') return `${prefix} v${id.raw}`\n\n return `${prefix} ${id.name}`\n}\n\n/** Render a release-candidate PR title: `Release v1.2.3 (RC)` | `Release <name> (RC)`. */\nexport const formatRcTitle = (id: ReleaseId): string => {\n if (id.kind === 'version') return `Release v${id.raw} (RC)`\n\n return `Release ${id.name} (RC)`\n}\n\n/** Render the Jira fix-version name: `v1.2.3` | `<name>`. */\nexport const formatJiraName = (id: ReleaseId): string => {\n if (id.kind === 'version') return `v${id.raw}`\n\n return id.name\n}\n\n/** Render a short human display label: `1.2.3` | `<name>`. */\nexport const displayLabel = (id: ReleaseId): string => {\n return id.raw\n}\n\n/** True iff `branch` is a valid release branch under either scheme. */\nexport const isReleaseBranch = (branch: string | null | undefined): boolean => {\n if (branch === null || branch === undefined) return false\n\n return parseBranchName(branch) !== null\n}\n\nconst toTime = (value: string | Date | undefined): number | null => {\n if (value === undefined) return null\n\n const time = value instanceof Date ? value.getTime() : new Date(value).getTime()\n\n return Number.isNaN(time) ? null : time\n}\n\n/**\n * Comparator for {@link ReleaseId} values (locked ordering):\n * - All versions sort before all names.\n * - Versions: semver ascending (major, then minor, then patch; numeric).\n * - Names: by date ascending when both dates are provided, otherwise\n * lexicographic by name. The result is stable and deterministic.\n */\nexport const compareReleaseIds = (\n a: ReleaseId,\n b: ReleaseId,\n dates?: { a?: string | Date; b?: string | Date },\n): number => {\n if (a.kind === 'version' && b.kind === 'version') {\n if (a.semver.major !== b.semver.major) return a.semver.major - b.semver.major\n if (a.semver.minor !== b.semver.minor) return a.semver.minor - b.semver.minor\n\n return a.semver.patch - b.semver.patch\n }\n\n if (a.kind === 'version') return -1\n if (b.kind === 'version') return 1\n\n const timeA = toTime(dates?.a)\n const timeB = toTime(dates?.b)\n\n if (timeA !== null && timeB !== null && timeA !== timeB) {\n return timeA - timeB\n }\n\n if (a.name < b.name) return -1\n if (a.name > b.name) return 1\n\n return 0\n}\n"],
|
|
5
|
-
"mappings": "AAAA,OAAOA,MAAa,eACpB,OAAOC,MAAU,OACjB,OAAOC,OAAY,cAGZ,IAAMC,EAAgB,yBAEhBC,GAAgB,IAAM,CACjC,IAAMC,EAAWL,EAAQ,KAAK,SAAS,SAAS,EAAI,QAAU,OAExDM,EAASL,EAAK,CAAE,MAAOI,CAAS,EAAGJ,EAAK,YAAY,CAAE,KAAME,CAAc,CAAC,CAAC,EAElF,OAAAG,EAAO,KAAK,kCAAkCD,CAAQ,iBAAiBF,CAAa,EAAE,EAE/EG,CACT,EAEaC,GAAgB,IAAM,CACjC,IAAMF,EAAWL,EAAQ,KAAK,SAAS,SAAS,EAAI,QAAU,OAExDQ,EAAe,CAAC,OAAQ,MAAO,UAAU,EAE/C,OAAIH,IAAa,SACfG,EAAa,KAAK,OAAO,EAGZP,EACb,CAAE,MAAOI,CAAS,EAClBH,GAAO,CACL,YAAa,EACb,OAAQM,EAAa,KAAK,GAAG,EAC7B,SAAU,EACZ,CAAC,CACH,CAGF,EAGaF,GAASC,GAAc,EC/BpC,UAAYE,MAAQ,UACpB,UAAYC,MAAU,YAYf,SAASC,GAAiBC,EAA0B,CACzD,IAAIC,EAAaD,EAEjB,QAASE,EAAI,EAAGA,EAAI,GAAIA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EAE1B,OAAIE,EAAK,SAAW,OAAO,KAAKD,CAAC,EAAE,OAAe,GAE3CC,EAAK,MAAOC,GACVH,EAAEG,CAAC,IAAMF,EAAEE,CAAC,CACpB,CACH,EAuBMT,GAAY,MAAOF,GAAgE,CACvF,IAAMY,EAAM,MAAML,GAAaP,EAAM,IAAI,EAEzC,GAAIY,IAAQ,KAAM,CAChB,GAAIZ,EAAM,SACR,MAAM,IAAI,MAAM,GAAGA,EAAM,KAAK,iBAAiBA,EAAM,IAAI,EAAE,EAG7D,OAAO,IACT,CAEA,IAAIa,EAEJ,GAAI,CACFA,EAAYD,EAAI,KAAK,IAAM,GAAK,CAAC,EAAI,KAAK,MAAMA,CAAG,CACrD,OAASE,EAAK,CACZ,MAAM,IAAI,MAAM,mBAAmBd,EAAM,KAAK,OAAOA,EAAM,IAAI,KAAMc,EAAc,OAAO,EAAE,CAC9F,CAEA,IAAMC,EAAShD,EAA6B,UAAU8C,CAAS,EAE/D,GAAI,CAACE,EAAO,QACV,MAAM,IAAI,MAAM,WAAWf,EAAM,KAAK,OAAOA,EAAM,IAAI,KAAK7D,EAAE,cAAc4E,EAAO,KAAK,CAAC,EAAE,EAG7F,OAAOA,EAAO,IAChB",
|
|
6
|
-
"names": ["process", "pino", "pretty", "LOG_FILE_PATH", "initLoggerMcp", "logLevel", "logger", "initLoggerCLI", "ignoreFields", "fs", "path", "findMonorepoRoot", "startDir", "currentDir", "i", "workspaceFile", "getPackageName", "apiPath", "appName", "pkgPath", "pkg", "discoverApiApps", "root", "appsDir", "apps", "appDirs", "dirent", "serverlessPath", "VITE_CONFIG_FILES", "usesInfraKitVite", "dir", "file", "configPath", "hasDevScript", "discoverUiApps", "uiPath", "normalizeAppInclude", "include", "filtered", "resolveSelfAppName", "relative", "firstSegment", "APP_PART_DIRS", "existingDistDir", "distDir", "subdirNames", "d", "getPackageDistDirs", "dirs", "name", "app", "part", "partDir", "getAppDistDirs", "classifyDistChange", "changedPath", "appDistDirs", "packageDistDirs", "normalized", "matchedPackageDir", "ALL_TARGETS_KEYS", "explainTargetKey", "key", "segments", "appGlob", "part", "parseTargetKey", "error", "validatePresetKeys", "presets", "issues", "preset", "def", "appsWithPart", "discovered", "allApps", "targetId", "app", "keyRank", "isGlob", "resolveWatch", "prior", "next", "addTarget", "state", "spec", "watchDeps", "id", "merged", "resolvePreset", "entries", "cfg", "apps", "targets", "localApps", "t", "deriveTargetLabel", "input", "running", "ownerApp", "apiPkgByApp", "pkg", "checkLocalRoute", "route", "launchedPkgs", "ctx", "owner", "hint", "validatePresetProxy", "resolved", "routes", "source", "issue", "fs", "os", "path", "process", "z", "path", "$", "VERSION_RE", "BRANCH_SEMVER_RE", "KEBAB_RE", "RELEASE_BRANCH_PREFIX", "VERSION_BRANCH_PREFIX", "REFS_HEADS_PREFIX", "NEXT_TOKEN", "RESERVED_NAMES", "InvalidReleaseNameError", "message", "InvalidReleaseRefError", "stripRefsHeads", "input", "REFS_HEADS_PREFIX", "makeVersion", "major", "minor", "patch", "validateName", "name", "KEBAB_RE", "parseBranchName", "branch", "stripped", "RELEASE_BRANCH_PREFIX", "VERSION_BRANCH_PREFIX", "semverPart", "match", "BRANCH_SEMVER_RE", "namePart", "parseReleaseRef", "trimmed", "parsed", "versionMatch", "VERSION_RE", "NEXT_TOKEN", "err", "reason", "formatBranchName", "id", "formatPrTitle", "type", "prefix", "formatRcTitle", "formatJiraName", "displayLabel", "isReleaseBranch", "toTime", "value", "time", "compareReleaseIds", "a", "b", "dates", "timeA", "timeB", "getCurrentWorktrees", "type", "worktreeLines", "$", "worktreePredicateMap", "releaseWorktreePredicate", "featureWorktreePredicate", "branch", "parseWorktreeBranch", "line", "trimmed", "open", "isReleaseBranch", "getProjectRoot", "getMainRepoRoot", "cwd", "root", "commonDir", "resolved", "path", "getCurrentBranch", "isWorkingTreeClean", "isInsideLinkedWorktree", "gitDirResult", "commonDirResult", "gitDir", "getRepoName", "projectRoot", "deleteLocalBranch", "deleteRemoteBranch", "INFRA_KIT_CONFIG_FILE", "USER_CONFIG_DIR_NAME", "USER_GLOBAL_CONFIG_FILE", "USER_PROJECTS_DIR", "dopplerEnvManagementSchema", "z", "envManagementSchema", "cursorIdeConfigSchema", "cursorIdeSchema", "zedIdeConfigSchema", "zedIdeSchema", "ideSchema", "idesSchema", "jiraTaskManagerSchema", "taskManagerSchema", "cmuxLayouts", "cmuxConfigSchema", "worktreesConfigSchema", "devAppConfigSchema", "devConfigSchema", "proxySourceSchema", "devPresetAppSchema", "devPresetSchema", "devPresetsSchema", "devProxyConfigSchema", "envAutoLoadSchema", "infraKitConfigObject", "DEFAULT_DEV_PROXY_PORT", "infraKitConfigSchema", "cfg", "ctx", "seen", "entry", "infraKitOverrideConfigSchema", "resolveConfiguredIdes", "config", "ide", "DEFAULT_CMUX_LAYOUT", "resolveCmuxLayout", "cached", "cachedPaths", "pathsCacheKey", "process", "os", "getInfraKitConfigPaths", "key", "projectRoot", "getProjectRoot", "mainRepoRoot", "getMainRepoRoot", "projectName", "path", "userConfigDir", "value", "getInfraKitConfig", "paths", "mainStat", "fs", "legacyYmlPath", "statIfExists", "userGlobalStat", "userProjectStat", "mtimes", "shallowEqual", "layers", "merged", "layer", "data", "loadLayer", "finalResult", "resetMergedConfigCache", "resetInfraKitConfigCache", "filePath", "readIfExists", "a", "b", "keys", "k", "raw", "parsedRaw", "err", "result"]
|
|
7
|
-
}
|
package/dist/chunk-DOG3OPNW.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var i={name:"infra-kit",type:"module",version:"0.1.134",files:["dist"],description:"infra-kit",main:"dist/index.js",module:"dist/index.js",types:"dist/entry/index.d.ts",exports:{".":{types:"./dist/entry/index.d.ts",import:"./dist/index.js"},"./vite":{types:"./dist/entry/vite.d.ts",import:"./dist/vite.js"}},bin:{"infra-kit":"dist/cli.js",ik:"dist/cli.js"},engines:{node:">=24.x"},scripts:{inspector:"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug",build:"pnpm run clean-artifacts && node ./scripts/build.js",prepack:"pnpm run build",prepublishOnly:"pnpm run build","infra-kit-check":"pnpm exec infra-kit audit","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@aws-lambda-powertools/logger":"^2.33.1","@inquirer/checkbox":"^5.2.1","@inquirer/confirm":"^6.1.1","@inquirer/select":"^5.2.1","@modelcontextprotocol/sdk":"^1.29.0",chalk:"^5.6.2",chokidar:"^5.0.0",commander:"^15.0.0",fastify:"5.10.0",ink:"^7.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",portless:"^0.15.1",react:"19.2.7",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@types/aws-lambda":"^8.10.162","@types/react":"19.2.17","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};export{i as a};
|
|
2
|
-
//# sourceMappingURL=chunk-DOG3OPNW.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../package.json"],
|
|
4
|
-
"sourcesContent": ["{\n \"name\": \"infra-kit\",\n \"type\": \"module\",\n \"version\": \"0.1.134\",\n \"files\": [\n \"dist\"\n ],\n \"description\": \"infra-kit\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/index.js\",\n \"types\": \"dist/entry/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/entry/index.d.ts\",\n \"import\": \"./dist/index.js\"\n },\n \"./vite\": {\n \"types\": \"./dist/entry/vite.d.ts\",\n \"import\": \"./dist/vite.js\"\n }\n },\n \"bin\": {\n \"infra-kit\": \"dist/cli.js\",\n \"ik\": \"dist/cli.js\"\n },\n \"engines\": {\n \"node\": \">=24.x\"\n },\n \"scripts\": {\n \"inspector\": \"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug\",\n \"build\": \"pnpm run clean-artifacts && node ./scripts/build.js\",\n \"prepack\": \"pnpm run build\",\n \"prepublishOnly\": \"pnpm run build\",\n \"infra-kit-check\": \"pnpm exec infra-kit audit\",\n \"clean-artifacts\": \"rm -rf dist\",\n \"clean-cache\": \"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc\",\n \"prettier-fix\": \"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"prettier-check\": \"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore\",\n \"eslint-check\": \"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src\",\n \"eslint-fix\": \"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix\",\n \"ts-check\": \"tsc --noEmit\",\n \"test\": \"pnpm exec vitest run --reporter=minimal\",\n \"test-watch\": \"pnpm exec vitest --watch --silent passed-only\",\n \"test-ui\": \"pnpm exec vitest --ui --silent passed-only\",\n \"test-report\": \"pnpm exec vitest run --coverage --silent passed-only\",\n \"qa\": \"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success\",\n \"fix\": \"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa\"\n },\n \"dependencies\": {\n \"@aws-lambda-powertools/logger\": \"^2.33.1\",\n \"@inquirer/checkbox\": \"^5.2.1\",\n \"@inquirer/confirm\": \"^6.1.1\",\n \"@inquirer/select\": \"^5.2.1\",\n \"@modelcontextprotocol/sdk\": \"^1.29.0\",\n \"chalk\": \"^5.6.2\",\n \"chokidar\": \"^5.0.0\",\n \"commander\": \"^15.0.0\",\n \"fastify\": \"5.10.0\",\n \"ink\": \"^7.1.0\",\n \"pino\": \"^10.3.1\",\n \"pino-pretty\": \"^13.1.3\",\n \"portless\": \"^0.15.1\",\n \"react\": \"19.2.7\",\n \"yaml\": \"^2.9.0\",\n \"zod\": \"^4.4.3\",\n \"zx\": \"^8.8.5\"\n },\n \"devDependencies\": {\n \"@types/aws-lambda\": \"^8.10.162\",\n \"@types/react\": \"19.2.17\",\n \"@wl/eslint-config\": \"workspace:*\",\n \"@wl/vitest-config\": \"workspace:*\",\n \"esbuild\": \"^0.28.1\",\n \"ink-testing-library\": \"^4.0.0\",\n \"typescript\": \"^6.0.3\"\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,IAAAA,EAAA,CACE,KAAQ,YACR,KAAQ,SACR,QAAW,UACX,MAAS,CACP,MACF,EACA,YAAe,YACf,KAAQ,gBACR,OAAU,gBACV,MAAS,wBACT,QAAW,CACT,IAAK,CACH,MAAS,0BACT,OAAU,iBACZ,EACA,SAAU,CACR,MAAS,yBACT,OAAU,gBACZ,CACF,EACA,IAAO,CACL,YAAa,cACb,GAAM,aACR,EACA,QAAW,CACT,KAAQ,QACV,EACA,QAAW,CACT,UAAa,iEACb,MAAS,sDACT,QAAW,iBACX,eAAkB,iBAClB,kBAAmB,4BACnB,kBAAmB,cACnB,cAAe,2EACf,eAAgB,4HAChB,iBAAkB,4HAClB,eAAgB,4EAChB,aAAc,kFACd,WAAY,eACZ,KAAQ,0CACR,aAAc,gDACd,UAAW,6CACX,cAAe,uDACf,GAAM,gHACN,IAAO,6DACT,EACA,aAAgB,CACd,gCAAiC,UACjC,qBAAsB,SACtB,oBAAqB,SACrB,mBAAoB,SACpB,4BAA6B,UAC7B,MAAS,SACT,SAAY,SACZ,UAAa,UACb,QAAW,SACX,IAAO,SACP,KAAQ,UACR,cAAe,UACf,SAAY,UACZ,MAAS,SACT,KAAQ,SACR,IAAO,SACP,GAAM,QACR,EACA,gBAAmB,CACjB,oBAAqB,YACrB,eAAgB,UAChB,oBAAqB,cACrB,oBAAqB,cACrB,QAAW,UACX,sBAAuB,SACvB,WAAc,QAChB,CACF",
|
|
6
|
-
"names": ["package_default"]
|
|
7
|
-
}
|
package/dist/chunk-JD5T4VCB.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import h from"node:process";var p=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],c=80,r={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",teal:"\x1B[36m",green:"\x1B[32m",blue:"\x1B[34m",red:"\x1B[31m"},a="\r\x1B[2K",u=/\x1B\[[0-9;]*m|\x1B\]8;;.*?\x1B\\/g,f=s=>s.replace(u,""),l=s=>String(s).padStart(2,"0"),m=s=>`${l(s.getHours())}:${l(s.getMinutes())}:${l(s.getSeconds())}`,v=s=>`${(s/1e3).toFixed(1)}s`,w=s=>`https://${s.alias}${s.prefixUrl}`,d=class{deps;spinnerTimer=null;spinnerPhase="";spinnerFrame=0;constructor(t={}){this.deps={write:t.write??(e=>{h.stdout.write(e)}),appendLog:t.appendLog??(()=>{}),isTTY:t.isTTY??!!h.stdout.isTTY,now:t.now??(()=>new Date),verbose:t.verbose??!1}}color(t,e){return this.deps.isTTY?`${t}${e}${r.reset}`:e}hyperlink(t,e){return!this.deps.isTTY||t===""?e:`\x1B]8;;file://${encodeURI(t).replace(/[#?]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`)}\x1B\\${e}\x1B]8;;\x1B\\`}teeOnly(t,e){this.deps.appendLog(`[${this.deps.now().toISOString()}] [${e.toUpperCase()}] ${f(t)}
|
|
2
|
-
`)}tee(t,e){this.teeOnly(t,e)}dispose(){}emit(t){if(this.spinnerTimer!=null&&this.deps.isTTY){this.deps.write(`${a}${t}
|
|
3
|
-
`),this.paintSpinner();return}this.deps.write(`${t}
|
|
4
|
-
`)}log(t,e="info"){(e!=="debug"||this.deps.verbose)&&this.emit(t),this.tee(t,e)}narrate(t){this.deps.verbose&&this.emit(t),this.tee(t,"info")}logFn=(t,e="info")=>{this.log(t,e)};paintSpinner(){let t=p[this.spinnerFrame%p.length];this.deps.write(`${a}${this.color(r.teal,t)} ${this.color(r.dim,this.spinnerPhase)}`)}bootStep(t){if(this.tee(t,"info"),this.spinnerPhase=t,!this.deps.isTTY){this.deps.write(`${t}
|
|
5
|
-
`);return}this.spinnerTimer==null&&(this.spinnerTimer=setInterval(()=>{this.spinnerFrame+=1,this.paintSpinner()},c),this.spinnerTimer.unref?.()),this.paintSpinner()}stopSpinner(){this.spinnerTimer!=null&&(clearInterval(this.spinnerTimer),this.spinnerTimer=null),this.deps.isTTY&&this.deps.write(a)}healthDot(t){return t===null?"":t?this.color(r.green,"\u25CF ok"):this.color(r.red,"\u25CF down")}ready(t){this.stopSpinner();let e=this.formatReadyLines(t);for(let i of e)this.emit(i),this.tee(i,"info")}tagWidth(t){return[...t.endpoints.map(i=>i.tag),...t.uiRefs.map(i=>i.tag),...(t.failed??[]).map(i=>i.tag)].reduce((i,n)=>Math.max(i,n.length),0)}titleLine(t){let e=[t.target,t.watch?"watch":null,t.release].filter(g=>!!g).join(" \xB7 "),i=t.failed?.length??0,n=v(t.elapsedMs),o=i>0?this.color(r.red,`${i} failed \xB7 started in ${n}`):this.color(r.green,`ready in ${n}`);return` ${this.color(r.bold,"infra-kit dev")} ${this.color(r.dim,e)} ${o}`}legendLines(t){let e=t.watch&&t.watchSummary?`watching ${t.watchSummary}`:"watch off",i=this.hyperlink(t.logHref,t.logPath),n=`${e} logs \u2192 ${i}`,o="\u2500".repeat(60);return[` ${this.color(r.dim,n)}`,` ${this.color(r.dim,o)}`]}uiRefLine(t,e){return` ${this.color(r.teal,t.padEnd(e))} ${this.color(r.dim,"\u2192 starting below (vite prints its URL)")}`}endpointLine(t,e,i){let n=i?this.healthDot(t.healthy):"",o=n?` ${n}`:"";return` ${this.color(r.teal,t.tag.padEnd(e))} ${this.color(r.blue,t.url)}${o}`}failedLine(t,e){return` ${this.color(r.teal,t.tag.padEnd(e))} ${this.color(r.red,"\u25CF failed")} ${this.color(r.dim,t.reason)}`}formatLines(t,{withHealthDot:e}){let i=this.tagWidth(t),n=["",this.titleLine(t),""];for(let o of t.endpoints)n.push(this.endpointLine(o,i,e));for(let o of t.failed??[])n.push(this.failedLine(o,i));for(let o of t.uiRefs)n.push(this.uiRefLine(o.tag,i));return n.push("",...this.legendLines(t)),n}formatHeaderLines(t){return this.formatLines(t,{withHealthDot:!1})}formatFooterLines(t){let e=this.tagWidth(t);return t.endpoints.filter(i=>i.healthy!==null).map(i=>` ${this.color(r.teal,i.tag.padEnd(e))} ${this.healthDot(i.healthy)}`)}formatReadyLines(t){return this.formatLines(t,{withHealthDot:!0})}event(t){let e=m(this.deps.now()),i=` ${this.color(r.dim,e)} ${this.color(r.teal,t.tag)} ${t.text}`;this.emit(i),this.tee(`${t.tag} ${t.text}`,"info")}};export{m as a,w as b,d as c};
|
|
6
|
-
//# sourceMappingURL=chunk-JD5T4VCB.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/dev/render.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Terminal renderer for `infra-kit dev` \u2014 a calm-print layer (never a full-screen TUI) that owns\n * every line the dev-server writes to the terminal, plus the tee to the session log (`logs.txt`).\n *\n * Design (see `.omc/plans/dev-log-redesign.md`): the boot collapses into a single transient spinner;\n * the final screen leads with per-server endpoints + health; the live tail is tagged + timestamped.\n * Full detail always reaches the log file regardless of `--verbose`.\n *\n * All I/O is injected (`write` / `appendLog` / `isTTY` / `now`) so every frame is snapshot-testable\n * and the spinner is deterministically disabled in tests (`isTTY: false`). The renderer coexists with\n * a child that owns its own TTY (vite via `turbo run dev`), because that child starts only AFTER\n * {@link DevRenderer.ready} has cleared the spinner \u2014 the spinner is never live concurrently with\n * inherited child output.\n */\nimport process from 'node:process'\n\nimport type { DevUi } from './dev-ui.js'\n\nexport type LogLevel = 'info' | 'warn' | 'error' | 'debug'\n\n/** Injected I/O seams. Defaults wire to the real stdout + a caller-provided file appender. */\nexport interface DevRendererDeps {\n /** Terminal sink (default: `process.stdout.write`). */\n write: (text: string) => void\n /** File tee \u2014 always receives full detail (default: no-op; the runner passes its log appender). */\n appendLog: (text: string) => void\n /** Whether the terminal is a TTY. Gates the spinner + ANSI color; false in CI / when piped. */\n isTTY: boolean\n /** Clock seam (default: `() => new Date()`), so timestamps + `ready in Xs` are testable. */\n now: () => Date\n /** When true, boot narration reaches the terminal; otherwise it is file-only. */\n verbose: boolean\n}\n\n/** One resolved backend endpoint row in the ready header. */\nexport interface EndpointRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** The app's `.localhost` alias URL \u2014 the only form, since an app that cannot be aliased never starts. */\n url: string\n /** Liveness: `true` \u2192 `\u25CF ok`, `false` \u2192 `\u25CF down`, `null` \u2192 no dot (not probed). */\n healthy: boolean | null\n}\n\n/**\n * A UI app whose URL the runner does not own, so it streams its own below \u2014 referenced, never given a\n * (fabricated) endpoint row. The fallback case only: a UI whose port the runner pre-assigned is an\n * {@link EndpointRow}, proxy or no proxy.\n */\nexport interface UiRef {\n /** Stream tag, e.g. `client/ui`. */\n tag: string\n}\n\n/**\n * An app that was asked for but never came up. It has no URL and no health \u2014 but it MUST still get a\n * row: the header is a report of what the user asked for, and an app that silently vanishes from it\n * reads as \"not requested\" rather than \"broken\".\n */\nexport interface FailedRow {\n /** Stream tag, e.g. `client/api`. */\n tag: string\n /** One-line reason, e.g. `config is missing field: 'connectionURL'`. */\n reason: string\n}\n\n/** Everything {@link DevRenderer.ready} needs to paint the final header in one shot. */\nexport interface ReadySummary {\n /** Resolved preset / target label (e.g. `client`, `*`). */\n target: string\n watch: boolean\n /**\n * True when this session launches a `turbo run dev` UI child that inherits the TTY. It is the\n * authoritative \"is this a UI session?\" signal \u2014 NOT `uiRefs.length > 0`. A UI whose port the runner\n * pre-assigned becomes an {@link EndpointRow}, not a {@link UiRef}, so `uiRefs` is normally empty even\n * for a UI session; any live region painted then would scribble into vite's inherited output. The\n * scroll-region footer (which tolerates the child) is chosen on this flag instead.\n */\n hasUiChild: boolean\n /** Slugified release for the header meta; omitted outside a git repo. */\n release?: string\n /** Backend readiness time in ms (UI is fire-and-forget, so this is BE-only \u2014 labeled honestly). */\n elapsedMs: number\n /** Real backend endpoint rows (owned ports + pre-probed health). */\n endpoints: EndpointRow[]\n /** UI apps that print their own URL below. */\n uiRefs: UiRef[]\n /**\n * Apps that failed to start. Optional only so the (many) existing summaries need not restate an\n * empty list; a non-empty one downgrades the title from a green `ready` to an honest `N failed`.\n */\n failed?: FailedRow[]\n /** Human watch summary, e.g. `1 app \u00B7 5 packages`; omitted when not watching. */\n watchSummary?: string\n /** Compact, human-readable log path shown as the `logs \u2192 \u2026` label (e.g. `~/.cache/infra-kit/<session>/logs.txt`). */\n logPath: string\n /** Absolute log path backing the clickable OSC-8 hyperlink (wrapped as `file://<logHref>`). */\n logHref: string\n}\n\nconst SPINNER_FRAMES = ['\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F']\nconst SPINNER_INTERVAL_MS = 80\n\nconst ANSI = {\n reset: '\\x1B[0m',\n dim: '\\x1B[2m',\n bold: '\\x1B[1m',\n teal: '\\x1B[36m',\n green: '\\x1B[32m',\n blue: '\\x1B[34m',\n red: '\\x1B[31m',\n} as const\n\n/** Erase the current line and return the cursor to column 0 (used to clear the spinner). */\nconst CLEAR_LINE = '\\r\\x1B[2K'\n\n/**\n * SGR color codes (`ESC [ \u2026 m`) and OSC-8 hyperlink wrappers (`ESC ] 8 ; ; \u2026 ESC \\`), non-greedy.\n * Matching the ESC control character is the whole point here \u2014 this pattern exists to remove it.\n */\n// eslint-disable-next-line sonarjs/no-control-regex, no-control-regex\nconst ANSI_PATTERN = /\\x1B\\[[0-9;]*m|\\x1B\\]8;;.*?\\x1B\\\\/g\n\n/**\n * Strip SGR colors + OSC-8 hyperlink escapes, keeping the hyperlink's visible label. Applied at the\n * file-tee seam so `logs.txt` stays greppable plain text even though the terminal frames it renders\n * from are colored + hyperlinked (both renderers format once, for a TTY, and tee the same string).\n */\nexport const stripAnsi = (s: string): string => {\n return s.replace(ANSI_PATTERN, '')\n}\n\n/** Zero-pad to 2 digits for `HH:MM:SS`. */\nconst pad2 = (n: number): string => {\n return String(n).padStart(2, '0')\n}\n\n/** `HH:MM:SS` for a tail timestamp. */\nexport const formatClock = (d: Date): string => {\n return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`\n}\n\n/** `2.4s` for the `ready in \u2026` header. */\nexport const formatElapsed = (ms: number): string => {\n return `${(ms / 1000).toFixed(1)}s`\n}\n\n/**\n * Resolve the endpoint URL for an app: `https://<alias><prefix>`, where `alias` is the portless hostname\n * the runner registered (e.g. `feat-x.backend-api.localhost`). The runner refuses to start an app it could\n * not alias, so there is no port-form to fall back to.\n *\n * There is no port and no scheme choice, by construction. The proxy serves TLS on 443 \u2014 the implicit HTTPS\n * port \u2014 so the URL is byte-identical to the `dev.proxy` local template that `infra-kit/vite` proxies to,\n * and what the table prints cannot drift from what the frontend calls. Any port suffix here would mean the\n * proxy is not on 443, which `ensureProxy` has already refused to start.\n */\nexport const resolveEndpointUrl = (input: { prefixUrl: string; alias: string }): string => {\n return `https://${input.alias}${input.prefixUrl}`\n}\n\nexport class DevRenderer implements DevUi {\n private readonly deps: DevRendererDeps\n private spinnerTimer: ReturnType<typeof setInterval> | null = null\n private spinnerPhase = ''\n private spinnerFrame = 0\n\n constructor(deps: Partial<DevRendererDeps> = {}) {\n this.deps = {\n write:\n deps.write ??\n ((text: string): void => {\n process.stdout.write(text)\n }),\n appendLog: deps.appendLog ?? ((): void => {}),\n isTTY: deps.isTTY ?? Boolean(process.stdout.isTTY),\n now:\n deps.now ??\n ((): Date => {\n return new Date()\n }),\n verbose: deps.verbose ?? false,\n }\n }\n\n /** Wrap `s` in an ANSI color on a TTY; return it untouched when piped (deterministic snapshots). */\n private color(code: string, s: string): string {\n return this.deps.isTTY ? `${code}${s}${ANSI.reset}` : s\n }\n\n /**\n * Wrap `label` in an OSC-8 terminal hyperlink to `href` (a filesystem path \u2192 `file://` URI) so the\n * log path is cmd/ctrl-clickable. Returns the bare `label` when piped (deterministic snapshots) or\n * when `href` is empty \u2014 terminals without OSC-8 support silently ignore the escapes anyway.\n */\n private hyperlink(href: string, label: string): string {\n if (!this.deps.isTTY || href === '') return label\n\n // `encodeURI` escapes spaces / non-ASCII but leaves `#` and `?`, which a file URI reads as a\n // fragment / query \u2014 encode those too so a path containing them still resolves to the real file.\n const uri = encodeURI(href).replace(/[#?]/g, (c) => {\n return `%${c.charCodeAt(0).toString(16).toUpperCase()}`\n })\n\n return `\\x1B]8;;file://${uri}\\x1B\\\\${label}\\x1B]8;;\\x1B\\\\`\n }\n\n /**\n * Append one line to the log file ONLY \u2014 the canonical `[iso] [LEVEL] msg` shape, no terminal write.\n * The single source of the file-tee format: the private {@link tee} and the Ink boot UI both route\n * here, so the log file stays identical whichever renderer is live.\n */\n teeOnly(message: string, level: LogLevel): void {\n this.deps.appendLog(`[${this.deps.now().toISOString()}] [${level.toUpperCase()}] ${stripAnsi(message)}\\n`)\n }\n\n /** File tee for a line that is ALSO written to the terminal; delegates the format to {@link teeOnly}. */\n private tee(message: string, level: LogLevel): void {\n this.teeOnly(message, level)\n }\n\n /**\n * No-op for the plain renderer: it owns no Ink / raw-mode terminal state to release. Present to\n * satisfy {@link DevUi} so the runner can call `dispose()` uniformly. Idempotent by construction.\n */\n dispose(): void {\n // Nothing to release \u2014 the plain renderer never seizes the terminal.\n }\n\n /**\n * Write one terminal line spinner-safely: if the spinner is live on a TTY, erase it, print the\n * line, then repaint the spinner, so a mid-boot message never shreds the `\\r`-based spinner.\n */\n private emit(line: string): void {\n if (this.spinnerTimer != null && this.deps.isTTY) {\n this.deps.write(`${CLEAR_LINE}${line}\\n`)\n this.paintSpinner()\n\n return\n }\n\n this.deps.write(`${line}\\n`)\n }\n\n /** A general message routed by level (terminal + file tee). Debug is terminal-only in verbose. */\n log(message: string, level: LogLevel = 'info'): void {\n if (level !== 'debug' || this.deps.verbose) {\n this.emit(message)\n }\n this.tee(message, level)\n }\n\n /** A boot-narration step: terminal only when `--verbose`, but always tee'd to the log. */\n narrate(message: string): void {\n if (this.deps.verbose) {\n this.emit(message)\n }\n this.tee(message, 'info')\n }\n\n /** `LogFn`-shaped adapter for the build runner seam (which passes `(msg, level)`). */\n readonly logFn = (message: string, level: LogLevel = 'info'): void => {\n this.log(message, level)\n }\n\n // ---- boot spinner -------------------------------------------------------\n\n /** Paint the current spinner frame in place (TTY only). */\n private paintSpinner(): void {\n const frame = SPINNER_FRAMES[this.spinnerFrame % SPINNER_FRAMES.length]!\n\n this.deps.write(`${CLEAR_LINE}${this.color(ANSI.teal, frame)} ${this.color(ANSI.dim, this.spinnerPhase)}`)\n }\n\n /**\n * Update the boot phase. On a TTY this drives a single transient spinner line; when piped it\n * prints one plain phase line (no ANSI, deterministic). Always tee'd to the log.\n */\n bootStep(phase: string): void {\n this.tee(phase, 'info')\n this.spinnerPhase = phase\n\n if (!this.deps.isTTY) {\n this.deps.write(`${phase}\\n`)\n\n return\n }\n\n if (this.spinnerTimer == null) {\n this.spinnerTimer = setInterval(() => {\n this.spinnerFrame += 1\n this.paintSpinner()\n }, SPINNER_INTERVAL_MS)\n // Never keep the event loop alive for the spinner alone.\n this.spinnerTimer.unref?.()\n }\n this.paintSpinner()\n }\n\n /** Stop + erase the spinner line (idempotent). Called before the ready header prints. */\n stopSpinner(): void {\n if (this.spinnerTimer != null) {\n clearInterval(this.spinnerTimer)\n this.spinnerTimer = null\n }\n if (this.deps.isTTY) {\n this.deps.write(CLEAR_LINE)\n }\n }\n\n // ---- the ready header ---------------------------------------------------\n\n /** Format the health dot for an endpoint row (`\u25CF ok` / `\u25CF down` / '' when unprobed). */\n private healthDot(healthy: boolean | null): string {\n if (healthy === null) return ''\n if (healthy) return this.color(ANSI.green, '\u25CF ok')\n\n return this.color(ANSI.red, '\u25CF down')\n }\n\n /**\n * Collapse the boot and print the final header in one shot: title line, one endpoint row per\n * backend server (with health dot), a reference line per UI app, the watch line, the clickable\n * log path, and a separator rule. Synchronous \u2014 health is pre-probed by the caller.\n */\n ready(summary: ReadySummary): void {\n this.stopSpinner()\n\n const lines = this.formatReadyLines(summary)\n\n for (const line of lines) {\n this.emit(line)\n this.tee(line, 'info')\n }\n }\n\n /** Column width for the aligned `tag` gutter \u2014 the widest endpoint/UI/failed tag. */\n private tagWidth(summary: ReadySummary): number {\n const tags = [\n ...summary.endpoints.map((e) => {\n return e.tag\n }),\n ...summary.uiRefs.map((u) => {\n return u.tag\n }),\n ...(summary.failed ?? []).map((f) => {\n return f.tag\n }),\n ]\n\n return tags.reduce((w, t) => {\n return Math.max(w, t.length)\n }, 0)\n }\n\n /**\n * The `infra-kit dev \u00B7 <meta> ready in Xs` title line.\n *\n * A green `ready` is a claim about the whole session, so it is spent only when the whole session\n * is up. With anything in `failed` the status turns red and counts the casualties instead \u2014 the\n * boot time alone, next to a green word, is exactly how a half-dead session used to pass for a\n * healthy one.\n */\n private titleLine(summary: ReadySummary): string {\n const meta = [summary.target, summary.watch ? 'watch' : null, summary.release]\n .filter((s): s is string => {\n return Boolean(s)\n })\n .join(' \u00B7 ')\n\n const failedCount = summary.failed?.length ?? 0\n const elapsed = formatElapsed(summary.elapsedMs)\n const status =\n failedCount > 0\n ? this.color(ANSI.red, `${failedCount} failed \u00B7 started in ${elapsed}`)\n : this.color(ANSI.green, `ready in ${elapsed}`)\n\n return ` ${this.color(ANSI.bold, 'infra-kit dev')} ${this.color(ANSI.dim, meta)} ${status}`\n }\n\n /** The static legend tail: watch line + clickable log path, then a separator rule. */\n private legendLines(summary: ReadySummary): string[] {\n const watchText = summary.watch && summary.watchSummary ? `watching ${summary.watchSummary}` : 'watch off'\n const logLink = this.hyperlink(summary.logHref, summary.logPath)\n const watchLine = `${watchText} logs \u2192 ${logLink}`\n const rule = '\u2500'.repeat(60)\n\n return [` ${this.color(ANSI.dim, watchLine)}`, ` ${this.color(ANSI.dim, rule)}`]\n }\n\n /** A UI reference row (`client/ui \u2192 starting below \u2026`) \u2014 used only when infra-kit could not claim its port. */\n private uiRefLine(tag: string, tagWidth: number): string {\n return ` ${this.color(ANSI.teal, tag.padEnd(tagWidth))} ${this.color(\n ANSI.dim,\n '\u2192 starting below (vite prints its URL)',\n )}`\n }\n\n /** One endpoint row (`client/api http://\u2026`); appends a health dot only when `withHealthDot` and the endpoint is probed. */\n private endpointLine(endpoint: ReadySummary['endpoints'][number], tagWidth: number, withHealthDot: boolean): string {\n const dot = withHealthDot ? this.healthDot(endpoint.healthy) : ''\n const dotSuffix = dot ? ` ${dot}` : ''\n\n return ` ${this.color(ANSI.teal, endpoint.tag.padEnd(tagWidth))} ${this.color(ANSI.blue, endpoint.url)}${dotSuffix}`\n }\n\n /** One failed row (`client/api \u25CF failed <reason>`) \u2014 no URL, because there is nothing listening. */\n private failedLine(failed: FailedRow, tagWidth: number): string {\n return ` ${this.color(ANSI.teal, failed.tag.padEnd(tagWidth))} ${this.color(\n ANSI.red,\n '\u25CF failed',\n )} ${this.color(ANSI.dim, failed.reason)}`\n }\n\n /**\n * Shared header layout: blank, title line, blank, one endpoint row per backend, a reference row per\n * UI app, then the watch/log legend. `withHealthDot` is the ONLY difference between the static Ink\n * header (false \u2014 health is live, the footer owns it) and the ready/boot frame (true).\n */\n private formatLines(summary: ReadySummary, { withHealthDot }: { withHealthDot: boolean }): string[] {\n const tagWidth = this.tagWidth(summary)\n const lines: string[] = ['', this.titleLine(summary), '']\n\n for (const e of summary.endpoints) {\n lines.push(this.endpointLine(e, tagWidth, withHealthDot))\n }\n // Failures sit with the live rows, not in the scrollback above: the log line announcing the crash\n // is metres up the terminal by now, and the header is the only thing the user actually reads.\n for (const f of summary.failed ?? []) {\n lines.push(this.failedLine(f, tagWidth))\n }\n for (const u of summary.uiRefs) {\n lines.push(this.uiRefLine(u.tag, tagWidth))\n }\n\n lines.push('', ...this.legendLines(summary))\n\n return lines\n }\n\n /**\n * Static reference lines for the persistent Ink header, committed ONCE via `<Static>`: title,\n * endpoint URLs WITHOUT the health dot (health is live \u2192 the footer owns it), UI reference rows,\n * watch line, clickable log path, separator. Pure; colors follow `isTTY`.\n */\n formatHeaderLines(summary: ReadySummary): string[] {\n return this.formatLines(summary, { withHealthDot: false })\n }\n\n /**\n * Live status lines for the persistent Ink footer, re-rendered in place as health flips (never\n * committed to `<Static>`): one health row per PROBED backend endpoint (`client/api \u25CF ok`).\n * Unprobed endpoints (`healthy === null`) are omitted. Pure; colors follow `isTTY`.\n */\n formatFooterLines(summary: ReadySummary): string[] {\n const tagWidth = this.tagWidth(summary)\n\n return summary.endpoints\n .filter((e) => {\n return e.healthy !== null\n })\n .map((e) => {\n return ` ${this.color(ANSI.teal, e.tag.padEnd(tagWidth))} ${this.healthDot(e.healthy)}`\n })\n }\n\n /**\n * Build the ready-header lines with NO side effects (no terminal write, no tee), so both\n * {@link ready} (which writes + tees them) and the Ink boot UI (which commits them via `<Static>`\n * and tee-only's them) share one layout. Colors follow `isTTY` exactly like every other line.\n */\n formatReadyLines(summary: ReadySummary): string[] {\n return this.formatLines(summary, { withHealthDot: true })\n }\n\n // ---- the live tail ------------------------------------------------------\n\n /**\n * One tagged, timestamped tail line: `14:02:11 client/api GET /api/v1/ping 200 12ms`. Arrives\n * strictly after {@link ready} (a request implies a running server), so it never interleaves the\n * header. Timestamp comes from the injected clock.\n */\n event(input: { tag: string; text: string }): void {\n const ts = formatClock(this.deps.now())\n const line = ` ${this.color(ANSI.dim, ts)} ${this.color(ANSI.teal, input.tag)} ${input.text}`\n\n this.emit(line)\n this.tee(`${input.tag} ${input.text}`, 'info')\n }\n}\n"],
|
|
5
|
-
"mappings": "AAcA,OAAOA,MAAa,eAsFpB,IAAMC,EAAiB,CAAC,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,SAAK,QAAG,EAClEC,EAAsB,GAEtBC,EAAO,CACX,MAAO,UACP,IAAK,UACL,KAAM,UACN,KAAM,WACN,MAAO,WACP,KAAM,WACN,IAAK,UACP,EAGMC,EAAa,YAObC,EAAe,qCAORC,EAAa,GACjB,EAAE,QAAQD,EAAc,EAAE,EAI7BE,EAAQC,GACL,OAAOA,CAAC,EAAE,SAAS,EAAG,GAAG,EAIrBC,EAAeC,GACnB,GAAGH,EAAKG,EAAE,SAAS,CAAC,CAAC,IAAIH,EAAKG,EAAE,WAAW,CAAC,CAAC,IAAIH,EAAKG,EAAE,WAAW,CAAC,CAAC,GAIjEC,EAAiBC,GACrB,IAAIA,EAAK,KAAM,QAAQ,CAAC,CAAC,IAarBC,EAAsBC,GAC1B,WAAWA,EAAM,KAAK,GAAGA,EAAM,SAAS,GAGpCC,EAAN,KAAmC,CACvB,KACT,aAAsD,KACtD,aAAe,GACf,aAAe,EAEvB,YAAYC,EAAiC,CAAC,EAAG,CAC/C,KAAK,KAAO,CACV,MACEA,EAAK,QACHC,GAAuB,CACvBjB,EAAQ,OAAO,MAAMiB,CAAI,CAC3B,GACF,UAAWD,EAAK,YAAc,IAAY,CAAC,GAC3C,MAAOA,EAAK,OAAS,EAAQhB,EAAQ,OAAO,MAC5C,IACEgB,EAAK,MACJ,IACQ,IAAI,MAEf,QAASA,EAAK,SAAW,EAC3B,CACF,CAGQ,MAAME,EAAcC,EAAmB,CAC7C,OAAO,KAAK,KAAK,MAAQ,GAAGD,CAAI,GAAGC,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AMW,EAAM,GAAG,CAAC,KAAKA,EAAM,IAAI,GAE9F,KAAK,KAAKW,CAAI,EACd,KAAK,IAAI,GAAGX,EAAM,GAAG,IAAIA,EAAM,IAAI,GAAI,MAAM,CAC/C,CACF",
|
|
6
|
-
"names": ["process", "SPINNER_FRAMES", "SPINNER_INTERVAL_MS", "ANSI", "CLEAR_LINE", "ANSI_PATTERN", "stripAnsi", "pad2", "n", "formatClock", "d", "formatElapsed", "ms", "resolveEndpointUrl", "input", "DevRenderer", "deps", "text", "code", "s", "href", "label", "c", "message", "level", "line", "frame", "phase", "healthy", "summary", "lines", "e", "u", "f", "w", "t", "meta", "failedCount", "elapsed", "status", "watchText", "logLink", "watchLine", "rule", "tag", "tagWidth", "endpoint", "withHealthDot", "dot", "dotSuffix", "failed", "ts"]
|
|
7
|
-
}
|
package/dist/chunk-LTKR3F4N.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/release-slug/release-slug.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Shared, dependency-light release-slug helper.\n *\n * Extracted from `lib/vite/vite.ts` so BOTH the published `infra-kit/vite` helper\n * (which re-exports it) and the dev-server's dev-context fragment writer derive the\n * `<release>` hostname segment from ONE implementation \u2014 the recorded slug and the\n * helper-computed slug can never drift. Pure (regex only, no imports) so importing it\n * into the lightweight `infra-kit/vite` bundle stays cheap.\n */\n\n/**\n * Slugify an arbitrary string into a single DNS label: lowercase, collapse every\n * non-alphanumeric run to `-`, and drop leading/trailing separators. Returns `''`\n * when the input carries no alphanumeric run (the caller must treat that as \"no label\").\n *\n * portless rejects any hostname outside `[a-z0-9.-]`, so every segment fed into a\n * `<release>.<packageName>.localhost` alias must pass through here. A scoped npm name\n * (`@hulyo/client-ui`) is the motivating case: registering it raw fails with\n * `Invalid hostname`, and because the driver swallows that into a best-effort `false`,\n * the whole hero-URL path degrades silently to `localhost:<port>`.\n *\n * Distinct from {@link slugifyRelease}: this does NOT strip a git-flow prefix, so a\n * package legitimately named `fix-utils` keeps its `fix-` prefix.\n *\n * @example\n * slugifyHostLabel('@hulyo/client-ui') // => 'hulyo-client-ui'\n * slugifyHostLabel('backend-api') // => 'backend-api'\n */\nexport const slugifyHostLabel = (label: string): string => {\n // Collect the alphanumeric runs and join with `-`. Doing it this way (rather\n // than collapse-then-trim) is linear and sidesteps a super-linear trim regex,\n // while inherently dropping any leading/trailing separators.\n const runs = label.toLowerCase().match(/[a-z0-9]+/g)\n\n return runs ? runs.join('-') : ''\n}\n\n/**\n * Slugify a git branch into a `<release>` token: strip a leading git-flow prefix\n * (`feature/`, `release/`, \u2026), then reduce the remainder to a single DNS label.\n *\n * @example\n * slugifyRelease('release/2.4') // => '2-4'\n * slugifyRelease('feature/HUL-123') // => 'hul-123'\n */\nexport const slugifyRelease = (branch: string): string => {\n return slugifyHostLabel(branch.replace(/^(?:feature|feat|release|hotfix|bugfix|fix|chore)\\//i, ''))\n}\n\n/**\n * The `<release>` label used when no git branch resolves (outside a repo, or a branch that slugifies to\n * nothing). Both the dev-server's alias writer and `infra-kit/vite`'s template interpolation fall back\n * to this SAME constant \u2014 a divergence here would emit a hostname no alias backs.\n */\nexport const DEFAULT_RELEASE_SLUG = 'local'\n"],
|
|
5
|
-
"mappings": "AA4BO,IAAMA,EAAoBC,GAA0B,CAIzD,IAAMC,EAAOD,EAAM,YAAY,EAAE,MAAM,YAAY,EAEnD,OAAOC,EAAOA,EAAK,KAAK,GAAG,EAAI,EACjC,EAUaC,EAAkBC,GACtBJ,EAAiBI,EAAO,QAAQ,uDAAwD,EAAE,CAAC,EAQvFC,EAAuB",
|
|
6
|
-
"names": ["slugifyHostLabel", "label", "runs", "slugifyRelease", "branch", "DEFAULT_RELEASE_SLUG"]
|
|
7
|
-
}
|
package/dist/chunk-TUVUKM4K.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{a as v,b as x,c as y}from"./chunk-LTKR3F4N.js";import{Buffer as K}from"node:buffer";import{execFileSync as L}from"node:child_process";import g from"node:fs";import O from"node:net";import u from"node:path";import p from"node:process";import{pathToFileURL as _}from"node:url";import{z as l}from"zod";import{z as i}from"zod";var P=i.strictObject({requiredScripts:i.array(i.string().min(1)).optional(),requiredFiles:i.array(i.string().min(1)).optional(),turbo:i.strictObject({requiredTasks:i.array(i.string().min(1)).optional()}).optional(),dev:i.strictObject({proxy:i.strictObject({templates:i.strictObject({local:i.string().min(1),cloud:i.string().min(1)}),routes:i.record(i.string().min(1),i.strictObject({packageName:i.string().min(1),from:i.array(i.enum(["local","cloud"])).min(1),default:i.enum(["local","cloud"]).optional()}).refine(e=>e.from.length<=1||e.default!==void 0,{message:"default is required when `from` has more than one source"}).refine(e=>e.default===void 0||e.from.includes(e.default),{message:"default must be listed in `from`"}))}).optional()}).optional()});var R="INFRA_KIT_ENV",k="infra-kit.config.ts",N=u.join(".infra-kit","dev-context"),T=u.join(".infra-kit","dev-context.json"),D=l.object({package:l.string(),port:l.number(),pid:l.number().optional(),writtenAt:l.number().optional(),release:l.string().optional(),alias:l.string().optional(),proxyPort:l.number().optional(),origin:l.string().optional()}),j=(e,t)=>{let r=t?.username??e.E2E__BASIC_AUTH_USERNAME,n=t?.password??e.E2E__BASIC_AUTH_PASSWORD;return!r||!n?void 0:`Basic ${K.from(`${r}:${n}`).toString("base64")}`};var b=(e,t)=>e.replaceAll("<release>",t.release).replaceAll("<packageName>",t.packageName).replaceAll("<env>",t.env),C=80,F="127.0.0.1",S=(e,t)=>{if(t==null||t===C)return e;let r;try{r=new URL(e)}catch{throw new Error(`infra-kit/vite: dev.proxy templates.local resolved to "${e}", which is not a valid URL, so the proxy port ${t} cannot be applied.`)}if(r.port!=="")return e;r.port=String(t);let n=r.toString();return!e.endsWith("/")&&n.endsWith("/")?n.slice(0,-1):n},U=1024,V=(e,t)=>t!=null&&t>=U?S(e.replace(/^https:\/\//iu,"http://"),t):S(e,t),M=e=>{let{route:t,templates:r,env:n,getRelease:a,info:o}=e;if(o?.origin)return o.origin;let s=b(r.local,{release:o?.release??a(),packageName:v(t.packageName),env:n??""});return V(s,o?.proxyPort)},H=(e,t)=>{let r=e.default??e.from[0];return e.from.includes("local")&&t.has(e.packageName)?"local":r},$=new Set(["localhost","127.0.0.1","::1"]),B=e=>{let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}let r=t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t;return r.endsWith(".localhost")||$.has(r)},W=({routePath:e,route:t,templates:r,localSet:n,env:a,getRelease:o,localInfo:s})=>{if(H(t,n)==="local"){let f=M({route:t,templates:r,env:a,getRelease:o,info:s?.get(t.packageName)});return B(f)?{target:f,changeOrigin:!0,secure:!1}:{target:f,changeOrigin:!0}}if(!a)throw new Error(`infra-kit/vite: proxy route "${e}" resolves to a cloud backend but ${R} is not set. Source an environment from Doppler first (e.g. \`infra-kit env-load -c dev\`).`);return{target:b(r.cloud,{release:"",packageName:t.packageName,env:a}),changeOrigin:!0,secure:!1,cookieDomainRewrite:"localhost"}},J=({proxy:e,localSet:t,env:r,getRelease:n,authHeader:a,localInfo:o})=>{let s={},c=a?{Authorization:a}:void 0;for(let[d,f]of Object.entries(e.routes)){let m=W({routePath:d,route:f,templates:e.templates,localSet:t,env:r,getRelease:n,localInfo:o});s[d]=c?{...m,headers:c}:m}return s},G=e=>{let t;return()=>(t??={value:e()},t.value)},q=async e=>{let t=u.join(e,k);if(!g.existsSync(t))return;let r=g.statSync(t),o=(await import(`${_(t).href}?mtime=${Number(r.mtimeMs)}`)).default;if(o===void 0)return;let s=typeof o=="function"?await o():o,c=P.safeParse(s);if(!c.success)throw new Error(`infra-kit/vite: invalid ${k} at ${t}: ${l.prettifyError(c.error)}`);return c.data.dev},z=e=>{if(Array.isArray(e))return e.filter(t=>typeof t=="string");if(e!==null&&typeof e=="object"){let t=e.packages??e.localPackages;if(Array.isArray(t))return t.filter(r=>typeof r=="string")}return[]},I=(e,t)=>{let r=u.resolve(e);for(;;){let n=u.join(r,t);if(g.existsSync(n))return n;let a=u.dirname(r);if(a===r)return;r=a}},h=()=>({packages:new Set,info:new Map}),X=e=>{if(e==null)return!0;try{return p.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Y=e=>{let t;try{t=g.readdirSync(e)}catch{return h()}let r=new Set,n=new Map;for(let a of t)if(a.endsWith(".json"))try{let o=D.safeParse(JSON.parse(g.readFileSync(u.join(e,a),"utf-8")));if(!o.success||!X(o.data.pid))continue;r.add(o.data.package),n.set(o.data.package,{port:o.data.port,origin:o.data.origin,release:o.data.release,alias:o.data.alias,proxyPort:o.data.proxyPort})}catch{continue}return{packages:r,info:n}},Q=e=>{let t=I(e,N);if(t)return Y(t);let r=I(e,T);if(!r)return h();try{return{packages:new Set(z(JSON.parse(g.readFileSync(r,"utf-8")))),info:new Map}}catch{return h()}};var Z=e=>L("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf-8"}).trim(),ee=()=>new Promise((e,t)=>{let r=O.createServer();r.unref(),r.on("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address(),a=typeof n=="object"&&n!==null?n.port:0;r.close(()=>e(a))})}),te="INFRA_KIT_UI_PORTS",re=e=>{try{let t=JSON.parse(g.readFileSync(u.join(e,"package.json"),"utf-8"));return typeof t.name=="string"?t.name:null}catch{return null}},ne=e=>{let t=p.env[te];if(t==null||t==="")return null;let r=re(e);if(r==null)return null;try{let n=JSON.parse(t)[r];if(typeof n=="number")return{port:n};if(n===null||typeof n!="object")return null;let{port:a,alias:o}=n;return typeof a!="number"?null:{port:a,alias:typeof o=="string"?o:void 0}}catch{return null}},oe=443,ae=async(e={})=>{let t=e.cwd??p.cwd();if(e.command==="build")return{proxy:{}};let r=e.port==null?ne(t):null,n=e.port??r?.port??await ee(),a=r!=null,o=e.host??F,s=r?.alias==null?void 0:{protocol:"wss",host:r.alias,clientPort:oe},c={port:n,host:o,...a?{strictPort:a}:{},...s?{hmr:s}:{}},d=await q(t);if(!d?.proxy)return{...c,proxy:{}};let{packages:f,info:m}=Q(t),w=p.env[R],A=j(p.env,e.basicAuth),E=G(()=>{try{return x(Z(t))||y}catch{return y}});return{...c,proxy:J({proxy:d.proxy,localSet:f,env:w,getRelease:E,authHeader:A,localInfo:m})}},ve=async(e={})=>(await ae(e)).proxy;export{P as a,J as b,q as c,ae as d,ve as e};
|
|
2
|
-
//# sourceMappingURL=chunk-TUVUKM4K.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/vite/vite.ts", "../src/lib/package-config/package-config-schema.ts"],
|
|
4
|
-
"sourcesContent": ["import { Buffer } from 'node:buffer'\nimport { execFileSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport net from 'node:net'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { pathToFileURL } from 'node:url'\nimport { z } from 'zod'\n\nimport type {\n InfraKitDev,\n InfraKitDevProxy,\n InfraKitDevProxyRoute,\n InfraKitDevProxySource,\n} from '../package-config/package-config'\nimport { packageConfigSchema } from '../package-config/package-config-schema'\nimport { DEFAULT_RELEASE_SLUG, slugifyHostLabel, slugifyRelease } from '../release-slug/release-slug'\n\n/**\n * Env-name handle read at vite-config time to fill the `<env>` placeholder in a\n * cloud proxy target. Inlined (not imported from `src/lib/constants`) to keep the\n * `infra-kit/vite` bundle's import graph tiny \u2014 see the module header. Kept\n * byte-identical to `INFRA_KIT_ENV_VAR` in `src/lib/constants/constants.ts`.\n */\nconst INFRA_KIT_ENV = 'INFRA_KIT_ENV'\n\n/** Per-package config filename, mirrored from the CLI's `PACKAGE_CONFIG_FILE`. */\nconst PACKAGE_CONFIG_FILE = 'infra-kit.config.ts'\n\n/**\n * Repo-relative dev-context fragment DIRECTORY, searched upward from cwd. Each\n * runner (single-process or cmux pane) writes its OWN `<app>.json` fragment here\n * recording its real bound port + release; the helper merges them (see\n * {@link readLocalContext}). This is the current source of truth.\n */\nconst DEV_CONTEXT_DIR = path.join('.infra-kit', 'dev-context')\n\n/**\n * Legacy single-file dev-context manifest, searched upward from cwd. Read only as\n * a transitional back-compat path when {@link DEV_CONTEXT_DIR} is absent (the\n * directory wins per-package when both exist).\n */\nconst DEV_CONTEXT_FILE = path.join('.infra-kit', 'dev-context.json')\n\n/**\n * One `.infra-kit/dev-context/<app>.json` fragment. `package` is the load-bearing\n * field the helper reads (\u2192 localSet); `origin` is **the authoritative local target** \u2014\n * the exact origin the runner registered, obeyed verbatim by {@link resolveLocalTarget}.\n * The runner is the only party that knows the scheme and port its alias is really served\n * on, so the helper never re-derives them when `origin` is present.\n *\n * `release`, `alias` and `proxyPort` are the LEGACY inputs, read only when `origin` is\n * absent \u2014 which can only happen when an OLD CLI wrote the fragment (a CLI-only rollback).\n * `port` is no longer a proxy target (the direct `127.0.0.1:<port>` branch is gone) \u2014 it\n * survives as diagnostic provenance. `pid` is the staleness guard: {@link readFragmentDir}\n * drops a fragment whose writer is no longer alive, so a crashed runner cannot keep a\n * package pinned `local` at a dead alias. `writtenAt` is provenance only.\n *\n * Kept lenient (not `.strict()`) so extra writer fields never reject a valid fragment, and\n * deliberately un-`refine`d: a rejected fragment would drop a started package to `cloud`\n * instead of falling into legacy mode, which is what makes the rollback path work.\n */\nconst devContextFragmentSchema = z.object({\n package: z.string(),\n port: z.number(),\n pid: z.number().optional(),\n writtenAt: z.number().optional(),\n release: z.string().optional(),\n alias: z.string().optional(),\n proxyPort: z.number().optional(),\n origin: z.string().optional(),\n})\n\n/**\n * A single Vite `server.proxy` entry. `changeOrigin` is always set. `cookieDomainRewrite` is cloud-only\n * (it keeps an HTTPS cloud BE's cookies usable from a local FE). `secure: false` appears on BOTH sources\n * but for different reasons: a cloud target may serve a cert the local store rejects, and a local target\n * is served by portless from its own private CA \u2014 set there only for a loopback host (see\n * {@link isLoopbackTarget}). `headers` is present only when HTTP Basic Auth is injected (see\n * {@link buildBasicAuthHeader}) \u2014 it carries the `Authorization` header applied\n * uniformly to every route so upstream environments behind auth (e2e/staging)\n * stay reachable.\n */\nexport interface InfraKitViteProxyEntry {\n target: string\n changeOrigin: true\n secure?: false\n cookieDomainRewrite?: 'localhost'\n headers?: Record<string, string>\n}\n\n/** A Vite `server.proxy`-shaped map: path-prefix \u2192 proxy entry. */\nexport type InfraKitViteProxy = Record<string, InfraKitViteProxyEntry>\n\n/** Explicit HTTP Basic Auth credentials, overriding the `E2E__BASIC_AUTH_*` env vars. */\nexport interface InfraKitBasicAuth {\n username: string\n password: string\n}\n\nexport interface InfraKitDevOptions {\n /** Package dir whose `infra-kit.config.ts` is loaded. Defaults to `process.cwd()`. */\n cwd?: string\n /**\n * Explicit HTTP Basic Auth credentials injected into every proxy route as an\n * `Authorization` header. Takes precedence over the `E2E__BASIC_AUTH_USERNAME`\n * / `E2E__BASIC_AUTH_PASSWORD` env vars. Omit to use the env-based default.\n */\n basicAuth?: InfraKitBasicAuth\n /**\n * Vite's `command`. Pass it (`defineConfig(async ({ command }) => ({ server: await infraKitDev({ command }) }))`)\n * so `build` is a no-op: `server` is irrelevant to a build and proxy resolution would otherwise\n * fail-fast on a cloud route with no sourced env. Omit (or `'serve'`) for the dev-server config.\n */\n command?: 'build' | 'serve'\n /**\n * Explicit dev-server port. Omit for a **per-worktree dynamic** free port (a fresh OS-assigned\n * port) so N simultaneous git worktrees never collide on Vite's default `5173`; Vite prints the\n * chosen URL. Pass a fixed number only when an external contract pins the port.\n */\n port?: number\n /**\n * Interface the dev server binds. Defaults to {@link LOOPBACK_V4} so a portless alias can reach it\n * (Vite's own `localhost` default binds `[::1]` only, which the proxy cannot dial). Override when\n * the dev server must be reachable off the loopback \u2014 `'0.0.0.0'` or `true` inside a container, on\n * a LAN, or for an e2e runner on another host.\n */\n host?: string | boolean\n}\n\n/**\n * Build the `Authorization: Basic <base64(user:pass)>` header value. Credentials\n * come from `override` when given, else from `E2E__BASIC_AUTH_USERNAME` /\n * `E2E__BASIC_AUTH_PASSWORD` (NOTE: double underscore). Returns `undefined` when\n * either half is missing, so callers add no `headers` key at all.\n */\nconst buildBasicAuthHeader = (env: NodeJS.ProcessEnv, override?: InfraKitBasicAuth): string | undefined => {\n const username = override?.username ?? env.E2E__BASIC_AUTH_USERNAME\n const password = override?.password ?? env.E2E__BASIC_AUTH_PASSWORD\n\n if (!username || !password) return undefined\n\n const encoded = Buffer.from(`${username}:${password}`).toString('base64')\n\n return `Basic ${encoded}`\n}\n\n/**\n * Re-exported from the shared, dependency-light `lib/release-slug` module so the\n * published `infra-kit/vite` surface (`entry/vite.ts:7`) is unchanged while the\n * dev-server's fragment writer derives `<release>` from the SAME implementation\n * (no slug drift). See {@link slugifyRelease}.\n */\nexport { slugifyRelease }\n\n/** Fill the `<release>`/`<packageName>`/`<env>` placeholders in a URL template. */\nconst interpolate = (template: string, values: { release: string; packageName: string; env: string }): string => {\n return template\n .replaceAll('<release>', values.release)\n .replaceAll('<packageName>', values.packageName)\n .replaceAll('<env>', values.env)\n}\n\n/** The port a bare `http://` target implies, and the proxy's default \u2014 never spelled out in a URL. */\nconst DEFAULT_HTTP_PORT = 80\n\n/**\n * The interface the vite dev server binds. Pinned to IPv4 loopback because portless dials its routes\n * on `127.0.0.1`, while vite's default `host: 'localhost'` combined with its\n * `dns.setDefaultResultOrder('verbatim')` binds `[::1]` ONLY \u2014 the alias then resolves, the proxy\n * connects, and the connection is refused, surfacing as a 502 on every UI request. Backends never hit\n * this because `ServerlessLocalRun` already binds `127.0.0.1`. Still loopback-only: this narrows the\n * address family, it does not expose the dev server to the network.\n */\nconst LOOPBACK_V4 = '127.0.0.1'\n\n/**\n * Graft the proxy's listen port onto an interpolated local target. The `dev.proxy` local template is\n * written port-free (`https://<release>.<packageName>.localhost`) because the proxy serves TLS on `:443`,\n * the only port a port-free HTTPS URL can come from. A consumer who trades the clean URL for a zero-sudo\n * unprivileged port still needs the frontend to reach it, so the runner records the port it actually bound\n * and we append it here. A template that already pins its own port keeps it.\n */\nconst withProxyPort = (target: string, proxyPort: number | undefined): string => {\n if (proxyPort == null || proxyPort === DEFAULT_HTTP_PORT) return target\n\n let url: URL\n\n try {\n url = new URL(target)\n } catch {\n throw new Error(\n `infra-kit/vite: dev.proxy templates.local resolved to \"${target}\", which is not a valid URL, so the proxy port ${proxyPort} cannot be applied.`,\n )\n }\n\n if (url.port !== '') return target\n url.port = String(proxyPort)\n\n // `URL.toString()` synthesizes a `/` pathname for an authority-only URL, so the common port-free\n // template would come back as `\u2026localhost:1355/`. Strip that ONLY when the template had no trailing\n // slash of its own \u2014 a template ending in `/` (e.g. `\u2026localhost/base/`) means it, and silently\n // trimming it would change the path the frontend proxies to.\n const grafted = url.toString()\n\n return !target.endsWith('/') && grafted.endsWith('/') ? grafted.slice(0, -1) : grafted\n}\n\n/**\n * The lowest port a daemon can bind without root. An origin-less fragment recording a port AT OR ABOVE\n * this was written by an old CLI whose `spawnDaemon` always passed `--no-tls`, so infra-kit itself could\n * only ever have put PLAIN HTTP there. Below it (80/443) the daemon was installed out-of-band, where\n * portless defaults to TLS ON \u2014 which is precisely why the legacy scheme is left alone down there.\n */\nconst LEGACY_SELF_SPAWNED_PORT_FLOOR = 1024\n\n/**\n * Legacy target resolution \u2014 reached ONLY for an origin-less fragment, i.e. one written by an OLD CLI\n * (a CLI-only rollback). It must reproduce the old helper rather than reject anything, because that is\n * what lets the CLI be reverted without touching a single consumer repo.\n *\n * `proxyPort >= 1024`: force the scheme to `http`. **Mitigation, not a proof** \u2014 infra-kit's own\n * `spawnDaemon` always passed `--no-tls`, so an unprivileged daemon *infra-kit created* was always plain\n * HTTP; a HAND-STARTED TLS daemon on such a port (portless's own default is TLS) would be wrongly\n * downgraded here. That corner is accepted: forcing `http` reproduces what the old CLI + old helper\n * already emitted, so it regresses nothing that worked.\n *\n * `proxyPort < 1024` (80/443) or absent: the daemon was installed out-of-band and may well be TLS, and we\n * cannot know. Reproduce the old helper verbatim and NEVER rewrite the scheme \u2014 forcing `http` on a `:443`\n * fragment would emit `http://<alias>:443`, plain HTTP into a TLS listener, the exact silent failure this\n * design exists to remove.\n */\nconst resolveLegacyTarget = (target: string, proxyPort: number | undefined): string => {\n if (proxyPort != null && proxyPort >= LEGACY_SELF_SPAWNED_PORT_FLOOR) {\n return withProxyPort(target.replace(/^https:\\/\\//iu, 'http://'), proxyPort)\n }\n\n return withProxyPort(target, proxyPort)\n}\n\n/**\n * The proxy target for a route resolved to `local`. The runner PUBLISHES the contract and the helper OBEYS\n * it: when the fragment carries an `origin`, that string is the target verbatim \u2014 the runner is the only\n * party that knows the scheme and port the alias it registered is actually served on, and this helper ships\n * on its own release cadence, so any re-derivation here is a guess that can silently disagree.\n *\n * `templates.local` is consulted ONLY in legacy mode (see {@link resolveLegacyTarget}).\n *\n * The target proxies to a stable HOSTNAME, and the runner re-points that alias at the freshly-bound port\n * on every `--watch` restart, so it self-heals without Vite reloading its config.\n */\nconst resolveLocalTarget = (args: {\n route: InfraKitDevProxyRoute\n templates: InfraKitDevProxy['templates']\n env: string | undefined\n getRelease: () => string\n info: LocalPackageInfo | undefined\n}): string => {\n const { route, templates, env, getRelease, info } = args\n\n if (info?.origin) return info.origin\n\n const target = interpolate(templates.local, {\n // Prefer THIS package's runner-recorded release slug (R4) over the single global git derivation,\n // so cross-branch FE/BE pairings don't drift the emitted `<release>` from the segment the runner\n // aliased. Fall back to the global git slug only when the fragment carried no release.\n release: info?.release ?? getRelease(),\n // The local template resolves to a `<release>.<packageName>.localhost` alias the dev-server\n // registered with portless \u2014 which slugifies the package name to a legal DNS label. Slugify\n // identically here or a scoped name (`@hulyo/client-ui`) emits a target that no alias backs.\n packageName: slugifyHostLabel(route.packageName),\n env: env ?? '',\n })\n\n return resolveLegacyTarget(target, info?.proxyPort)\n}\n\n/**\n * Pick the effective source for a route: `local` when the route lists `local` as\n * a capability AND its packageName is in the local dev set; otherwise the fallback\n * \u2014 the declared `default` for a multi-source route, or the sole `from` entry for\n * a single-source one. Always resolves (the schema guarantees a usable fallback).\n */\nconst pickSource = (route: InfraKitDevProxyRoute, localSet: ReadonlySet<string>): InfraKitDevProxySource => {\n // `from` is guaranteed non-empty by the schema, so `from[0]` is always present.\n const fallback = route.default ?? route.from[0]!\n\n return route.from.includes('local') && localSet.has(route.packageName) ? 'local' : fallback\n}\n\ninterface ResolveRouteArgs {\n routePath: string\n route: InfraKitDevProxyRoute\n templates: InfraKitDevProxy['templates']\n localSet: ReadonlySet<string>\n env: string | undefined\n getRelease: () => string\n /** Per-package runtime data (recorded release/port) from the dev-context merge. */\n localInfo?: ReadonlyMap<string, LocalPackageInfo>\n}\n\n/** Hostnames that can only be this machine \u2014 the only ones a private-CA cert is allowed to go unchecked on. */\nconst LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1'])\n\n/**\n * Is `target` unambiguously on this machine? Only then may {@link resolveRoute} disable cert validation:\n * `templates.local` is an unconstrained string in a consumer-authored config, so an unconditional\n * `secure: false` in a PUBLISHED helper would silently switch off validation for whatever URL a consumer\n * wrote there. Scoping it to `.localhost`/loopback is what makes \"no MITM surface\" true by construction.\n * An unparseable target is NOT local (the caller then leaves `secure` unset \u2014 fail closed).\n */\nconst isLoopbackTarget = (target: string): boolean => {\n let hostname: string\n\n try {\n hostname = new URL(target).hostname.toLowerCase()\n } catch {\n return false\n }\n\n // `URL.hostname` brackets an IPv6 literal (`[::1]`); compare the bare address.\n const bare = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname\n\n return bare.endsWith('.localhost') || LOOPBACK_HOSTNAMES.has(bare)\n}\n\n/** Resolve one route into a Vite proxy entry (or throw an actionable error). */\nconst resolveRoute = ({\n routePath,\n route,\n templates,\n localSet,\n env,\n getRelease,\n localInfo,\n}: ResolveRouteArgs): InfraKitViteProxyEntry => {\n const source = pickSource(route, localSet)\n\n if (source === 'local') {\n const target = resolveLocalTarget({ route, templates, env, getRelease, info: localInfo?.get(route.packageName) })\n\n // The local target is now HTTPS, served with a cert minted by portless's own private CA. Node's\n // http-proxy validates the upstream chain against the system store, which does not contain that CA,\n // so every proxied request fails with SELF_SIGNED_CERT_IN_CHAIN (confirmed empirically \u2014 see\n // `.omc/research/portless-https-spike.md`). Only a loopback target earns the exemption.\n return isLoopbackTarget(target) ? { target, changeOrigin: true, secure: false } : { target, changeOrigin: true }\n }\n\n if (!env) {\n throw new Error(\n `infra-kit/vite: proxy route \"${routePath}\" resolves to a cloud backend but ${INFRA_KIT_ENV} is not set. Source an environment from Doppler first (e.g. \\`infra-kit env-load -c dev\\`).`,\n )\n }\n\n const target = interpolate(templates.cloud, { release: '', packageName: route.packageName, env })\n\n return { target, changeOrigin: true, secure: false, cookieDomainRewrite: 'localhost' }\n}\n\ninterface ResolveProxyArgs {\n proxy: InfraKitDevProxy\n localSet: ReadonlySet<string>\n env: string | undefined\n getRelease: () => string\n /** Pre-computed `Authorization` header value applied uniformly to every route. */\n authHeader?: string\n /** Per-package runtime data (recorded release/port) from the dev-context merge. */\n localInfo?: ReadonlyMap<string, LocalPackageInfo>\n}\n\n/**\n * Pure resolver: turn a `dev.proxy` config + resolved inputs (local set, env,\n * lazy release) into a Vite `server.proxy` map. Side-effect-free so the\n * resolution shape is fully unit-testable. When `authHeader` is set, every route\n * entry gets a matching `headers.Authorization`; otherwise no `headers` key.\n */\nexport const resolveProxyConfig = ({\n proxy,\n localSet,\n env,\n getRelease,\n authHeader,\n localInfo,\n}: ResolveProxyArgs): InfraKitViteProxy => {\n const result: InfraKitViteProxy = {}\n const headers = authHeader ? { Authorization: authHeader } : undefined\n\n for (const [routePath, route] of Object.entries(proxy.routes)) {\n const entry = resolveRoute({ routePath, route, templates: proxy.templates, localSet, env, getRelease, localInfo })\n\n result[routePath] = headers ? { ...entry, headers } : entry\n }\n\n return result\n}\n\n/** Memoize a zero-arg thunk so `<release>` git resolution runs at most once. */\nconst once = <T>(fn: () => T): (() => T) => {\n let cached: { value: T } | undefined\n\n return () => {\n cached ??= { value: fn() }\n\n return cached.value\n }\n}\n\n/**\n * Load a package's `infra-kit.config.ts` and return its `dev` block, or\n * `undefined` when the config or the `dev` key is absent. The `.ts` config is\n * evaluated via Node's native type stripping (Node >= 24) \u2014 the same mechanism\n * the CLI's config loader uses. Cache-busted by mtime so repeated dev-server\n * reloads pick up edits.\n */\nexport const loadDev = async (cwd: string): Promise<InfraKitDev | undefined> => {\n const configPath = path.join(cwd, PACKAGE_CONFIG_FILE)\n\n if (!fs.existsSync(configPath)) return undefined\n\n const stat = fs.statSync(configPath)\n const moduleUrl = `${pathToFileURL(configPath).href}?mtime=${Number(stat.mtimeMs)}`\n\n const imported = (await import(moduleUrl)) as { default?: unknown }\n const rawExport = imported.default\n\n if (rawExport === undefined) return undefined\n\n const resolved = typeof rawExport === 'function' ? await (rawExport as () => unknown)() : rawExport\n\n const parsed = packageConfigSchema.safeParse(resolved)\n\n if (!parsed.success) {\n throw new Error(`infra-kit/vite: invalid ${PACKAGE_CONFIG_FILE} at ${configPath}: ${z.prettifyError(parsed.error)}`)\n }\n\n return parsed.data.dev\n}\n\n/** Coerce a parsed dev-context.json into the set of locally-running package names. */\nconst extractPackages = (parsed: unknown): string[] => {\n if (Array.isArray(parsed)) {\n return parsed.filter((v): v is string => {\n return typeof v === 'string'\n })\n }\n\n if (parsed !== null && typeof parsed === 'object') {\n const candidate = (parsed as Record<string, unknown>).packages ?? (parsed as Record<string, unknown>).localPackages\n\n if (Array.isArray(candidate)) {\n return candidate.filter((v): v is string => {\n return typeof v === 'string'\n })\n }\n }\n\n return []\n}\n\n/** Search upward from `start` for `relative`, returning the first hit or undefined. */\nconst findUp = (start: string, relative: string): string | undefined => {\n let dir = path.resolve(start)\n\n for (;;) {\n const candidate = path.join(dir, relative)\n\n if (fs.existsSync(candidate)) return candidate\n\n const parent = path.dirname(dir)\n\n if (parent === dir) return undefined\n\n dir = parent\n }\n}\n\n/** Per-package runtime data merged from the dev-context fragment directory. */\nexport interface LocalPackageInfo {\n /** The real bound port the runner recorded. Provenance only \u2014 the proxy target is the alias host. */\n port: number\n /**\n * The authoritative local target (`https://<release>.<packageName>.localhost`), published by the\n * runner. Present \u2192 {@link resolveLocalTarget} uses it verbatim and consults no template. Absent \u2192\n * the fragment came from an old CLI and the legacy template path runs.\n */\n origin?: string\n /** LEGACY (no `origin`): the runner-recorded release slug, preferred over the helper's git derivation. */\n release?: string\n /** LEGACY (no `origin`): `<release>.<packageName>.localhost`, present only when an alias was registered. */\n alias?: string\n /** LEGACY (no `origin`): the port {@link alias} resolves on. `80` (the default) is implicit in the template. */\n proxyPort?: number\n}\n\n/**\n * The locally-running package set plus a `package \u2192 { port, release }` map merged\n * from the dev-context fragments. `packages` feeds `pickSource`; `info` lets a\n * `local` route emit the per-package recorded release (see {@link resolveRoute}).\n */\nexport interface LocalContext {\n packages: ReadonlySet<string>\n info: ReadonlyMap<string, LocalPackageInfo>\n}\n\n/** An empty {@link LocalContext} (frontend-only / dev-context absent). */\nconst emptyLocalContext = (): LocalContext => {\n return { packages: new Set(), info: new Map() }\n}\n\n/**\n * Is the runner that wrote a fragment still alive? Signal `0` performs the permission and existence\n * checks without delivering anything. `ESRCH` is the one answer that means \"gone\"; `EPERM` means the\n * pid exists under another uid, which is still a live process. A fragment with no `pid` predates the\n * field and is trusted (back-compat) rather than dropped.\n */\nconst isFragmentWriterAlive = (pid: number | undefined): boolean => {\n if (pid == null) return true\n\n try {\n process.kill(pid, 0)\n\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/**\n * Merge every `<app>.json` fragment in the dev-context directory into a\n * {@link LocalContext}. Two DISTINCT failure branches (do NOT collapse them into\n * one directory-wide catch):\n * - `readdir`-ENOENT (directory vanished mid-race) \u2192 empty context, matching the\n * dir-absent back-compat behaviour.\n * - a single corrupt/truncated/invalid `<app>.json` \u2192 that ONE fragment is\n * SKIPPED (per-fragment `safeParse` isolation); the rest still merge, so one bad\n * fragment never collapses the whole localSet to empty (which would silently\n * drop a started package to cloud).\n */\nconst readFragmentDir = (dir: string): LocalContext => {\n let entries: string[]\n\n try {\n entries = fs.readdirSync(dir)\n } catch {\n return emptyLocalContext()\n }\n\n const packages = new Set<string>()\n const info = new Map<string, LocalPackageInfo>()\n\n for (const name of entries) {\n if (!name.endsWith('.json')) continue\n\n try {\n const parsed = devContextFragmentSchema.safeParse(JSON.parse(fs.readFileSync(path.join(dir, name), 'utf-8')))\n\n if (!parsed.success) continue\n\n // A runner killed with SIGKILL (or crashed) leaves its fragment AND its portless alias behind.\n // Trusting it would route this package's `/api` at an alias nothing serves \u2014 a silent 502 with\n // no diagnostic. The writer already stamps its pid; honour it.\n if (!isFragmentWriterAlive(parsed.data.pid)) continue\n\n packages.add(parsed.data.package)\n info.set(parsed.data.package, {\n port: parsed.data.port,\n origin: parsed.data.origin,\n release: parsed.data.release,\n alias: parsed.data.alias,\n proxyPort: parsed.data.proxyPort,\n })\n } catch {\n // Corrupt/truncated fragment (JSON.parse / read failure): skip ONLY this one.\n continue\n }\n }\n\n return { packages, info }\n}\n\n/**\n * Read the locally-running package context, searched upward from `cwd`. Prefers\n * the `.infra-kit/dev-context/` fragment DIRECTORY (merged via\n * {@link readFragmentDir}); when it is absent, falls back to the legacy single\n * `.infra-kit/dev-context.json` file (read as before \u2014 no per-package release);\n * when neither exists \u2192 empty context (frontend-only, every route resolves cloud).\n */\nexport const readLocalContext = (cwd: string): LocalContext => {\n const dir = findUp(cwd, DEV_CONTEXT_DIR)\n\n if (dir) return readFragmentDir(dir)\n\n const legacy = findUp(cwd, DEV_CONTEXT_FILE)\n\n if (!legacy) return emptyLocalContext()\n\n try {\n return { packages: new Set(extractPackages(JSON.parse(fs.readFileSync(legacy, 'utf-8')))), info: new Map() }\n } catch {\n return emptyLocalContext()\n }\n}\n\n/**\n * Read the set of locally-running packages (searched upward from `cwd`). Thin\n * wrapper over {@link readLocalContext} preserving the historical `Set`-returning\n * contract. Absent dev-context \u2192 empty set (frontend-only cloud resolution).\n */\nexport const readLocalSet = (cwd: string): ReadonlySet<string> => {\n return readLocalContext(cwd).packages\n}\n\n/** Current git branch of `cwd` (raw, un-slugified). */\nconst readGitBranch = (cwd: string): string => {\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n return execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd, encoding: 'utf-8' }).trim()\n}\n\n/**\n * An OS-assigned free TCP port on 127.0.0.1 \u2014 the per-worktree dev-server port (mirrors the\n * backend's `listen(0)`). This probes then releases the port, so there is a small TOCTOU window\n * before Vite binds it; Vite's default `strictPort: false` absorbs a lost race by stepping to the\n * next free port. Only a consumer that sets `strictPort: true` would hard-fail on the rare collision.\n */\nconst getFreePort = (): Promise<number> => {\n return new Promise((resolve, reject) => {\n const srv = net.createServer()\n\n srv.unref()\n srv.on('error', reject)\n srv.listen(0, '127.0.0.1', () => {\n const address = srv.address()\n const port = typeof address === 'object' && address !== null ? address.port : 0\n\n srv.close(() => {\n return resolve(port)\n })\n })\n })\n}\n\n/** Env var carrying the runner-assigned `{ \"<ui-package>\": <port> }` map (Layer B). */\nconst UI_PORTS_ENV = 'INFRA_KIT_UI_PORTS'\n\n/** This package's `package.json` `name`, or `null` (unreadable / nameless). */\nconst readPackageName = (cwd: string): string | null => {\n try {\n const parsed = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf-8')) as { name?: unknown }\n\n return typeof parsed.name === 'string' ? parsed.name : null\n } catch {\n return null\n }\n}\n\n/**\n * What the runner assigned THIS UI. `alias` is present only in the widened record form, i.e. only when the\n * runner both assigned the port AND registered the hostname \u2014 which is exactly the condition for pointing\n * HMR at that hostname. The legacy bare-number form yields no alias.\n */\ninterface ManagedUi {\n port: number\n alias?: string\n}\n\n/**\n * What `infra-kit dev` assigned THIS UI via `INFRA_KIT_UI_PORTS` (Layer B), or `null` when the map is\n * absent / this package isn't in it / it's malformed. Present \u2192 the helper binds the port with\n * `strictPort` so vite lands on exactly the port the runner already aliased. Absent (a standalone\n * `vite dev`) \u2192 the caller falls back to a free port, byte-identical to today.\n *\n * Accepts BOTH the widened `{ port, alias }` record and the legacy bare `<port>` number an older runner\n * writes \u2014 a new helper paired with an old CLI must still bind the assigned port.\n */\nconst resolveManagedUi = (cwd: string): ManagedUi | null => {\n const raw = process.env[UI_PORTS_ENV]\n\n if (raw == null || raw === '') return null\n\n const name = readPackageName(cwd)\n\n if (name == null) return null\n\n try {\n const entry = (JSON.parse(raw) as Record<string, unknown>)[name]\n\n if (typeof entry === 'number') return { port: entry }\n\n if (entry === null || typeof entry !== 'object') return null\n\n const { port, alias } = entry as { port?: unknown; alias?: unknown }\n\n if (typeof port !== 'number') return null\n\n return { port, alias: typeof alias === 'string' ? alias : undefined }\n } catch {\n return null\n }\n}\n\n/** The port an `https://` alias is served on \u2014 never spelled out in a URL, and what the HMR client dials. */\nconst HTTPS_PORT = 443\n\n/**\n * Vite's `server.hmr` override, pointing the HMR client at the alias instead of at the raw dev-server port.\n * The page is loaded over `https://<alias>`, so its websocket must be `wss://` on the same origin or the\n * browser blocks it as mixed content; `clientPort` is the proxy's implicit `:443`, not vite's bound port.\n */\nexport interface InfraKitViteHmr {\n protocol: 'wss'\n host: string\n clientPort: number\n}\n\n/**\n * Resolve a package's `dev` block into a ready-made Vite `server` config: a per-worktree dev-server\n * `port` plus the `proxy` map. Loads the package's `infra-kit.config.ts`, merges the local dev set\n * from the `.infra-kit/dev-context/` fragment directory, and interpolates the local/cloud templates.\n * `<env>` comes from `INFRA_KIT_ENV`; `<release>` from each package's runner-recorded fragment when\n * present, else the slugified git branch (computed lazily, only when a local route needs it).\n *\n * `port` defaults to a fresh OS-assigned free port so simultaneous git worktrees never collide on\n * Vite's `5173` (override via `options.port`). `host` defaults to {@link LOOPBACK_V4} so the portless\n * alias can actually reach it (override via `options.host` for containers/LAN). `hmr` is emitted only\n * when `infra-kit dev` registered an alias for this UI, so a bare `vite dev` keeps vite's own HMR\n * defaults. Pass `command` so `build` is a no-op (empty proxy, no port) \u2014 a build ignores `server` and\n * proxy resolution would otherwise fail-fast on a cloud route with no sourced env.\n *\n * @example\n * // vite.config.ts \u2014 the whole `server` field is the helper's output\n * import { infraKitDev } from 'infra-kit/vite'\n * export default defineConfig(async ({ command }) => ({ server: await infraKitDev({ command }) }))\n */\nexport const infraKitDev = async (\n options: InfraKitDevOptions = {},\n): Promise<{\n port?: number\n host?: string | boolean\n strictPort?: boolean\n hmr?: InfraKitViteHmr\n proxy: InfraKitViteProxy\n}> => {\n const cwd = options.cwd ?? process.cwd()\n\n // A build ignores `server`; skip the port + proxy work (proxy resolution would fail-fast on a\n // cloud route with no sourced env).\n if (options.command === 'build') return { proxy: {} }\n\n // Port precedence: explicit `options.port` > the runner-assigned Layer-B port (bound `strictPort` so\n // vite lands on exactly the aliased port) > a fresh free port (today's default; the portless-off path).\n const managed = options.port == null ? resolveManagedUi(cwd) : null\n const port = options.port ?? managed?.port ?? (await getFreePort())\n const strictPort = managed != null\n const host = options.host ?? LOOPBACK_V4\n\n // Override HMR ONLY when the runner handed us the alias it registered. A bare `vite dev` (no runner)\n // has no alias, and a computable hostname is not a registered one \u2014 pointing the HMR client at a\n // hostname nothing resolves would break hot reload on a path that works today.\n const hmr: InfraKitViteHmr | undefined =\n managed?.alias == null ? undefined : { protocol: 'wss', host: managed.alias, clientPort: HTTPS_PORT }\n const server = { port, host, ...(strictPort ? { strictPort } : {}), ...(hmr ? { hmr } : {}) }\n const dev = await loadDev(cwd)\n\n if (!dev?.proxy) return { ...server, proxy: {} }\n\n const { packages: localSet, info: localInfo } = readLocalContext(cwd)\n const env = process.env[INFRA_KIT_ENV]\n const authHeader = buildBasicAuthHeader(process.env, options.basicAuth)\n const getRelease = once(() => {\n // Mirrors the dev-server's `readAppRelease`: outside a git repo both sides must land on the SAME\n // label, or this target names a host the runner never aliased.\n try {\n return slugifyRelease(readGitBranch(cwd)) || DEFAULT_RELEASE_SLUG\n } catch {\n return DEFAULT_RELEASE_SLUG\n }\n })\n\n return {\n ...server,\n proxy: resolveProxyConfig({ proxy: dev.proxy, localSet, env, getRelease, authHeader, localInfo }),\n }\n}\n\n/**\n * Convenience wrapper returning just the proxy map (for spreading into\n * `server.proxy` directly). Equivalent to `(await infraKitDev(options)).proxy`.\n */\nexport const infraKitProxy = async (options: InfraKitDevOptions = {}): Promise<InfraKitViteProxy> => {\n return (await infraKitDev(options)).proxy\n}\n", "import { z } from 'zod'\n\n/**\n * Schema for the resolved (post-factory) package config object. `strictObject`\n * rejects unknown keys so typos in `infra-kit.config.ts` surface as validation\n * errors instead of being silently ignored.\n *\n * Kept in its own module \u2014 separate from the public `defineConfig`/types entry \u2014\n * so the published `infra-kit` type surface stays free of a `zod` import.\n */\nexport const packageConfigSchema = z.strictObject({\n requiredScripts: z.array(z.string().min(1)).optional(),\n requiredFiles: z.array(z.string().min(1)).optional(),\n turbo: z\n .strictObject({\n requiredTasks: z.array(z.string().min(1)).optional(),\n })\n .optional(),\n dev: z\n .strictObject({\n proxy: z\n .strictObject({\n templates: z.strictObject({\n local: z.string().min(1),\n cloud: z.string().min(1),\n }),\n routes: z.record(\n z.string().min(1),\n z\n .strictObject({\n packageName: z.string().min(1),\n from: z.array(z.enum(['local', 'cloud'])).min(1),\n default: z.enum(['local', 'cloud']).optional(),\n })\n .refine(\n (route) => {\n return route.from.length <= 1 || route.default !== undefined\n },\n {\n message: 'default is required when `from` has more than one source',\n },\n )\n .refine(\n (route) => {\n return route.default === undefined || route.from.includes(route.default)\n },\n {\n message: 'default must be listed in `from`',\n },\n ),\n ),\n })\n .optional(),\n })\n .optional(),\n})\n"],
|
|
5
|
-
"mappings": "sDAAA,OAAS,UAAAA,MAAc,cACvB,OAAS,gBAAAC,MAAoB,qBAC7B,OAAOC,MAAQ,UACf,OAAOC,MAAS,WAChB,OAAOC,MAAU,YACjB,OAAOC,MAAa,eACpB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,KAAAC,MAAS,MCPlB,OAAS,KAAAC,MAAS,MAUX,IAAMC,EAAsBD,EAAE,aAAa,CAChD,gBAAiBA,EAAE,MAAMA,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE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a,CAAE,WAAAA,CAAW,EAAI,CAAC,EAAI,GAAIG,EAAM,CAAE,IAAAA,CAAI,EAAI,CAAC,CAAG,EACtFE,EAAM,MAAMC,EAAQ9B,CAAG,EAE7B,GAAI,CAAC6B,GAAK,MAAO,MAAO,CAAE,GAAGD,EAAQ,MAAO,CAAC,CAAE,EAE/C,GAAM,CAAE,SAAUG,EAAU,KAAMC,CAAU,EAAIC,EAAiBjC,CAAG,EAC9DkC,EAAMlB,EAAQ,IAAImB,CAAa,EAC/BC,EAAaC,EAAqBrB,EAAQ,IAAKM,EAAQ,SAAS,EAChEgB,EAAaC,EAAK,IAAM,CAG5B,GAAI,CACF,OAAOC,EAAezC,EAAcC,CAAG,CAAC,GAAKyC,CAC/C,MAAQ,CACN,OAAOA,CACT,CACF,CAAC,EAED,MAAO,CACL,GAAGb,EACH,MAAOc,EAAmB,CAAE,MAAOb,EAAI,MAAO,SAAAE,EAAU,IAAAG,EAAK,WAAAI,EAAY,WAAAF,EAAY,UAAAJ,CAAU,CAAC,CAClG,CACF,EAMaW,GAAgB,MAAOrB,EAA8B,CAAC,KACzD,MAAMD,GAAYC,CAAO,GAAG",
|
|
6
|
-
"names": ["Buffer", "execFileSync", "fs", "net", "path", "process", "pathToFileURL", "z", "z", "packageConfigSchema", "route", "INFRA_KIT_ENV", "PACKAGE_CONFIG_FILE", "DEV_CONTEXT_DIR", "path", "DEV_CONTEXT_FILE", "devContextFragmentSchema", "z", "buildBasicAuthHeader", "env", "override", "username", "password", "Buffer", "interpolate", "template", "values", "DEFAULT_HTTP_PORT", "LOOPBACK_V4", "withProxyPort", "target", "proxyPort", "url", "grafted", "LEGACY_SELF_SPAWNED_PORT_FLOOR", "resolveLegacyTarget", "resolveLocalTarget", "args", "route", "templates", "env", "getRelease", "info", "slugifyHostLabel", "pickSource", "localSet", "fallback", "LOOPBACK_HOSTNAMES", "isLoopbackTarget", "hostname", "bare", "resolveRoute", "routePath", "localInfo", "INFRA_KIT_ENV", "resolveProxyConfig", "proxy", "authHeader", "result", "headers", "entry", "once", "fn", "cached", "loadDev", "cwd", "configPath", "path", "PACKAGE_CONFIG_FILE", "fs", "stat", "rawExport", "pathToFileURL", "resolved", "parsed", "packageConfigSchema", "z", "extractPackages", "v", "candidate", "findUp", "start", "relative", "dir", "parent", "emptyLocalContext", "isFragmentWriterAlive", "pid", "process", "error", "readFragmentDir", "entries", "packages", "name", "devContextFragmentSchema", "readLocalContext", "DEV_CONTEXT_DIR", "legacy", "DEV_CONTEXT_FILE", "readGitBranch", "cwd", "execFileSync", "getFreePort", "resolve", "reject", "srv", "net", "address", "port", "UI_PORTS_ENV", "readPackageName", "parsed", "fs", "path", "resolveManagedUi", "raw", "process", "name", "entry", "alias", "HTTPS_PORT", "infraKitDev", "options", "managed", "strictPort", "host", "LOOPBACK_V4", "hmr", "server", "dev", "loadDev", "localSet", "localInfo", "readLocalContext", "env", "INFRA_KIT_ENV", "authHeader", "buildBasicAuthHeader", "getRelease", "once", "slugifyRelease", "DEFAULT_RELEASE_SLUG", "resolveProxyConfig", "infraKitProxy"]
|
|
7
|
-
}
|
package/dist/chunk-Z6KTUVIC.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var a=e=>e,n={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},c={requiredScripts:["build","dev","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},f=(e,t=n)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import{z as r}from"zod";var p="vendor.config.ts",o=r.string().refine(e=>{let t=/^(?:[/\\]|[a-z]:)/i.test(e),i=e.split(/[\\/]/).includes("..");return!t&&!i&&e.trim().length>0},{message:'must be a non-empty repo-relative path without ".." segments'}),s=r.object({name:r.string(),source:o,target:o,type:r.enum(["file","directory"]),vendored:r.boolean().optional()}),g=r.object({copy:r.array(s)}).strict(),l=e=>e;export{a,n as b,c,f as d,p as e,g as f,l as g};
|
|
2
|
-
//# sourceMappingURL=chunk-Z6KTUVIC.js.map
|