infra-kit 0.1.133 → 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-RXEMP3VI.js → chunk-4MRYIYJP.js} +3 -3
- package/dist/chunk-4MRYIYJP.js.map +7 -0
- 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-NC2TIQ3M.js +4 -0
- package/dist/chunk-NC2TIQ3M.js.map +7 -0
- 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-6EPRH34O.js +0 -2
- package/dist/chunk-6EPRH34O.js.map +0 -7
- package/dist/chunk-6FDGBQGX.js +0 -2
- package/dist/chunk-6FDGBQGX.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-RSF5XAQJ.js +0 -4
- package/dist/chunk-RSF5XAQJ.js.map +0 -7
- package/dist/chunk-RXEMP3VI.js.map +0 -7
- package/dist/chunk-V37MZDFR.js +0 -3
- package/dist/chunk-V37MZDFR.js.map +0 -7
- package/dist/chunk-WSO6DN6Q.js +0 -220
- package/dist/chunk-WSO6DN6Q.js.map +0 -7
- package/dist/chunk-Z6KTUVIC.js +0 -2
- package/dist/chunk-Z6KTUVIC.js.map +0 -7
- package/dist/dev-wizard-run-TNA5YI7P.js +0 -2
- package/dist/dev-wizard-run-TNA5YI7P.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-3OMHS5RE.js.map → chunk-E2SEBLGJ.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
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as l}from"./chunk-4MRYIYJP.js";import{I as k,Q as w,v as d,w as v,x,y}from"./chunk-KZP2SY37.js";import{e as b}from"./chunk-CHETBZ6M.js";import S from"@inquirer/checkbox";import R from"@inquirer/confirm";import N,{Separator as $}from"@inquirer/select";import{loadDev as O}from"@slip-stream-kit/config/internal";import B from"node:path";import h from"node:process";var f=e=>e.split("/")[0],W=e=>new Map(e.apps.map(r=>[r.name,r])),D=(e,r)=>{let a={},s=!1;for(let t of e.backends){let n=t.localCapable&&t.ownerApp!=null&&r.has(t.ownerApp);n||(s=!0);for(let o of t.routes)a[o]=n?"local":"cloud"}return{overrides:a,anyCloud:s}},z=(e,r)=>{let a=W(r),s=e.targets.filter(c=>c.endsWith("/ui")),t=new Set(e.targets.filter(c=>c.endsWith("/api")).map(f)),n={},o=!1;for(let c of s){let u=a.get(f(c)),{overrides:p,anyCloud:i}=u?D(u,t):{overrides:{},anyCloud:!1};i&&(o=!0),n[c]=Object.keys(p).length>0?{proxy:p}:{}}for(let c of t)n[`${c}/api`]??={};return{presetDef:{apps:n,cmux:e.cmux},anyCloudRoute:o,targetKeys:Object.keys(n).sort()}},M=(e,r,a)=>{let s=W(a),t=[...new Set(e.targetKeys.map(f))].sort(),n=new Set(e.targetKeys),o=t.every(u=>{let p=s.get(u);if(!p)return!1;let i=!p.hasUi||n.has(`${u}/ui`),m=!p.hasApi||n.has(`${u}/api`);return i&&m}),c=[`--app=${t.join(",")}`];return r.watch&&c.push("--watch"),r.cmux&&c.push("--cmux"),{flags:c.join(" "),exact:o}};var g={output:h.stderr,clearPromptOnDone:!0},j={select:e=>N({message:e.message,choices:e.choices,default:e.default},g),checkbox:e=>S({message:e.message,choices:e.choices},g),confirm:e=>R({message:e.message,default:e.default},g)},q=(e,r)=>{let a=new Map;for(let[s,t]of Object.entries(e)){let n=a.get(t.packageName),o=t.from.includes("local");n?(n.routes.push(s),n.localCapable=n.localCapable||o):a.set(t.packageName,{packageName:t.packageName,routes:[s],localCapable:o,ownerApp:r.get(t.packageName)})}return[...a.values()]},K=async e=>{let r=x(e),a=y(e),s=await w(),t=new Map(r.map(i=>[i.packageName,i.name])),n=new Map(r.map(i=>[i.name,i.packageName])),o=new Set(a.map(i=>i.name)),c=new Set(r.map(i=>i.name)),u=[...new Set([...c,...o])].sort();return{apps:await Promise.all(u.map(async i=>{let m=o.has(i),P=m?(await O(B.join(e,"apps",i,"ui")))?.proxy?.routes:void 0;return{name:i,hasApi:c.has(i),hasUi:m,apiPackage:n.get(i),backends:P?q(P,t):[]}})),presets:Object.keys(s.devServersPresets??{}),environments:s.environments}},U=e=>{let r=[];for(let a of e.apps){if(a.hasUi){let s=a.backends.flatMap(n=>n.routes),t=s.length>0?`frontend \u2014 proxies ${[...s].sort().join(", ")}`:"frontend";r.push({name:`${a.name}/ui`,value:`${a.name}/ui`,description:t})}a.hasApi&&r.push({name:`${a.name}/api`,value:`${a.name}/api`,description:"backend"})}return r},_=e=>{let r={api:e.apps.filter(t=>t.hasApi).map(t=>t.name),ui:e.apps.filter(t=>t.hasUi).map(t=>t.name)},a={},s=new Map;for(let t of e.apps){t.apiPackage!=null&&(a[t.name]=t.apiPackage);for(let n of t.backends)for(let o of n.routes)s.set(`${t.name} ${o}`,n.packageName)}return{discovered:r,apiPkgByApp:a,routePkg:(t,n)=>s.get(`${t} ${n}`)}},I=(e,r)=>k({__wizard__:e},_(r)).map(a=>a.message),C=async(e,r)=>{if(r.apps.length===0)return d.warn("No apps discovered to run."),null;let a=await e.checkbox({message:"\u{1F4E6} Which packages?",choices:U(r)});if(a.length===0)return d.warn("No packages selected."),null;let s=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!1}),t=await e.confirm({message:"\u{1F9E9} Run each app in its own cmux pane?",default:!1}),n={targets:a,watch:s,cmux:t},o=z(n,r);o.anyCloudRoute&&(n.env=await e.select({message:"\u2601\uFE0F Point cloud routes at which environment?",choices:r.environments.map(p=>({name:p,value:p}))}),h.env[b]=n.env);let c=I(o.presetDef,r);if(c.length>0){d.warn("\u26A0\uFE0F Proxy audit found issues with this selection:");for(let p of c)d.warn(` \u2022 ${p}`);return null}E(o,n,r);let u=o.targetKeys.filter(p=>p.endsWith("/api")).map(p=>p.split("/")[0]);return t&&u.length>0?{include:u,presetDef:o.presetDef,watch:s,cmux:!0}:(t&&d.info("\u2139\uFE0F cmux needs at least one local backend (panes are backend-only) \u2014 running in-process instead."),{presetDef:o.presetDef,watch:s,cmux:!1})},E=(e,r,a)=>{l.setInteractive();let s=M(e,r,a);l.addOption(s.flags,!0),l.print(),s.exact||d.info("\u2139\uFE0F This part-level selection has no exact single-flag form \u2014 save it as a devPreset to reproduce it.")},T=async(e,r)=>{let a=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!1});return l.setInteractive(),l.addOption(r,!0),a&&l.addOption("--watch",!0),l.print(),{preset:r,watch:a,cmux:!1}},A=" manual",F=async(e,r)=>{if(r.presets.length===0)return C(e,r);let a=await e.select({message:"\u{1F680} Start from a preset, or configure manually?",choices:[...r.presets.map(s=>({name:s,value:s})),new $(" "),{name:"Manual (custom)\u2026",value:A}]});return a===A?C(e,r):T(e,a)},se=async(e=j,r=v(h.cwd()))=>F(e,await K(r));export{A as MANUAL_CHOICE,I as auditManualPlan,j as defaultPrompts,K as gatherWizardModel,se as runDevWizard,F as runWizardFlow};
|
|
2
|
+
//# sourceMappingURL=dev-wizard-run-5HQOGE3R.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/dev/dev-wizard-run.ts", "../src/dev/dev-wizard.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Impure driver for the interactive `infra-kit dev` wizard: filesystem/config discovery, the inquirer\n * prompt flow (step-0 preset-or-manual, then the manual matrix), the pre-flight proxy audit, and the\n * `commandEcho` teaching line. The pure answer\u2192plan mapping lives in {@link file://./dev-wizard.ts}.\n *\n * Prompts are behind the injectable {@link WizardPrompts} seam so the flow is testable without a TTY.\n * This module is reached ONLY from the bare-invocation TTY branch of the entry point; every flagged /\n * non-TTY / `--json` / MCP invocation bypasses it entirely.\n */\nimport inquirerCheckbox from '@inquirer/checkbox'\nimport inquirerConfirm from '@inquirer/confirm'\nimport inquirerSelect, { Separator } from '@inquirer/select'\nimport { loadDev } from '@slip-stream-kit/config/internal'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { discoverApiApps, discoverUiApps, findMonorepoRoot } from 'src/dev/discovery'\nimport { commandEcho } from 'src/lib/command-echo'\nimport { INFRA_KIT_ENV_VAR } from 'src/lib/constants'\nimport { getInfraKitConfig } from 'src/lib/infra-kit-config'\nimport type { DevPreset } from 'src/lib/infra-kit-config'\nimport { logger } from 'src/lib/logger'\n\nimport { deriveManualPlan, equivalentCommand } from './dev-wizard.js'\nimport type { DerivedPlan, ManualSelection, ProxyBackend, WizardApp, WizardModel } from './dev-wizard.js'\nimport { validatePresetProxy } from './presets.js'\nimport type { DiscoveredParts, PresetProxyContext } from './presets.js'\n\n/** A wizard prompt choice \u2014 all values are strings, so the seam needs no generics. */\nexport interface WizardChoice {\n name: string\n value: string\n description?: string\n checked?: boolean\n disabled?: boolean | string\n}\n\n/**\n * Injectable prompt seam (a string-valued subset of `@inquirer/*`). The default implementation\n * ({@link defaultPrompts}) delegates to the real prompts, rendering to stderr so the dev-server's\n * stdout stays clean. Tests pass a scripted object.\n */\nexport interface WizardPrompts {\n select: (cfg: { message: string; choices: (WizardChoice | Separator)[]; default?: string }) => Promise<string>\n checkbox: (cfg: { message: string; choices: WizardChoice[] }) => Promise<string[]>\n confirm: (cfg: { message: string; default?: boolean }) => Promise<boolean>\n}\n\n/**\n * Shared `@inquirer/*` context. Rendered to stderr (mirrors the bare-`infra-kit` command palette).\n *\n * `clearPromptOnDone` erases each answered prompt instead of leaving a `\u2714 <question> <answer>` line\n * behind, so the wizard collapses to nothing once it finishes and the dev-server's ready header lands\n * at the top of a clean screen. The choices are not lost: {@link echoManual} / {@link runPresetBranch}\n * print the equivalent flag command, which is the durable record of what was picked.\n */\nconst promptContext = { output: process.stderr, clearPromptOnDone: true }\n\n/** Real `@inquirer/*` prompts, rendered to stderr and erased once answered. */\nexport const defaultPrompts: WizardPrompts = {\n select: (cfg) => {\n return inquirerSelect({ message: cfg.message, choices: cfg.choices, default: cfg.default }, promptContext)\n },\n checkbox: (cfg) => {\n return inquirerCheckbox({ message: cfg.message, choices: cfg.choices }, promptContext)\n },\n confirm: (cfg) => {\n return inquirerConfirm({ message: cfg.message, default: cfg.default }, promptContext)\n },\n}\n\n/** What the wizard hands back to the entry point (merged into `DevServerOptions`), or null on cancel. */\nexport interface WizardResult {\n /** Named preset (preset branch) \u2014 passed through as `options.preset`. */\n preset?: string\n /** In-memory preset (manual branch, non-cmux) \u2014 passed through as `options.presetDef`. */\n presetDef?: DevPreset\n /**\n * App-name include list for the cmux path only: which discovered API apps get a pane. Paired with\n * `presetDef`, which tells each pane the exact parts to run. An app selected UI-only gets no pane\n * (cmux panes are opened per API app). Unset for the non-cmux manual path.\n */\n include?: string[]\n watch: boolean\n cmux: boolean\n}\n\n/** Group one frontend's `dev.proxy.routes` into {@link ProxyBackend}s keyed by backend package. */\nconst groupBackends = (\n routes: Record<string, { packageName: string; from: readonly string[] }>,\n ownerByPkg: Map<string, string>,\n): ProxyBackend[] => {\n const byPkg = new Map<string, ProxyBackend>()\n\n for (const [route, def] of Object.entries(routes)) {\n const existing = byPkg.get(def.packageName)\n const localCapable = def.from.includes('local')\n\n if (existing) {\n existing.routes.push(route)\n existing.localCapable = existing.localCapable || localCapable\n } else {\n byPkg.set(def.packageName, {\n packageName: def.packageName,\n routes: [route],\n localCapable,\n ownerApp: ownerByPkg.get(def.packageName),\n })\n }\n }\n\n return [...byPkg.values()]\n}\n\n/** Discover apps + configs and assemble the {@link WizardModel} (backends resolved per frontend). */\nexport const gatherWizardModel = async (root: string): Promise<WizardModel> => {\n const apiApps = discoverApiApps(root)\n const uiApps = discoverUiApps(root)\n const config = await getInfraKitConfig()\n\n const ownerByPkg = new Map(\n apiApps.map((a) => {\n return [a.packageName, a.name] as const\n }),\n )\n const apiPkgByName = new Map(\n apiApps.map((a) => {\n return [a.name, a.packageName] as const\n }),\n )\n const uiNames = new Set(\n uiApps.map((a) => {\n return a.name\n }),\n )\n const apiNames = new Set(\n apiApps.map((a) => {\n return a.name\n }),\n )\n const allNames = [...new Set([...apiNames, ...uiNames])].sort()\n\n const apps: WizardApp[] = await Promise.all(\n allNames.map(async (name): Promise<WizardApp> => {\n const hasUi = uiNames.has(name)\n const routes = hasUi ? (await loadDev(path.join(root, 'apps', name, 'ui')))?.proxy?.routes : undefined\n\n return {\n name,\n hasApi: apiNames.has(name),\n hasUi,\n apiPackage: apiPkgByName.get(name),\n backends: routes ? groupBackends(routes, ownerByPkg) : [],\n }\n }),\n )\n\n return { apps, presets: Object.keys(config.devServersPresets ?? {}), environments: config.environments }\n}\n\n/**\n * Build the flat `<app>/<part>` checkbox choices, grouped per app as `ui` then `api`. A frontend choice\n * carries a description of the routes it proxies, so ticking the matching api part reads as \"run that\n * route locally\". This is the checkbox the user directly picks their targets from.\n *\n * Nothing starts checked: the manual branch is opt-in, so a run only ever launches what was explicitly\n * ticked. Pre-checking every part would make the fast path (accept the defaults) boot the whole monorepo\n * \u2014 the exact opposite of why someone reached for \"Manual\" over a preset.\n */\nconst buildPartChoices = (model: WizardModel): WizardChoice[] => {\n const choices: WizardChoice[] = []\n\n for (const app of model.apps) {\n if (app.hasUi) {\n const routes = app.backends.flatMap((b) => {\n return b.routes\n })\n const description = routes.length > 0 ? `frontend \u2014 proxies ${[...routes].sort().join(', ')}` : 'frontend'\n\n choices.push({ name: `${app.name}/ui`, value: `${app.name}/ui`, description })\n }\n if (app.hasApi) {\n choices.push({ name: `${app.name}/api`, value: `${app.name}/api`, description: 'backend' })\n }\n }\n\n return choices\n}\n\n/** Build the audit context from the gathered model (no re-reading of configs). */\nconst buildAuditContext = (model: WizardModel): PresetProxyContext => {\n const discovered: DiscoveredParts = {\n api: model.apps\n .filter((a) => {\n return a.hasApi\n })\n .map((a) => {\n return a.name\n }),\n ui: model.apps\n .filter((a) => {\n return a.hasUi\n })\n .map((a) => {\n return a.name\n }),\n }\n const apiPkgByApp: Record<string, string> = {}\n const routeToPkg = new Map<string, string>()\n\n for (const app of model.apps) {\n // Map EVERY discovered api app to its own api package \u2014 including api-only apps a frontend proxies\n // to cross-app \u2014 so `launchedPkgs` in validatePresetProxy is faithful (mirrors preset-proxy-check.ts).\n // Deriving this from proxy backends alone would miss api-only owners and false-positive the audit.\n if (app.apiPackage != null) apiPkgByApp[app.name] = app.apiPackage\n for (const b of app.backends) {\n for (const route of b.routes) {\n routeToPkg.set(`${app.name} ${route}`, b.packageName)\n }\n }\n }\n\n return {\n discovered,\n apiPkgByApp,\n routePkg: (app, route) => {\n return routeToPkg.get(`${app} ${route}`)\n },\n }\n}\n\n/**\n * Run the assembled plan through the SAME proxy-locality rule the root audit uses. Returns issue\n * messages (empty when clean). Catches a `local` override whose backend won't launch \u2014 the wizard's\n * derivation launches owners, so a hit means the backend has no discoverable owning app.\n */\nexport const auditManualPlan = (presetDef: DevPreset, model: WizardModel): string[] => {\n return validatePresetProxy({ __wizard__: presetDef }, buildAuditContext(model)).map((i) => {\n return i.message\n })\n}\n\n/** The manual-branch flow: app + per-app proxy + env + watch + cmux \u2192 audited plan \u2192 echo. */\nconst runManualBranch = async (prompts: WizardPrompts, model: WizardModel): Promise<WizardResult | null> => {\n if (model.apps.length === 0) {\n logger.warn('No apps discovered to run.')\n\n return null\n }\n\n const selectedTargets = await prompts.checkbox({ message: '\uD83D\uDCE6 Which packages?', choices: buildPartChoices(model) })\n\n if (selectedTargets.length === 0) {\n logger.warn('No packages selected.')\n\n return null\n }\n\n const watch = await prompts.confirm({ message: '\uD83D\uDC40 Rebuild & restart on save (watch)?', default: false })\n const cmux = await prompts.confirm({ message: '\uD83E\uDDE9 Run each app in its own cmux pane?', default: false })\n\n const selection: ManualSelection = { targets: selectedTargets, watch, cmux }\n const plan = deriveManualPlan(selection, model)\n\n if (plan.anyCloudRoute) {\n selection.env = await prompts.select({\n message: '\u2601\uFE0F Point cloud routes at which environment?',\n choices: model.environments.map((e) => {\n return { name: e, value: e }\n }),\n })\n process.env[INFRA_KIT_ENV_VAR] = selection.env\n }\n\n const issues = auditManualPlan(plan.presetDef, model)\n\n if (issues.length > 0) {\n logger.warn('\u26A0\uFE0F Proxy audit found issues with this selection:')\n for (const issue of issues) {\n logger.warn(` \u2022 ${issue}`)\n }\n\n return null\n }\n\n echoManual(plan, selection, model)\n\n // cmux opens one pane per selected API app. `include` picks WHICH apps get a pane; `presetDef` tells\n // each pane exactly which of its parts to run. Without the latter a pane runs `--app=<name>`, which\n // expands to every part the app has \u2014 silently starting a UI the user just unticked.\n const apiApps = plan.targetKeys\n .filter((k) => {\n return k.endsWith('/api')\n })\n .map((k) => {\n return k.split('/')[0]!\n })\n\n // An empty include would collapse to `null` in `normalizeAppInclude` and make cmux run EVERY api app,\n // so a cmux run with no selected backends (e.g. an all-frontend selection) falls back to in-process.\n if (cmux && apiApps.length > 0) {\n return { include: apiApps, presetDef: plan.presetDef, watch, cmux: true }\n }\n\n if (cmux) {\n logger.info('\u2139\uFE0F cmux needs at least one local backend (panes are backend-only) \u2014 running in-process instead.')\n }\n\n return { presetDef: plan.presetDef, watch, cmux: false }\n}\n\n/** Print the equivalent flag command (and, for a part-level selection, the save-as-preset hint). */\nconst echoManual = (plan: DerivedPlan, selection: ManualSelection, model: WizardModel): void => {\n commandEcho.setInteractive()\n\n const eq = equivalentCommand(plan, selection, model)\n\n commandEcho.addOption(eq.flags, true)\n commandEcho.print()\n\n if (!eq.exact) {\n logger.info('\u2139\uFE0F This part-level selection has no exact single-flag form \u2014 save it as a devPreset to reproduce it.')\n }\n}\n\n/** The preset-branch flow: run a named preset, asking only whether to watch (presets can't encode it). */\nconst runPresetBranch = async (prompts: WizardPrompts, preset: string): Promise<WizardResult> => {\n const watch = await prompts.confirm({ message: '\uD83D\uDC40 Rebuild & restart on save (watch)?', default: false })\n\n commandEcho.setInteractive()\n commandEcho.addOption(preset, true)\n if (watch) commandEcho.addOption('--watch', true)\n commandEcho.print()\n\n return { preset, watch, cmux: false }\n}\n\n/** Sentinel value for the \"Manual (custom)\" step-0 choice (a preset name can never be empty). */\nexport const MANUAL_CHOICE = ' manual'\n\n/**\n * Drive the wizard's branch flow over an ALREADY-gathered model (no disk/config access). Split from\n * {@link runDevWizard} so the flow is unit-testable with scripted prompts + a fixture model.\n */\nexport const runWizardFlow = async (prompts: WizardPrompts, model: WizardModel): Promise<WizardResult | null> => {\n if (model.presets.length === 0) {\n return runManualBranch(prompts, model)\n }\n\n const choice = await prompts.select({\n message: '\uD83D\uDE80 Start from a preset, or configure manually?',\n choices: [\n ...model.presets.map((p) => {\n return { name: p, value: p }\n }),\n new Separator(' '),\n { name: 'Manual (custom)\u2026', value: MANUAL_CHOICE },\n ],\n })\n\n return choice === MANUAL_CHOICE ? runManualBranch(prompts, model) : runPresetBranch(prompts, choice)\n}\n\n/**\n * Gather the model from disk/config, then drive the wizard flow, returning the resolved run options (or\n * null on cancel / empty selection). The entry point calls this on a bare TTY `infra-kit dev`.\n */\nexport const runDevWizard = async (\n prompts: WizardPrompts = defaultPrompts,\n root: string = findMonorepoRoot(process.cwd()),\n): Promise<WizardResult | null> => {\n return runWizardFlow(prompts, await gatherWizardModel(root))\n}\n", "/**\n * Pure core of the interactive `infra-kit dev` wizard (the no-args, TTY path).\n *\n * The wizard is FRONTEND-CENTRIC: you pick apps to run, and for each frontend you choose, per backend\n * it proxies to, whether that backend runs LOCALLY (its `/api` is launched \u2192 the route resolves local)\n * or stays CLOUD (not launched \u2192 the route proxies to the `<env>` cloud target). A backend runs iff a\n * frontend points at it locally, or its app is selected and not demoted to cloud. This module turns\n * those answers into an in-memory {@link DevPreset} the runner consumes verbatim (part-level targets\n * that the app-name-only `--app` include cannot express) \u2014 and is side-effect-free so the mapping is\n * fully unit-testable. The impure I/O (discovery, inquirer prompts, audit, launch) lives in\n * {@link file://./dev-wizard-run.ts}.\n */\nimport type { DevPreset, ProxySource } from 'src/lib/infra-kit-config'\n\n/**\n * One backend a frontend's proxy routes can be pointed at, grouped by the backend package. A frontend\n * that maps `/api` and `/media` to the same package yields ONE {@link ProxyBackend} with both routes \u2014\n * launching the package flips every one of its `local`-capable routes together (see `pickSource`).\n */\nexport interface ProxyBackend {\n /** Backend package name (a route's `packageName`). */\n packageName: string\n /** Route paths that resolve to this package (for display + the audit's per-route overrides). */\n routes: string[]\n /** True when at least one of `routes` lists `local` in its `from` capabilities \u2014 i.e. it is toggleable. A `false` backend is fixed-cloud, shown as info. */\n localCapable: boolean\n /** App folder whose `api` package is {@link packageName}, or undefined when no discovered app owns it (a `local` choice then has nothing to launch \u2014 the audit flags it). */\n ownerApp?: string\n}\n\n/** A discovered app as the wizard sees it: which parts exist + which backends its frontend proxies to. */\nexport interface WizardApp {\n /** App folder name (e.g. `client`). */\n name: string\n /** Has `apps/<app>/api` (a launchable backend). */\n hasApi: boolean\n /** Has `apps/<app>/ui` (a launchable frontend). */\n hasUi: boolean\n /**\n * This app's OWN `api` package name (from `apps/<app>/api`), or undefined when it has no api. Carried\n * so the audit can build a faithful `app \u2192 apiPackage` map for EVERY discovered api app \u2014 including\n * api-only apps a frontend proxies to cross-app \u2014 mirroring the root audit (`preset-proxy-check.ts`).\n */\n apiPackage?: string\n /** Backends this app's frontend proxies to (empty for api-only apps or a frontend with no `dev.proxy`). */\n backends: ProxyBackend[]\n}\n\n/** Everything the wizard needs, gathered impurely by {@link file://./dev-wizard-run.ts}. */\nexport interface WizardModel {\n /** All discovered apps (api and/or ui), sorted by name. */\n apps: WizardApp[]\n /** `devServersPresets` names (drives the preset-or-manual step-0). */\n presets: string[]\n /** Configured `environments` (the cloud-env `select` options). */\n environments: string[]\n}\n\n/** The manual-branch answers collected from the prompts, fed to {@link deriveManualPlan}. */\nexport interface ManualSelection {\n /**\n * The `<app>/<part>` target keys the user ticked directly (e.g. `client/ui`, `client/api`). A frontend's\n * proxy route resolves LOCAL iff the backend's owner-api part is in this set \u2014 otherwise CLOUD \u2014 so the\n * part checkbox IS the local/cloud decision; there is no separate per-backend question.\n */\n targets: string[]\n /** Chosen cloud env for cloud routes (undefined when nothing resolves cloud). */\n env?: string\n /** Rebuild + restart on save. */\n watch: boolean\n /** One cmux pane per app. */\n cmux: boolean\n}\n\n/** The resolved run plan derived from a {@link ManualSelection}. */\nexport interface DerivedPlan {\n /** In-memory preset handed to the runner (`options.presetDef`). */\n presetDef: DevPreset\n /** At least one route resolves to cloud \u2192 an env must be chosen (pre-flight gate). */\n anyCloudRoute: boolean\n /** Resolved `<app>/<part>` target keys, sorted \u2014 for the echo + audit display. */\n targetKeys: string[]\n}\n\n/** App folder name from an `<app>/<part>` target key. */\nconst appOf = (key: string): string => {\n return key.split('/')[0]!\n}\n\n/** Index a model's apps by folder name for O(1) lookup. */\nconst byName = (model: WizardModel): Map<string, WizardApp> => {\n return new Map(\n model.apps.map((a) => {\n return [a.name, a]\n }),\n )\n}\n\n/**\n * Resolve ONE selected frontend's proxy routes against the set of api parts the user ticked: a route is\n * `local` iff its backend is `localCapable` AND that backend's owner-api part was selected \u2014 otherwise\n * `cloud`. Kept separate from {@link deriveManualPlan} so the per-app override loop stays flat.\n */\nconst resolveUiProxy = (\n app: WizardApp,\n selectedApiApps: ReadonlySet<string>,\n): { overrides: Record<string, ProxySource>; anyCloud: boolean } => {\n const overrides: Record<string, ProxySource> = {}\n let anyCloud = false\n\n for (const backend of app.backends) {\n const isLocal = backend.localCapable && backend.ownerApp != null && selectedApiApps.has(backend.ownerApp)\n\n if (!isLocal) anyCloud = true\n for (const route of backend.routes) {\n overrides[route] = isLocal ? 'local' : 'cloud'\n }\n }\n\n return { overrides, anyCloud }\n}\n\n/**\n * Turn a part-level {@link ManualSelection} into an in-memory {@link DevPreset}. Because the user picks\n * `<app>/<part>` targets directly, the mapping is straightforward:\n * - every selected `<app>/ui` runs that frontend;\n * - every selected `<app>/api` runs that backend locally;\n * - each frontend's proxy route resolves `local` iff the backend's owner-api part was also selected\n * (even cross-app), else `cloud` \u2014 i.e. ticking the api part IS the local choice.\n *\n * @example\n * // client frontend only (its /api left unticked \u2192 its proxy route resolves to cloud):\n * deriveManualPlan(\n * { targets: ['client/ui'], watch: false, cmux: false },\n * { apps: [{ name: 'client', hasApi: true, hasUi: true,\n * backends: [{ packageName: 'client-api', routes: ['/api'], localCapable: true, ownerApp: 'client' }] }],\n * presets: [], environments: ['dev'] },\n * ).targetKeys // => ['client/ui']\n */\nexport const deriveManualPlan = (selection: ManualSelection, model: WizardModel): DerivedPlan => {\n const apps = byName(model)\n const uiKeys = selection.targets.filter((t) => {\n return t.endsWith('/ui')\n })\n const apiApps = new Set(\n selection.targets\n .filter((t) => {\n return t.endsWith('/api')\n })\n .map(appOf),\n )\n\n const presetApps: Record<string, { proxy?: Record<string, ProxySource> }> = {}\n let anyCloud = false\n\n for (const key of uiKeys) {\n const app = apps.get(appOf(key))\n const { overrides, anyCloud: cloud } = app ? resolveUiProxy(app, apiApps) : { overrides: {}, anyCloud: false }\n\n if (cloud) anyCloud = true\n presetApps[key] = Object.keys(overrides).length > 0 ? { proxy: overrides } : {}\n }\n for (const name of apiApps) {\n presetApps[`${name}/api`] ??= {}\n }\n\n return {\n presetDef: { apps: presetApps, cmux: selection.cmux },\n anyCloudRoute: anyCloud,\n targetKeys: Object.keys(presetApps).sort(),\n }\n}\n\n/** The equivalent non-interactive command, plus whether it reproduces the selection exactly. */\nexport interface EquivalentCommand {\n /** The `--app=\u2026`-form flag string (no leading `infra-kit dev`). */\n flags: string\n /**\n * True when `--app` reproduces the plan exactly \u2014 i.e. every involved app runs ALL the parts it has.\n * False for a part-level selection (e.g. frontend-only), which `--app` (app-name granularity) cannot\n * express; the caller then hints \"save as a preset\" for exact reproduction.\n */\n exact: boolean\n}\n\n/**\n * Build the equivalent `infra-kit dev --app=\u2026 [--watch] [--cmux]` flag string for a derived plan.\n * `exact` is true only when the target set covers every part each involved app HAS (a whole-app\n * selection), since `--app` filters by app name, not part.\n */\nexport const equivalentCommand = (\n plan: DerivedPlan,\n selection: ManualSelection,\n model: WizardModel,\n): EquivalentCommand => {\n const apps = byName(model)\n const involved = [...new Set(plan.targetKeys.map(appOf))].sort()\n const present = new Set(plan.targetKeys)\n\n const exact = involved.every((name) => {\n const app = apps.get(name)\n\n if (!app) return false\n\n const uiOk = !app.hasUi || present.has(`${name}/ui`)\n const apiOk = !app.hasApi || present.has(`${name}/api`)\n\n return uiOk && apiOk\n })\n\n const parts = [`--app=${involved.join(',')}`]\n\n if (selection.watch) parts.push('--watch')\n if (selection.cmux) parts.push('--cmux')\n\n return { flags: parts.join(' '), exact }\n}\n"],
|
|
5
|
+
"mappings": "iJASA,OAAOA,MAAsB,qBAC7B,OAAOC,MAAqB,oBAC5B,OAAOC,GAAkB,aAAAC,MAAiB,mBAC1C,OAAS,WAAAC,MAAe,mCACxB,OAAOC,MAAU,YACjB,OAAOC,MAAa,eCuEpB,IAAMC,EAASC,GACNA,EAAI,MAAM,GAAG,EAAE,CAAC,EAInBC,EAAUC,GACP,IAAI,IACTA,EAAM,KAAK,IAAKC,GACP,CAACA,EAAE,KAAMA,CAAC,CAClB,CACH,EAQIC,EAAiB,CACrBC,EACAC,IACkE,CAClE,IAAMC,EAAyC,CAAC,EAC5CC,EAAW,GAEf,QAAWC,KAAWJ,EAAI,SAAU,CAClC,IAAMK,EAAUD,EAAQ,cAAgBA,EAAQ,UAAY,MAAQH,EAAgB,IAAIG,EAAQ,QAAQ,EAEnGC,IAASF,EAAW,IACzB,QAAWG,KAASF,EAAQ,OAC1BF,EAAUI,CAAK,EAAID,EAAU,QAAU,OAE3C,CAEA,MAAO,CAAE,UAAAH,EAAW,SAAAC,CAAS,CAC/B,EAmBaI,EAAmB,CAACC,EAA4BX,IAAoC,CAC/F,IAAMY,EAAOb,EAAOC,CAAK,EACnBa,EAASF,EAAU,QAAQ,OAAQG,GAChCA,EAAE,SAAS,KAAK,CACxB,EACKC,EAAU,IAAI,IAClBJ,EAAU,QACP,OAAQG,GACAA,EAAE,SAAS,MAAM,CACzB,EACA,IAAIjB,CAAK,CACd,EAEMmB,EAAsE,CAAC,EACzEV,EAAW,GAEf,QAAWR,K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QAAQ,SAAW,EAC3B,OAAOa,EAAgBC,EAASd,CAAK,EAGvC,IAAMmC,EAAS,MAAMrB,EAAQ,OAAO,CAClC,QAAS,wDACT,QAAS,CACP,GAAGd,EAAM,QAAQ,IAAKoC,IACb,CAAE,KAAMA,EAAG,MAAOA,CAAE,EAC5B,EACD,IAAIC,EAAU,GAAG,EACjB,CAAE,KAAM,wBAAoB,MAAOJ,CAAc,CACnD,CACF,CAAC,EAED,OAAOE,IAAWF,EAAgBpB,EAAgBC,EAASd,CAAK,EAAI+B,EAAgBjB,EAASqB,CAAM,CACrG,EAMaG,GAAe,MAC1BxB,EAAyB7C,EACzBc,EAAewD,EAAiBvE,EAAQ,IAAI,CAAC,IAEtCkE,EAAcpB,EAAS,MAAMhC,EAAkBC,CAAI,CAAC",
|
|
6
|
+
"names": ["inquirerCheckbox", "inquirerConfirm", "inquirerSelect", "Separator", "loadDev", "path", "process", "appOf", "key", "byName", "model", "a", "resolveUiProxy", "app", "selectedApiApps", "overrides", "anyCloud", "backend", "isLocal", "route", "deriveManualPlan", "selection", "apps", "uiKeys", "t", "apiApps", "presetApps", "cloud", "name", "equivalentCommand", "plan", "involved", "present", "exact", "uiOk", "apiOk", "parts", "promptContext", "process", "defaultPrompts", "cfg", "inquirerSelect", "inquirerCheckbox", "inquirerConfirm", "groupBackends", "routes", "ownerByPkg", "byPkg", "route", "def", "existing", "localCapable", "gatherWizardModel", "root", "apiApps", "discoverApiApps", "uiApps", "discoverUiApps", "config", "getInfraKitConfig", "a", "apiPkgByName", "uiNames", "apiNames", "allNames", "name", "hasUi", "loadDev", "path", "buildPartChoices", "model", "choices", "app", "b", "description", "buildAuditContext", "discovered", "apiPkgByApp", "routeToPkg", "auditManualPlan", "presetDef", "validatePresetProxy", "i", "runManualBranch", "prompts", "logger", "selectedTargets", "watch", "cmux", "selection", "plan", "deriveManualPlan", "e", "INFRA_KIT_ENV_VAR", "issues", "issue", "echoManual", "k", "commandEcho", "eq", "equivalentCommand", "runPresetBranch", "preset", "MANUAL_CHOICE", "runWizardFlow", "choice", "p", "Separator", "runDevWizard", "findMonorepoRoot"]
|
|
7
|
+
}
|
package/dist/mcp.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ea as d,ha as u,v as l}from"./chunk-RLZ5IB2E.js";import"./chunk-NC2TIQ3M.js";import"./chunk-E2NWNNC6.js";import"./chunk-6FU2TRU5.js";import{a as m}from"./chunk-4MRYIYJP.js";import{t as c,u as p,v as s}from"./chunk-KZP2SY37.js";import"./chunk-CHETBZ6M.js";import{StdioServerTransport as y}from"@modelcontextprotocol/sdk/server/stdio.js";import g from"node:process";import o from"node:process";var f=r=>{o.on("SIGINT",()=>{r.info({msg:"Received SIGINT. Shutting down..."}),o.exit(0)}),o.on("SIGTERM",()=>{r.info({msg:"Received SIGTERM. Shutting down..."}),o.exit(0)}),o.on("uncaughtException",e=>{r.fatal({err:e,msg:"Uncaught Exception"}),r.error(`Uncaught Exception! Check ${c}. Shutting down...`),r.flush(),o.exit(1)}),o.on("unhandledRejection",(e,n)=>{r.fatal({reason:e,promise:n,msg:"Unhandled Rejection"}),r.error(`Unhandled Rejection! Check ${c}. Shutting down...`),r.flush(),o.exit(1)})};import{McpServer as T}from"@modelcontextprotocol/sdk/server/mcp.js";var v=async r=>{};var h=async r=>{};var a=({toolName:r,handler:e})=>async n=>{s.info({msg:`Tool execution started: ${r}`,params:n});try{await l(),m.reset();let i=await e({...n,confirmedCommand:!0});return s.info({msg:`Tool execution successful: ${r}`}),i}catch(i){throw s.error({err:i,params:n,msg:`Tool execution failed: ${r}`}),i}};var x=async r=>{for(let e of d())r.registerTool(e.name,{description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema},a({toolName:e.name,handler:e.handler}))};async function S(){let r=new T({name:"infra-kit",version:"1.0.0"},{capabilities:{resources:{},tools:{},prompts:{}}});return await v(r),await h(r),await x(r),r}u();var t=p(),w=async()=>{let r;try{r=await S(),t.info("MCP Server instance created")}catch(e){t.error({err:e,msg:"Failed to create MCP server"}),t.error("Fatal error during server creation."),g.exit(1)}try{let e=new y;await r.connect(e),t.info({msg:"Server connected to transport. Ready."})}catch(e){t.error({err:e,msg:"Failed to initialize server"}),t.error("Fatal error during server transport init."),g.exit(1)}};f(t);w();
|
|
2
2
|
//# sourceMappingURL=mcp.js.map
|
package/dist/mcp.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/entry/mcp.ts", "../src/lib/error-handlers/index.ts", "../src/mcp/server.ts", "../src/mcp/prompts/index.ts", "../src/mcp/resources/index.ts", "../src/lib/tool-handler/tool-handler.ts", "../src/mcp/tools/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport process from 'node:process'\n\nimport { setupErrorHandlers } from 'src/lib/error-handlers'\nimport { initLoggerMcp } from 'src/lib/logger'\n\nimport { createMcpServer } from '../mcp/server'\n\nconst logger = initLoggerMcp()\n\nconst startServer = async () => {\n let server\n\n try {\n server = await createMcpServer()\n\n logger.info('MCP Server instance created')\n } catch (error) {\n logger.error({ err: error, msg: 'Failed to create MCP server' })\n logger.error(`Fatal error during server creation.`)\n\n process.exit(1)\n }\n\n try {\n const transport = new StdioServerTransport()\n\n await server.connect(transport)\n\n logger.info({ msg: 'Server connected to transport. Ready.' })\n } catch (error) {\n logger.error({ err: error, msg: 'Failed to initialize server' })\n logger.error(`Fatal error during server transport init.`)\n\n process.exit(1)\n }\n}\n\n// Setup error handlers\nsetupErrorHandlers(logger)\n\n// Start the server\nstartServer()\n", "import process from 'node:process'\nimport type { Logger } from 'pino'\n\nimport { LOG_FILE_PATH } from '../logger/index'\n\n/**\n * Setup error handlers for the application\n * @param logger - The logger instance\n *\n * ONLY FOR SERVER!\n */\nexport const setupErrorHandlers = (logger: Logger) => {\n process.on('SIGINT', () => {\n logger.info({ msg: 'Received SIGINT. Shutting down...' })\n process.exit(0)\n })\n\n process.on('SIGTERM', () => {\n logger.info({ msg: 'Received SIGTERM. Shutting down...' })\n process.exit(0)\n })\n\n process.on('uncaughtException', (error) => {\n logger.fatal({ err: error, msg: 'Uncaught Exception' })\n logger.error(`Uncaught Exception! Check ${LOG_FILE_PATH}. Shutting down...`)\n logger.flush()\n process.exit(1)\n })\n\n process.on('unhandledRejection', (reason, promise) => {\n logger.fatal({ reason, promise, msg: 'Unhandled Rejection' })\n logger.error(`Unhandled Rejection! Check ${LOG_FILE_PATH}. Shutting down...`)\n logger.flush()\n process.exit(1)\n })\n}\n", "import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nimport { initializePrompts } from './prompts'\nimport { initializeResources } from './resources'\nimport { initializeTools } from './tools'\n\nexport async function createMcpServer() {\n const server = new McpServer(\n {\n name: 'infra-kit',\n version: '1.0.0',\n },\n {\n capabilities: {\n resources: {},\n tools: {},\n prompts: {},\n },\n },\n )\n\n await initializePrompts(server)\n await initializeResources(server)\n await initializeTools(server)\n\n return server\n}\n", "import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nexport const initializePrompts = async (_server: McpServer) => {}\n", "import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nexport const initializeResources = async (_server: McpServer) => {}\n", "import { ensureUserProjectConfig } from 'src/lib/config-bootstrap'\nimport { logger } from 'src/lib/logger'\nimport type { ToolsExecutionResult } from 'src/types'\n\ninterface ToolHandlerArgs {\n toolName: string\n handler: (params: any) => Promise<ToolsExecutionResult>\n}\n\nexport const createToolHandler = ({\n toolName,\n handler,\n}: ToolHandlerArgs): ((params: unknown) => Promise<ToolsExecutionResult>) => {\n return async (params: unknown) => {\n logger.info({ msg: `Tool execution started: ${toolName}`, params })\n try {\n // MCP entry-boundary seed. This wrapper is the sole chokepoint for every exposed tool\n // (`src/mcp/tools/index.ts` holds the only `registerTool` call), and the `mcp` command itself is\n // in program.ts's SEED_EXCLUDED \u2014 so an MCP server seeds lazily, on its FIRST tool invocation,\n // and a server that never receives one never writes to $HOME. The once-per-process guard inside\n // ensureUserProjectConfig makes calls 2..N free on this long-lived process.\n //\n // Deliberately INSIDE the try, not before it: defense-in-depth. ensureUserProjectConfig is\n // contractually never-throw, but if that contract ever broke, an unhandled rejection here would\n // take down the long-lived server. Inside the try it degrades to an ordinary tool error.\n await ensureUserProjectConfig()\n\n const payload = await handler({ ...(params as object), confirmedCommand: true })\n\n logger.info({ msg: `Tool execution successful: ${toolName}` })\n\n return payload\n } catch (error) {\n logger.error({\n err: error,\n params,\n msg: `Tool execution failed: ${toolName}`,\n })\n\n throw error\n }\n }\n}\n", "import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nimport { getExposedMcpTools } from 'src/lib/command-catalog'\nimport { createToolHandler } from 'src/lib/tool-handler'\n\nexport const initializeTools = async (server: McpServer) => {\n // The registered tool set is derived from the single command catalog, filtered\n // by its explicit `mcpExposed` allowlist. doctor / vendor-sync / vendor-manifest\n // are intentionally excluded there and must never be registered here.\n for (const tool of getExposedMcpTools()) {\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n },\n createToolHandler({ toolName: tool.name, handler: tool.handler }),\n )\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["StdioServerTransport", "process", "process", "setupErrorHandlers", "logger", "process", "error", "LOG_FILE_PATH", "reason", "promise", "McpServer", "initializePrompts", "_server", "initializeResources", "_server", "createToolHandler", "toolName", "handler", "params", "logger", "ensureUserProjectConfig", "payload", "error", "initializeTools", "server", "tool", "getExposedMcpTools", "createToolHandler", "createMcpServer", "server", "McpServer", "initializePrompts", "initializeResources", "initializeTools", "logger", "initLoggerMcp", "startServer", "server", "createMcpServer", "error", "process", "transport", "StdioServerTransport", "setupErrorHandlers"]
|
|
4
|
+
"sourcesContent": ["import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport process from 'node:process'\n\nimport { setupErrorHandlers } from 'src/lib/error-handlers'\nimport { initLoggerMcp } from 'src/lib/logger'\nimport { suppressTypelessPackageJsonWarning } from 'src/lib/node-warnings'\n\nimport { createMcpServer } from '../mcp/server'\n\n// The MCP tools run the same commands as the CLI, so they hit the same consumer `.ts` configs.\n// This keeps the client's log pane clean; it cannot affect protocol framing either way, since\n// the stdio transport frames JSON-RPC on stdout and `emitWarning` only ever writes to stderr.\nsuppressTypelessPackageJsonWarning()\n\nconst logger = initLoggerMcp()\n\nconst startServer = async () => {\n let server\n\n try {\n server = await createMcpServer()\n\n logger.info('MCP Server instance created')\n } catch (error) {\n logger.error({ err: error, msg: 'Failed to create MCP server' })\n logger.error(`Fatal error during server creation.`)\n\n process.exit(1)\n }\n\n try {\n const transport = new StdioServerTransport()\n\n await server.connect(transport)\n\n logger.info({ msg: 'Server connected to transport. Ready.' })\n } catch (error) {\n logger.error({ err: error, msg: 'Failed to initialize server' })\n logger.error(`Fatal error during server transport init.`)\n\n process.exit(1)\n }\n}\n\n// Setup error handlers\nsetupErrorHandlers(logger)\n\n// Start the server\nstartServer()\n", "import process from 'node:process'\nimport type { Logger } from 'pino'\n\nimport { LOG_FILE_PATH } from '../logger/index'\n\n/**\n * Setup error handlers for the application\n * @param logger - The logger instance\n *\n * ONLY FOR SERVER!\n */\nexport const setupErrorHandlers = (logger: Logger) => {\n process.on('SIGINT', () => {\n logger.info({ msg: 'Received SIGINT. Shutting down...' })\n process.exit(0)\n })\n\n process.on('SIGTERM', () => {\n logger.info({ msg: 'Received SIGTERM. Shutting down...' })\n process.exit(0)\n })\n\n process.on('uncaughtException', (error) => {\n logger.fatal({ err: error, msg: 'Uncaught Exception' })\n logger.error(`Uncaught Exception! Check ${LOG_FILE_PATH}. Shutting down...`)\n logger.flush()\n process.exit(1)\n })\n\n process.on('unhandledRejection', (reason, promise) => {\n logger.fatal({ reason, promise, msg: 'Unhandled Rejection' })\n logger.error(`Unhandled Rejection! Check ${LOG_FILE_PATH}. Shutting down...`)\n logger.flush()\n process.exit(1)\n })\n}\n", "import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nimport { initializePrompts } from './prompts'\nimport { initializeResources } from './resources'\nimport { initializeTools } from './tools'\n\nexport async function createMcpServer() {\n const server = new McpServer(\n {\n name: 'infra-kit',\n version: '1.0.0',\n },\n {\n capabilities: {\n resources: {},\n tools: {},\n prompts: {},\n },\n },\n )\n\n await initializePrompts(server)\n await initializeResources(server)\n await initializeTools(server)\n\n return server\n}\n", "import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nexport const initializePrompts = async (_server: McpServer) => {}\n", "import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nexport const initializeResources = async (_server: McpServer) => {}\n", "import { commandEcho } from 'src/lib/command-echo'\nimport { ensureUserProjectConfig } from 'src/lib/config-bootstrap'\nimport { logger } from 'src/lib/logger'\nimport type { ToolsExecutionResult } from 'src/types'\n\ninterface ToolHandlerArgs {\n toolName: string\n handler: (params: any) => Promise<ToolsExecutionResult>\n}\n\nexport const createToolHandler = ({\n toolName,\n handler,\n}: ToolHandlerArgs): ((params: unknown) => Promise<ToolsExecutionResult>) => {\n return async (params: unknown) => {\n logger.info({ msg: `Tool execution started: ${toolName}`, params })\n try {\n // MCP entry-boundary seed. This wrapper is the sole chokepoint for every exposed tool\n // (`src/mcp/tools/index.ts` holds the only `registerTool` call), and the `mcp` command itself is\n // in program.ts's SEED_EXCLUDED \u2014 so an MCP server seeds lazily, on its FIRST tool invocation,\n // and a server that never receives one never writes to $HOME. The once-per-process guard inside\n // ensureUserProjectConfig makes calls 2..N free on this long-lived process.\n //\n // Deliberately INSIDE the try, not before it: defense-in-depth. ensureUserProjectConfig is\n // contractually never-throw, but if that contract ever broke, an unhandled rejection here would\n // take down the long-lived server. Inside the try it degrades to an ordinary tool error.\n await ensureUserProjectConfig()\n\n // The command handlers record their resolved flags into the `commandEcho` singleton. On the CLI,\n // Commander's `preAction` clears it before every command; this long-lived server never runs that\n // hook, so without a reset here one tool call's flags would leak into the next one's snapshot and\n // the options array would grow for the life of the process.\n commandEcho.reset()\n\n const payload = await handler({ ...(params as object), confirmedCommand: true })\n\n logger.info({ msg: `Tool execution successful: ${toolName}` })\n\n return payload\n } catch (error) {\n logger.error({\n err: error,\n params,\n msg: `Tool execution failed: ${toolName}`,\n })\n\n throw error\n }\n }\n}\n", "import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\nimport { getExposedMcpTools } from 'src/lib/command-catalog'\nimport { createToolHandler } from 'src/lib/tool-handler'\n\nexport const initializeTools = async (server: McpServer) => {\n // The registered tool set is derived from the single command catalog, filtered\n // by its explicit `mcpExposed` allowlist. doctor / vendor-sync / vendor-manifest\n // are intentionally excluded there and must never be registered here.\n for (const tool of getExposedMcpTools()) {\n server.registerTool(\n tool.name,\n {\n description: tool.description,\n inputSchema: tool.inputSchema,\n outputSchema: tool.outputSchema,\n },\n createToolHandler({ toolName: tool.name, handler: tool.handler }),\n )\n }\n}\n"],
|
|
5
|
+
"mappings": "sQAAA,OAAS,wBAAAA,MAA4B,4CACrC,OAAOC,MAAa,eCDpB,OAAOC,MAAa,eAWb,IAAMC,EAAsBC,GAAmB,CACpDC,EAAQ,GAAG,SAAU,IAAM,CACzBD,EAAO,KAAK,CAAE,IAAK,mCAAoC,CAAC,EACxDC,EAAQ,KAAK,CAAC,CAChB,CAAC,EAEDA,EAAQ,GAAG,UAAW,IAAM,CAC1BD,EAAO,KAAK,CAAE,IAAK,oCAAqC,CAAC,EACzDC,EAAQ,KAAK,CAAC,CAChB,CAAC,EAEDA,EAAQ,GAAG,oBAAsBC,GAAU,CACzCF,EAAO,MAAM,CAAE,IAAKE,EAAO,IAAK,oBAAqB,CAAC,EACtDF,EAAO,MAAM,6BAA6BG,CAAa,oBAAoB,EAC3EH,EAAO,MAAM,EACbC,EAAQ,KAAK,CAAC,CAChB,CAAC,EAEDA,EAAQ,GAAG,qBAAsB,CAACG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,CAAM,EAChC,MAAMI,EAAgBJ,CAAM,EAErBA,CACT,CFdAK,EAAmC,EAEnC,IAAMC,EAASC,EAAc,EAEvBC,EAAc,SAAY,CAC9B,IAAIC,EAEJ,GAAI,CACFA,EAAS,MAAMC,EAAgB,EAE/BJ,EAAO,KAAK,6BAA6B,CAC3C,OAASK,EAAO,CACdL,EAAO,MAAM,CAAE,IAAKK,EAAO,IAAK,6BAA8B,CAAC,EAC/DL,EAAO,MAAM,qCAAqC,EAElDM,EAAQ,KAAK,CAAC,CAChB,CAEA,GAAI,CACF,IAAMC,EAAY,IAAIC,EAEtB,MAAML,EAAO,QAAQI,CAAS,EAE9BP,EAAO,KAAK,CAAE,IAAK,uCAAwC,CAAC,CAC9D,OAASK,EAAO,CACdL,EAAO,MAAM,CAAE,IAAKK,EAAO,IAAK,6BAA8B,CAAC,EAC/DL,EAAO,MAAM,2CAA2C,EAExDM,EAAQ,KAAK,CAAC,CAChB,CACF,EAGAG,EAAmBT,CAAM,EAGzBE,EAAY",
|
|
6
|
+
"names": ["StdioServerTransport", "process", "process", "setupErrorHandlers", "logger", "process", "error", "LOG_FILE_PATH", "reason", "promise", "McpServer", "initializePrompts", "_server", "initializeResources", "_server", "createToolHandler", "toolName", "handler", "params", "logger", "ensureUserProjectConfig", "commandEcho", "payload", "error", "initializeTools", "server", "tool", "getExposedMcpTools", "createToolHandler", "createMcpServer", "server", "McpServer", "initializePrompts", "initializeResources", "initializeTools", "suppressTypelessPackageJsonWarning", "logger", "initLoggerMcp", "startServer", "server", "createMcpServer", "error", "process", "transport", "StdioServerTransport", "setupErrorHandlers"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as p,c as u}from"./chunk-TI33V5G2.js";import{a as l}from"./chunk-TPVXMJ7N.js";import{render as C}from"ink";import E from"node:process";import{Box as c,Static as S,Text as a}from"ink";import{useEffect as F,useState as b}from"react";import{jsx as o,jsxs as v}from"react/jsx-runtime";var g=r=>{let{phase:e,narration:t,readyLines:i}=r,[h,f]=b(0);return F(()=>{if(i)return;let n=setInterval(()=>{f(s=>s+1)},w);return()=>{clearInterval(n)}},[i]),i?o(S,{items:i,children:(n,s)=>o(a,{children:n},s)}):v(c,{flexDirection:"column",children:[v(c,{children:[o(a,{color:"cyan",children:m[h%m.length]}),o(a,{dimColor:!0,children:` ${e}`})]}),t?o(a,{dimColor:!0,children:t}):null]})},m=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],w=80;import{Box as P,Static as D,Text as L}from"ink";import{Fragment as T,jsx as d,jsxs as z}from"react/jsx-runtime";var R=r=>{let{headerLines:e,logLines:t,footerLines:i}=r,h=[...e,...t],f=B(i,r.maxFooterLines);return z(T,{children:[d(D,{items:h,children:(n,s)=>d(L,{children:n},s)}),d(P,{flexDirection:"column",children:f.map((n,s)=>d(L,{children:n},s))})]})},B=(r,e)=>{if(e==null||e<1||r.length<=e)return r;let t=r.slice(0,e-1);return[...t,` \u2026 +${r.length-t.length} more`]};import{jsx as x}from"react/jsx-runtime";var y=class{renderer;renderFn;stdout;verbose;now;instance=null;finalized=!1;persistent=!1;phase="";narration="";headerLines=[];logLines=[];footerLines=[];constructor(e){this.verbose=e.verbose??!1,this.renderFn=e.render??C,this.stdout=e.stdout??l(E.stdout),this.now=e.now??(()=>new Date),this.renderer=new u({appendLog:e.appendLog,verbose:this.verbose,isTTY:!0,write:t=>{this.stdout.write(t)},now:this.now})}logFn=(e,t="info")=>{this.log(e,t)};renderBoot(e){let t=x(g,{phase:this.phase,narration:this.narration,readyLines:e});if(this.instance){this.instance.rerender(t);return}this.instance=this.renderFn(t,{stdout:this.stdout,exitOnCtrlC:!1,patchConsole:!1})}unmount(){this.instance&&(this.instance.unmount(),this.instance=null)}narrate(e){if(this.renderer.teeOnly(e,"info"),this.persistent){this.verbose&&(this.logLines.push(e),this.rerenderPersistent());return}this.finalized||(this.narration=e,this.instance&&this.renderBoot())}log(e,t="info"){let i=t!=="debug"||this.verbose;if(this.persistent){this.renderer.teeOnly(e,t),i&&(this.logLines.push(e),this.rerenderPersistent());return}i&&this.unmount(),this.renderer.log(e,t)}bootStep(e){this.renderer.teeOnly(e,"info"),!this.finalized&&(this.phase=e,this.renderBoot())}stopSpinner(){this.persistent||this.unmount()}ready(e){this.headerLines=this.renderer.formatHeaderLines(e),this.footerLines=this.renderer.formatFooterLines(e),this.logLines=[];for(let t of this.headerLines)this.renderer.teeOnly(t,"info");this.finalized=!0,this.persistent=!0,typeof this.stdout.on=="function"&&this.stdout.on("resize",this.onResize),this.rerenderPersistent()}maxFooterLines(){return Math.max(3,(this.stdout.rows??24)-6)}rerenderPersistent(){let e=x(R,{headerLines:this.headerLines,logLines:this.logLines,footerLines:this.footerLines,maxFooterLines:this.maxFooterLines()});if(this.instance){this.instance.rerender(e);return}this.instance=this.renderFn(e,{stdout:this.stdout,exitOnCtrlC:!1,patchConsole:!1})}onResize=()=>{this.persistent&&this.rerenderPersistent()};event(e){if(this.persistent){let t=` ${p(this.now())} ${e.tag} ${e.text}`;this.renderer.teeOnly(`${e.tag} ${e.text}`,"info"),this.logLines.push(t),this.rerenderPersistent();return}this.unmount(),this.renderer.event(e)}refresh(e){this.persistent&&(this.footerLines=this.renderer.formatFooterLines(e),this.rerenderPersistent())}dispose(){this.persistent&&(this.rerenderPersistent(),typeof this.stdout.off=="function"&&this.stdout.off("resize",this.onResize)),this.finalized=!0,this.persistent=!1,this.unmount()}};export{y as PersistentInkDevUi};
|
|
2
|
+
//# sourceMappingURL=persistent-ink-dev-ui-KOI44ZVT.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/tui/dev-ui/persistent-ink-dev-ui.tsx", "../src/tui/dev-ui/boot-region.tsx", "../src/tui/dev-ui/live-region.tsx"],
|
|
4
|
+
"sourcesContent": ["import { render as inkRender } from 'ink'\nimport process from 'node:process'\nimport type { ReactElement } from 'react'\n\nimport type { DevUi, LogLevel, ReadySummary } from 'src/dev/dev-ui'\nimport { DevRenderer, formatClock } from 'src/dev/render'\nimport { createSafeStream } from 'src/tui/safe-stderr'\n\nimport { BootRegion } from './boot-region'\nimport { LiveRegion } from './live-region'\n\n/**\n * Ink-backed {@link DevUi} for `infra-kit dev`: a boot region that collapses into a PERSISTENT status\n * panel. It is the UI on any interactive TTY.\n *\n * There is one shape of session now, not two. Until recently `ready` branched on `summary.hasUiChild`\n * and, for a UI session, unmounted Ink and handed off to a DECSTBM scroll-region UI \u2014 because the\n * `turbo run dev` child's piped output produced an unbounded tail, Ink repaints its live region on every\n * appended line, and a pinned footer can only survive a scrolling stream if the TERMINAL is told to\n * confine it.\n *\n * That tail no longer exists. Framework lines and request lines go to their per-service log files and\n * are never printed, so there is nothing to scroll past the panel and nothing for a scroll region to\n * defend it from. The branch, the handoff, and the whole DECSTBM machinery were deleted with the stream\n * that justified them.\n *\n * What still prints above the panel is only what the RUNNER says \u2014 a restart, an unhealthy app, a dead\n * engine. Those are rare and they are events, not logs.\n *\n * The embedded {@link DevRenderer} owns the file-tee format (`teeOnly`); in persistent mode it is used\n * ONLY for teeing, never its direct stdout write, which would collide with the live region. Every\n * component here is OUTPUT-ONLY (no `useInput`) \u2014 see live-region.tsx.\n */\n\n/** The subset of an Ink render handle this UI drives \u2014 shared by `ink` and `ink-testing-library`. */\ninterface RenderHandle {\n rerender: (tree: ReactElement) => void\n unmount: () => void\n}\n\n/** Render seam: `ink`'s `render` by default; `ink-testing-library`'s `render` is injected in tests. */\ntype RenderFn = (tree: ReactElement, options?: unknown) => RenderHandle\n\nexport interface PersistentInkDevUiDeps {\n /** File tee \u2014 the same appender the runner hands the plain renderer. */\n appendLog: (text: string) => void\n /** Mirrors the renderer's verbose gate: only in verbose does a `debug` log reach the terminal. */\n verbose?: boolean\n /** Clock seam (for deterministic tee + event timestamps in tests). */\n now?: () => Date\n /** Render seam (default `ink`'s `render`); tests inject `ink-testing-library`'s `render`. */\n render?: RenderFn\n /**\n * Target stream (default: `process.stdout` behind the scrollback-safe filter).\n *\n * The runner injects a stream whose `write` BYPASSES the output interceptor. That is not optional:\n * the interceptor owns `process.stdout` for the life of the session, so a panel painted through the\n * raw stream would have its frames filed into a log file instead of drawn \u2014 a blank screen, with no\n * error and no failing test.\n */\n stdout?: NodeJS.WriteStream\n}\n\nexport class PersistentInkDevUi implements DevUi {\n private readonly renderer: DevRenderer\n private readonly renderFn: RenderFn\n private readonly stdout: NodeJS.WriteStream\n private readonly verbose: boolean\n private readonly now: () => Date\n /** Live Ink handle, or `null` when not mounted. */\n private instance: RenderHandle | null = null\n /** True once boot is done: never mount the boot region again. */\n private finalized = false\n /** True while the persistent panel owns the terminal (after ready). */\n private persistent = false\n private phase = ''\n private narration = ''\n private headerLines: string[] = []\n private logLines: string[] = []\n private footerLines: string[] = []\n\n constructor(deps: PersistentInkDevUiDeps) {\n this.verbose = deps.verbose ?? false\n this.renderFn = deps.render ?? (inkRender as RenderFn)\n // NOT raw `process.stdout`: Ink writes `ESC[3J` (erase saved lines) whenever a frame overflows the\n // viewport, which wipes the terminal's SCROLLBACK \u2014 the user's history, and every previous command's\n // output when `dev` runs as a session-shell child. `createSafeStream` drops that one escape and\n // forwards everything else live.\n this.stdout = deps.stdout ?? createSafeStream(process.stdout as NodeJS.WriteStream)\n this.now =\n deps.now ??\n ((): Date => {\n return new Date()\n })\n this.renderer = new DevRenderer({\n appendLog: deps.appendLog,\n verbose: this.verbose,\n isTTY: true,\n write: (text) => {\n this.stdout.write(text)\n },\n now: this.now,\n })\n }\n\n /** `LogFn`-shaped adapter for the build runner seam. */\n readonly logFn = (message: string, level: LogLevel = 'info'): void => {\n this.log(message, level)\n }\n\n // ---- boot ---------------------------------------------------------------\n\n /** Mount the Ink boot region (or rerender it in place) with the current phase + narration. */\n private renderBoot(readyLines?: string[]): void {\n const tree = <BootRegion phase={this.phase} narration={this.narration} readyLines={readyLines} />\n\n if (this.instance) {\n this.instance.rerender(tree)\n\n return\n }\n this.instance = this.renderFn(tree, { stdout: this.stdout, exitOnCtrlC: false, patchConsole: false })\n }\n\n /** Unmount Ink if mounted (idempotent). */\n private unmount(): void {\n if (this.instance) {\n this.instance.unmount()\n this.instance = null\n }\n }\n\n narrate(message: string): void {\n this.renderer.teeOnly(message, 'info')\n if (this.persistent) {\n // Visible only in verbose (matches the plain renderer); tee already happened above.\n if (this.verbose) {\n this.logLines.push(message)\n this.rerenderPersistent()\n }\n\n return\n }\n if (this.finalized) {\n return\n }\n this.narration = message\n if (this.instance) {\n this.renderBoot()\n }\n }\n\n log(message: string, level: LogLevel = 'info'): void {\n const willWrite = level !== 'debug' || this.verbose\n\n if (this.persistent) {\n // Never the embedded renderer's direct stdout write here \u2014 append to the live region instead.\n this.renderer.teeOnly(message, level)\n if (willWrite) {\n this.logLines.push(message)\n this.rerenderPersistent()\n }\n\n return\n }\n if (willWrite) {\n this.unmount()\n }\n this.renderer.log(message, level)\n }\n\n bootStep(phase: string): void {\n this.renderer.teeOnly(phase, 'info')\n if (this.finalized) {\n return\n }\n this.phase = phase\n this.renderBoot()\n }\n\n stopSpinner(): void {\n if (!this.persistent) {\n this.unmount()\n }\n }\n\n // ---- the persistent panel ----------------------------------------------\n\n /** Commit the header, tee it, mount the live panel, and STAY mounted for the rest of the session. */\n ready(summary: ReadySummary): void {\n this.headerLines = this.renderer.formatHeaderLines(summary)\n this.footerLines = this.renderer.formatFooterLines(summary)\n this.logLines = []\n for (const line of this.headerLines) {\n this.renderer.teeOnly(line, 'info')\n }\n this.finalized = true\n this.persistent = true\n // Re-clamp the panel when the terminal resizes. Guarded: an injected (test/piped) stream may not\n // be an EventEmitter TTY.\n if (typeof this.stdout.on === 'function') {\n this.stdout.on('resize', this.onResize)\n }\n this.rerenderPersistent()\n }\n\n /**\n * Cap for the pinned panel: it is a live region and cannot scroll, so it must never exceed the\n * viewport. Reserve rows for the runner's occasional lines above it; fall back to an 80\u00D724 assumption\n * when the stream reports no row count (piped / test stdout).\n */\n private maxFooterLines(): number {\n return Math.max(3, (this.stdout.rows ?? 24) - 6)\n }\n\n /** Mount or repaint the live region from the current header / logs / panel snapshot. */\n private rerenderPersistent(): void {\n const tree = (\n <LiveRegion\n headerLines={this.headerLines}\n logLines={this.logLines}\n footerLines={this.footerLines}\n maxFooterLines={this.maxFooterLines()}\n />\n )\n\n if (this.instance) {\n this.instance.rerender(tree)\n\n return\n }\n this.instance = this.renderFn(tree, { stdout: this.stdout, exitOnCtrlC: false, patchConsole: false })\n }\n\n /** Re-clamp + repaint on terminal resize (SIGWINCH), so a shrink never overflows the viewport. */\n private readonly onResize = (): void => {\n if (this.persistent) {\n this.rerenderPersistent()\n }\n }\n\n /**\n * A tagged, timestamped line. The runner no longer emits any \u2014 framework and request lines go to their\n * per-service files instead of the terminal \u2014 but the seam stays on the {@link DevUi} contract for the\n * plain/non-TTY renderer, which still streams.\n */\n event(input: { tag: string; text: string }): void {\n if (this.persistent) {\n const line = ` ${formatClock(this.now())} ${input.tag} ${input.text}`\n\n this.renderer.teeOnly(`${input.tag} ${input.text}`, 'info')\n this.logLines.push(line)\n this.rerenderPersistent()\n\n return\n }\n this.unmount()\n this.renderer.event(input)\n }\n\n /**\n * Repaint the live status rows in place from a fresh summary (header + runner lines untouched).\n *\n * This is the panel's heartbeat. With no log tail on screen, a panel whose numbers never move is\n * indistinguishable from a hung process \u2014 so this is what proves the session is alive.\n */\n refresh(summary: ReadySummary): void {\n // A session still in boot has no panel to refresh.\n if (!this.persistent) {\n return\n }\n this.footerLines = this.renderer.formatFooterLines(summary)\n this.rerenderPersistent()\n }\n\n dispose(): void {\n if (this.persistent) {\n // Commit the last panel state, then release the terminal.\n this.rerenderPersistent()\n if (typeof this.stdout.off === 'function') {\n this.stdout.off('resize', this.onResize)\n }\n }\n this.finalized = true\n this.persistent = false\n this.unmount()\n }\n}\n", "import { Box, Static, Text } from 'ink'\nimport { useEffect, useState } from 'react'\n\n/**\n * The Ink boot region for `infra-kit dev`: an animated spinner + phase line while the server boots,\n * then the ready header committed to scrollback via `<Static>`.\n *\n * HARD INVARIANT \u2014 this component (and every boot component under `src/tui/dev-ui/`) is OUTPUT-ONLY.\n * It MUST NEVER call `useInput`. `useInput` arms Ink's raw mode + Ctrl-C interception, which would\n * steal SIGINT from the process signal handler that owns dev-server shutdown. The spinner animates via\n * a self-contained interval only; there is no keyboard input during boot. Do not add `useInput` here.\n */\n\nexport interface BootRegionProps {\n /** Current boot phase, shown beside the spinner. */\n phase: string\n /** Latest narration detail (dim subtitle under the spinner); empty hides the line. */\n narration: string\n /**\n * When set, boot is done: the pre-formatted ready-header lines are committed to scrollback via\n * `<Static>` and the transient spinner region is gone. The renderer unmounts right after.\n */\n readyLines?: string[]\n}\n\n/** Animated boot spinner + phase/narration, or the committed ready header once `readyLines` is set. */\nexport const BootRegion = (props: BootRegionProps) => {\n const { phase, narration, readyLines } = props\n\n const [frame, setFrame] = useState(0)\n\n useEffect(() => {\n // No spinner once the ready header is committed.\n if (readyLines) {\n return\n }\n\n const timer = setInterval(() => {\n setFrame((f) => {\n return f + 1\n })\n }, SPINNER_INTERVAL_MS)\n\n return () => {\n clearInterval(timer)\n }\n }, [readyLines])\n\n if (readyLines) {\n // `<Static>` writes each line once, above the (now empty) live region, so the header persists in\n // scrollback after unmount. Lines are pre-formatted by DevRenderer.formatReadyLines.\n return (\n <Static items={readyLines}>\n {(line, index) => {\n return <Text key={index}>{line}</Text>\n }}\n </Static>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n <Box>\n <Text color=\"cyan\">{SPINNER_FRAMES[frame % SPINNER_FRAMES.length]}</Text>\n <Text dimColor>{` ${phase}`}</Text>\n </Box>\n {narration ? <Text dimColor>{narration}</Text> : null}\n </Box>\n )\n}\n\nconst SPINNER_FRAMES = ['\u280B', '\u2819', '\u2839', '\u2838', '\u283C', '\u2834', '\u2826', '\u2827', '\u2807', '\u280F']\nconst SPINNER_INTERVAL_MS = 80\n", "import { Box, Static, Text } from 'ink'\n\n/**\n * The persistent Ink live region for `infra-kit dev` (backend-only sessions): the committed header +\n * growing log scrollback above, and a live health footer re-rendered in place below.\n *\n * HARD INVARIANT \u2014 this component (and every component under `src/tui/dev-ui/`) is OUTPUT-ONLY. It\n * MUST NEVER call `useInput`. `useInput` arms Ink's raw mode + Ctrl-C interception, which would steal\n * SIGINT from the process signal handler that owns dev-server shutdown. There is no keyboard input in\n * the live region \u2014 it is props only, with no state, no effects, no input. Do not add `useInput` here.\n */\n\nexport interface LiveRegionProps {\n /** Reference header, committed once to scrollback via `<Static>` (from `formatHeaderLines`). */\n headerLines: string[]\n /** Log lines committed above the footer as they arrive (also via the SAME `<Static>`). */\n logLines: string[]\n /** Live footer, re-rendered in place on every health change (from `formatFooterLines`). */\n footerLines: string[]\n /**\n * Cap on rendered footer rows so a many-backend session never eats a short viewport (the footer is a\n * live region \u2014 it cannot scroll). Overflow collapses into a trailing dim `\u2026 +N more` line. Omit for\n * no cap. The pinned footer must stay short; the full health picture is always in the log file.\n */\n maxFooterLines?: number\n}\n\n/**\n * A SINGLE `<Static>` streams the header then the growing logs (Ink writes only newly-appended items\n * each commit, so the header lands first and logs accrete beneath it \u2014 one block, never two). The\n * footer is an ordinary `<Box>`, so it repaints in place on each rerender without touching scrollback.\n */\nexport const LiveRegion = (props: LiveRegionProps) => {\n const { headerLines, logLines, footerLines } = props\n\n const staticItems = [...headerLines, ...logLines]\n const footer = clampFooter(footerLines, props.maxFooterLines)\n\n return (\n <>\n <Static items={staticItems}>\n {(line, index) => {\n return <Text key={index}>{line}</Text>\n }}\n </Static>\n <Box flexDirection=\"column\">\n {footer.map((line, index) => {\n return <Text key={index}>{line}</Text>\n })}\n </Box>\n </>\n )\n}\n\n/** Cap the footer to `max` rows, collapsing the overflow into one trailing ` \u2026 +N more` line. */\nexport const clampFooter = (lines: string[], max?: number): string[] => {\n if (max == null || max < 1 || lines.length <= max) {\n return lines\n }\n\n const shown = lines.slice(0, max - 1)\n\n return [...shown, ` \u2026 +${lines.length - shown.length} more`]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", "useState", "jsx", "jsxs", "BootRegion", "props", "phase", "narration", "readyLines", "frame", "setFrame", "timer", "f", "SPINNER_INTERVAL_MS", "line", "index", "SPINNER_FRAMES", "Box", "Static", "Text", "Fragment", "jsx", "jsxs", "LiveRegion", "props", "headerLines", "logLines", "footerLines", "staticItems", "footer", "clampFooter", "line", "index", "lines", "max", "shown", "jsx", "PersistentInkDevUi", "deps", "inkRender", "createSafeStream", "process", "DevRenderer", "text", "message", "level", "readyLines", "tree", "BootRegion", "willWrite", "phase", "summary", "line", "LiveRegion", "input", "formatClock"]
|
|
7
|
+
}
|
package/dist/update-check.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{h as i}from"./chunk-
|
|
1
|
+
import{h as i}from"./chunk-E2SEBLGJ.js";import{a as t}from"./chunk-E2NWNNC6.js";import"./chunk-6FU2TRU5.js";import"./chunk-CHETBZ6M.js";import a from"node:fs";import o from"node:process";import{fileURLToPath as s}from"node:url";var m=r=>{let n=r.indexOf("--parent-pid");if(n===-1)return;let e=Number(r[n+1]);return Number.isInteger(e)&&e>0?e:void 0},p=()=>a.realpathSync(s(new URL("./cli.js",import.meta.url))),d=async()=>{await i(t.version,{selfRealPath:p(),parentPid:m(o.argv)})};d().catch(()=>{o.exitCode=0});
|
|
2
2
|
//# sourceMappingURL=update-check.js.map
|
package/package.json
CHANGED
|
@@ -1,24 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "infra-kit",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.0",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist"
|
|
7
7
|
],
|
|
8
8
|
"description": "infra-kit",
|
|
9
|
-
"main": "dist/index.js",
|
|
10
|
-
"module": "dist/index.js",
|
|
11
|
-
"types": "dist/entry/index.d.ts",
|
|
12
|
-
"exports": {
|
|
13
|
-
".": {
|
|
14
|
-
"types": "./dist/entry/index.d.ts",
|
|
15
|
-
"import": "./dist/index.js"
|
|
16
|
-
},
|
|
17
|
-
"./vite": {
|
|
18
|
-
"types": "./dist/entry/vite.d.ts",
|
|
19
|
-
"import": "./dist/vite.js"
|
|
20
|
-
}
|
|
21
|
-
},
|
|
22
9
|
"bin": {
|
|
23
10
|
"infra-kit": "dist/cli.js",
|
|
24
11
|
"ik": "dist/cli.js"
|
|
@@ -50,8 +37,10 @@
|
|
|
50
37
|
"@aws-lambda-powertools/logger": "^2.33.1",
|
|
51
38
|
"@inquirer/checkbox": "^5.2.1",
|
|
52
39
|
"@inquirer/confirm": "^6.1.1",
|
|
40
|
+
"@inquirer/password": "^5.0.2",
|
|
53
41
|
"@inquirer/select": "^5.2.1",
|
|
54
42
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
43
|
+
"@slip-stream-kit/config": "^0.3.0",
|
|
55
44
|
"chalk": "^5.6.2",
|
|
56
45
|
"chokidar": "^5.0.0",
|
|
57
46
|
"commander": "^15.0.0",
|
package/dist/chunk-6EPRH34O.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-6EPRH34O.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 (`http://<release>.<packageName>.localhost`) because the proxy defaults to `:80`.\n * A consumer who trades the clean URL for a zero-sudo unprivileged port still needs the frontend to\n * reach it, so the runner records the port it actually bound and we append it here. A template that\n * already pins its own port keeps it.\n */\nconst withProxyPort = (target: string, proxyPort: number | undefined): string => {\n if (proxyPort == null || proxyPort === DEFAULT_HTTP_PORT) return target\n\n let url: URL\n\n try {\n url = new URL(target)\n } catch {\n throw new Error(\n `infra-kit/vite: dev.proxy templates.local resolved to \"${target}\", which is not a valid URL, so the proxy port ${proxyPort} cannot be applied.`,\n )\n }\n\n if (url.port !== '') return target\n url.port = String(proxyPort)\n\n // `URL.toString()` synthesizes a `/` pathname for an authority-only URL, so the common port-free\n // template would come back as `\u2026localhost:1355/`. Strip that ONLY when the template had no trailing\n // slash of its own \u2014 a template ending in `/` (e.g. `\u2026localhost/base/`) means it, and silently\n // trimming it would change the path the frontend proxies to.\n const grafted = url.toString()\n\n return !target.endsWith('/') && grafted.endsWith('/') ? grafted.slice(0, -1) : grafted\n}\n\n/**\n * The 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,SAAS,EACrD,cAAeA,EAAE,MAAMA,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS,EACnD,MAAOA,EACJ,aAAa,CACZ,cAAeA,EAAE,MAAMA,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS,CACrD,CAAC,EACA,SAAS,EACZ,IAAKA,EACF,aAAa,CACZ,MAAOA,EACJ,aAAa,CACZ,UAAWA,EAAE,aAAa,CACxB,MAAOA,EAAE,OAAO,EAAE,IAAI,CAAC,EACvB,MAAOA,EAAE,OAAO,EAAE,IAAI,CAAC,CACzB,CAAC,EACD,OAAQA,EAAE,OACRA,EAAE,OAAO,EAAE,IAAI,CAAC,EAChBA,EACG,aAAa,CACZ,YAAaA,EAAE,OAAO,EAAE,IAAI,CAAC,EAC7B,KAAMA,EAAE,MAAMA,EAAE,KAAK,CAAC,QAAS,OAAO,CAAC,CAAC,EA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AE,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-6FDGBQGX.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var i={name:"infra-kit",type:"module",version:"0.1.133",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-6FDGBQGX.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.133\",\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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AAiC,CACjD,IAAMgB,EAAW,KAAK,SAAShB,CAAO,EAEtC,OAAOA,EAAQ,UACZ,OAAQE,GACAA,EAAE,UAAY,IACtB,EACA,IAAKA,GACG,KAAK,KAAK,MAAM5B,EAAK,KAAM4B,EAAE,IAAI,OAAOc,CAAQ,CAAC,CAAC,KAAK,KAAK,UAAUd,EAAE,OAAO,CAAC,EACxF,CACL,CAOA,iBAAiBF,EAAiC,CAChD,OAAO,KAAK,YAAYA,EAAS,CAAE,cAAe,EAAK,CAAC,CAC1D,CASA,MAAMf,EAA4C,CAChD,IAAMqC,EAAK1C,EAAY,KAAK,KAAK,IAAI,CAAC,EAChCgB,EAAO,KAAK,KAAK,MAAMtB,EAAK,IAAKgD,CAAE,CAAC,KAAK,KAAK,MAAMhD,EAAK,KAAMW,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
|
-
}
|