infra-kit 0.11.16 → 0.13.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.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/dev/discovery.ts", "../src/dev/presets.ts"],
4
+ "sourcesContent": ["/**\n * Filesystem discovery helpers for the dev-server.\n *\n * These functions read the filesystem (walking for the monorepo root, scanning\n * `apps/` and `packages/`) but never `chdir` and never resolve ports / prefixes \u2014\n * that stays with the pure {@link file://./ports.ts} layer. The starting directory\n * is passed in so discovery is testable against a fixture root.\n */\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\n/** Bare metadata for a discovered API app (no resolved port / prefix). */\nexport interface DiscoveredApiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** Package name from package.json (e.g. sls-trvl-client), or the folder name as fallback. */\n packageName: string\n path: string\n}\n\n/** Walk up from `startDir` (max 10 levels) to the dir containing `pnpm-workspace.yaml`. */\nexport function findMonorepoRoot(startDir: string): string {\n let currentDir = startDir\n\n for (let i = 0; i < 10; i++) {\n const workspaceFile = path.join(currentDir, 'pnpm-workspace.yaml')\n\n if (fs.existsSync(workspaceFile)) {\n return currentDir\n }\n currentDir = path.dirname(currentDir)\n }\n\n throw new Error('Could not find monorepo root (pnpm-workspace.yaml)')\n}\n\n/** Read the `name` field from `<apiPath>/package.json`, falling back to `appName`. */\nexport function getPackageName(apiPath: string, appName: string): string {\n const pkgPath = path.join(apiPath, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return appName\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { name?: string }\n\n return typeof pkg.name === 'string' ? pkg.name : appName\n } catch {\n return appName\n }\n}\n\n/** Discover every `apps/<app>` that has an `api/serverless.yml` (bare metadata only). */\nexport function discoverApiApps(root: string): DiscoveredApiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredApiApp[] = []\n\n if (!fs.existsSync(appsDir)) {\n throw new Error(`Apps directory not found: ${appsDir}`)\n }\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const apiPath = path.join(appsDir, appName, 'api')\n const serverlessPath = path.join(apiPath, 'serverless.yml')\n\n if (fs.existsSync(serverlessPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(apiPath, appName),\n path: apiPath,\n })\n }\n }\n\n return apps\n}\n\n/** Bare metadata for a discovered UI app (a frontend with its own framework `dev` script). */\nexport interface DiscoveredUiApp {\n /** App folder name (e.g. backoffice, client). */\n name: string\n /** package.json `name` \u2014 used as the exact `turbo run dev --filter` target. */\n packageName: string\n /** Absolute path to `apps/<app>/ui`. */\n path: string\n /**\n * True when this UI's vite config wires `infra-kit/vite`'s `infraKitDev()` helper \u2014 the ONLY thing\n * that makes it honor the runner-assigned `INFRA_KIT_UI_PORTS` port (which it binds with `strictPort`).\n *\n * The runner treats frameworks opaquely, so it cannot assume a pre-assigned port is the port the child\n * will bind. Without this signal it would print a confident, wrong URL for any UI that picks its own\n * port (vike, astro, a hand-rolled vite config). Unwired \u2192 the runner claims no port and the UI keeps\n * its honest \"vite prints its URL below\" reference line.\n */\n managedPort: boolean\n}\n\n/** Vite config filenames checked for the helper import, in vite's own resolution order. */\nconst VITE_CONFIG_FILES = [\n 'vite.config.ts',\n 'vite.config.mts',\n 'vite.config.cts',\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.cjs',\n]\n\n/**\n * Every module specifier that binds a UI to infra-kit's dev wiring \u2014 whether through the raw\n * `infraKitDev` helper or through the `@slip-stream-kit/vite` plugin that wraps it.\n *\n * Matched as a SUBSTRING of a config's import specifiers. This is what makes `managedPort` true, so a\n * MISSING entry is not cosmetic: the runner would stop claiming the port for every UI on that specifier,\n * and with it the hero URL. Drop the legacy entry once every consumer repo is migrated.\n */\n// A LIST, not a single literal, because the wiring moved packages twice: it used to ship from the\n// `infra-kit` CLI itself, then from `@slip-stream-kit/config` (the split that let the CLI become a global\n// install \u2014 a local `node_modules/.bin/infra-kit` would otherwise shadow the global bin, see that\n// package's readme), and the plugin form now ships from `@slip-stream-kit/vite`. Consumers migrate one\n// repo at a time, so all three specifiers are live.\n//\n// The substring match is why the config package could not be called `@infra-kit/vite`: that name\n// *contains* `infra-kit/vite`, so the legacy entry would have matched it by accident and hidden the very\n// coupling the split makes explicit. Neither `@slip-stream-kit/config/vite` nor `@slip-stream-kit/vite`\n// contains any other entry, so no entry here shadows another.\nexport const INFRA_KIT_VITE_SPECIFIERS = [\n '@slip-stream-kit/vite',\n '@slip-stream-kit/config/vite',\n 'infra-kit/vite',\n] as const\n\n/**\n * True when `<dir>`'s vite config references the `infraKitDev` helper module. A text match, not a\n * module load: the config is TypeScript the runner must not execute, and importing it would run the\n * consumer's own side effects. False negatives (a config that re-exports the helper from a shared\n * preset) cost only the reference line, never a wrong URL \u2014 the safe direction to be wrong in.\n */\nexport function usesInfraKitVite(dir: string): boolean {\n for (const file of VITE_CONFIG_FILES) {\n const configPath = path.join(dir, file)\n\n if (!fs.existsSync(configPath)) continue\n\n try {\n const source = fs.readFileSync(configPath, 'utf-8')\n\n return INFRA_KIT_VITE_SPECIFIERS.some((specifier) => {\n return source.includes(specifier)\n })\n } catch {\n return false\n }\n }\n\n return false\n}\n\n/**\n * True when `<dir>`'s vite config wires the `infraKit()` PLUGIN specifically \u2014 not just the raw\n * `infraKitDev()` helper it wraps (see {@link usesInfraKitVite}, which matches either). Only the\n * plugin watches `.infra-kit/dev-context` and restarts vite when the resolved proxy changes; a\n * config that calls the helper directly bakes its proxy at config load and will not react to a\n * backend recovering mid-session (see `dev-server.ts`'s boot warning for this).\n *\n * No structural signal exists to check instead: the plugin writes nothing to disk at config load,\n * so this is the same conservative text match as {@link usesInfraKitVite} \u2014 a config source read,\n * not a module load. The substring is the plugin's call syntax, `infraKit(`; it cannot false-match\n * `infraKitDev(`, whose next character after `infraKit` is `D`, not `(`. A false negative (e.g. the\n * plugin re-exported from a shared preset under a different call shape) only costs a spurious\n * warning \u2014 never a missed one \u2014 which is the safe direction here.\n */\nexport function usesInfraKitVitePlugin(dir: string): boolean {\n for (const file of VITE_CONFIG_FILES) {\n const configPath = path.join(dir, file)\n\n if (!fs.existsSync(configPath)) continue\n\n try {\n return fs.readFileSync(configPath, 'utf-8').includes('infraKit(')\n } catch {\n return false\n }\n }\n\n return false\n}\n\n/** True when `<dir>/package.json` declares a non-empty `scripts.dev`. */\nfunction hasDevScript(dir: string): boolean {\n const pkgPath = path.join(dir, 'package.json')\n\n if (!fs.existsSync(pkgPath)) return false\n\n try {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as { scripts?: Record<string, string> }\n\n return typeof pkg.scripts?.dev === 'string' && pkg.scripts.dev.length > 0\n } catch {\n return false\n }\n}\n\n/**\n * Discover every `apps/<app>/ui` whose package.json declares a `dev` script \u2014 the frontends\n * `infra-kit dev --ui` runs (via one delegated `turbo run dev`). Lenient: no `apps/` dir \u2192 `[]`\n * (UIs are optional), unlike {@link discoverApiApps} which requires it.\n */\nexport function discoverUiApps(root: string): DiscoveredUiApp[] {\n const appsDir = path.join(root, 'apps')\n const apps: DiscoveredUiApp[] = []\n\n if (!fs.existsSync(appsDir)) return apps\n\n const appDirs = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((dirent) => {\n return dirent.isDirectory()\n })\n .map((dirent) => {\n return dirent.name\n })\n\n for (const appName of appDirs) {\n const uiPath = path.join(appsDir, appName, 'ui')\n\n if (fs.existsSync(uiPath) && hasDevScript(uiPath)) {\n apps.push({\n name: appName,\n packageName: getPackageName(uiPath, appName),\n path: uiPath,\n managedPort: usesInfraKitVite(uiPath),\n })\n }\n }\n\n return apps\n}\n\n/** Normalize the `--app` include list: drop empties, and collapse an empty list to `null`. */\nexport function normalizeAppInclude(include?: string[] | null): string[] | null {\n const filtered = include?.filter(Boolean) ?? []\n\n return filtered.length > 0 ? filtered : null\n}\n\n/**\n * Infer the current app's folder name from `startDir`, so a per-app script can\n * run `infra-kit dev --self` without hardcoding its own app name. Walks up to the\n * monorepo root (via {@link findMonorepoRoot}), then takes the first path segment\n * of `startDir` relative to `<root>/apps` \u2014 e.g. `apps/config-handler/api` and\n * `apps/config-handler` both resolve to `config-handler`. Throws when `startDir`\n * isn't inside `<root>/apps/<app>/...` (repo root, or an unrelated path).\n *\n * @example\n * resolveSelfAppName('/repo/apps/config-handler/api') // => 'config-handler'\n */\nexport function resolveSelfAppName(startDir: string): string {\n const root = findMonorepoRoot(startDir)\n const relative = path.relative(path.join(root, 'apps'), startDir)\n const firstSegment = relative.split(path.sep)[0]\n const isOutsideApps = relative === '' || relative.startsWith('..') || path.isAbsolute(relative)\n\n if (isOutsideApps || !firstSegment) {\n throw new Error(\n `--self: not inside an apps/<app> directory (cwd: ${startDir}). Run from an app folder or use --app=<name>.`,\n )\n }\n\n return firstSegment\n}\n\n/** App-part directory names that are apps in their own right, never shared packages. See {@link getPackageDistDirs}. */\nconst APP_PART_DIRS = new Set(['api', 'ui'])\n\n/** `<dir>/dist` when it exists and is a directory, else `undefined`. */\nconst existingDistDir = (dir: string): string | undefined => {\n const distDir = path.join(dir, 'dist')\n\n return fs.existsSync(distDir) && fs.statSync(distDir).isDirectory() ? distDir : undefined\n}\n\n/** Immediate subdirectory names of `dir`, or `[]` when `dir` does not exist. */\nconst subdirNames = (dir: string): string[] => {\n if (!fs.existsSync(dir)) return []\n\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .filter((d) => {\n return d.isDirectory()\n })\n .map((d) => {\n return d.name\n })\n}\n\n/**\n * Existing dist directories of every SHARED workspace package \u2014 the compiled outputs `turbo watch`\n * rewrites. Watched (alongside app dist) because editing a shared lib rewrites only the lib's `dist`,\n * never the dependent app's, so a package-dist change is the only signal that a lib was rebuilt.\n *\n * Two homes, because the pnpm workspace globs cover `packages/<pkg>` as well as `apps/<app>/<part>`:\n * - `packages/<pkg>/dist` \u2014 the obvious one.\n * - `apps/<app>/<part>/dist` where `<part>` is neither `api` nor `ui` and the dir is a real workspace\n * member (it has a `package.json`).\n *\n * `api`/`ui` parts are excluded deliberately: an api's dist is already covered by {@link getAppDistDirs},\n * and treating a frontend's dist as a shared package would bounce every backend on a UI rebuild.\n */\n// A shared library may legally live beside the app that owns it \u2014 hulyo's `@pkg/ai-mcp` is `apps/ai/mcp`,\n// and two backends depend on it. Scanning only `packages` left such a package watched by nobody: turbo\n// rebuilt its dist, the runner never saw the change, and every dependent backend kept serving stale code.\nexport function getPackageDistDirs(root: string): string[] {\n const dirs: string[] = []\n\n for (const name of subdirNames(path.join(root, 'packages'))) {\n const distDir = existingDistDir(path.join(root, 'packages', name))\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n\n const appsDir = path.join(root, 'apps')\n\n for (const app of subdirNames(appsDir)) {\n for (const part of subdirNames(path.join(appsDir, app))) {\n if (APP_PART_DIRS.has(part)) continue\n\n const partDir = path.join(appsDir, app, part)\n\n // A workspace member, not a stray build artifact directory.\n if (!fs.existsSync(path.join(partDir, 'package.json'))) continue\n\n const distDir = existingDistDir(partDir)\n\n if (distDir !== undefined) dirs.push(distDir)\n }\n }\n\n return dirs\n}\n\n/** Existing `<app.path>/dist` directories for the given apps (order preserved). */\nexport function getAppDistDirs(apps: Array<{ path: string }>): string[] {\n return apps\n .map((app) => {\n return path.join(app.path, 'dist')\n })\n .filter((dir) => {\n return fs.existsSync(dir)\n })\n}\n\n/** How a watched dist change should be routed. */\nexport interface ChangeClassification {\n kind: 'app' | 'package'\n /** For app changes: the matched app dist dir (undefined when nothing matched). */\n app?: string\n /** For package changes: the matched `packages/<pkg>/dist` dir (the change identity used to scope restarts). */\n packageDir?: string\n}\n\n/**\n * Route a changed compiled-output path: a `packages/<pkg>/dist` change is a shared-package\n * rebuild \u2014 the matched package dist dir is returned so the caller can restart only the apps\n * whose dependency closure includes it. An `<app>/dist` change restarts only that app (the\n * matched app dist dir is returned; `undefined` when the path matches neither). Package matches\n * take precedence.\n */\nexport function classifyDistChange(\n changedPath: string,\n appDistDirs: string[],\n packageDistDirs: string[],\n): ChangeClassification {\n const normalized = path.normalize(changedPath)\n const isInside = (dir: string): boolean => {\n const normalizedDir = path.normalize(dir)\n\n return normalized === normalizedDir || normalized.startsWith(normalizedDir + path.sep)\n }\n\n const matchedPackageDir = packageDistDirs.find(isInside)\n\n if (matchedPackageDir) {\n return { kind: 'package', packageDir: matchedPackageDir }\n }\n\n const matchedDir = appDistDirs.find(isInside)\n\n return { kind: 'app', app: matchedDir }\n}\n", "/**\n * Pure resolution of a named dev preset into a concrete run plan.\n *\n * A preset (declared under `devServersPresets` in the per-project infra-kit.json) names\n * launch targets (`client/api`, `client/ui`, with `*` allowed in the app position), optional\n * per-target `watchDeps` (api + ui), per-route proxy-source overrides, and an `orca` layout\n * flag. This module turns that declarative shape into a flat {@link ResolvedPreset}\n * the runner consumes. Side-effect free: the discovered app parts are passed in\n * (never read from disk here), so resolution is fully unit-testable.\n *\n * Every target key names exactly one workspace package \u2014 the app folder plus the part\n * (`apps/<app>/api` or `apps/<app>/ui`). A bare `<app>` is not a package and is rejected.\n */\nimport type { DevPreset, DevPresets, ProxySource } from 'src/lib/infra-kit-config'\n\n/** The two launchable halves of an `apps/<app>` folder. */\nexport type AppPart = 'api' | 'ui'\n\n/** One concrete thing to launch: a single part of a single app. */\nexport interface ResolvedTarget {\n /** App folder name (e.g. `client`). */\n app: string\n /** Which half of the app to launch. */\n part: AppPart\n /**\n * Participate in dependency-closure watching (uniform for api + ui): react to a change in\n * this target's own workspace-dependency closure. Default `true` (opt-in participation).\n * Resolution is specificity-ordered: an explicit value on a more-specific key (a concrete\n * app, or an explicit `/part`) wins over a `*` glob; at equal specificity an explicit\n * `false` wins over `true` (order-independent opt-out). See {@link resolveWatch}.\n */\n watchDeps: boolean\n}\n\n/** Which apps have an `api` / `ui` part on disk \u2014 the resolver's view of discovery. */\nexport interface DiscoveredParts {\n /** App names that have `apps/<app>/api`. */\n api: string[]\n /** App names that have `apps/<app>/ui`. */\n ui: string[]\n}\n\n/** A fully-resolved preset: the flat run plan derived from its declarative shape. */\nexport interface ResolvedPreset {\n /** Every (app, part) to launch, de-duplicated. */\n targets: ResolvedTarget[]\n /** Run each target in its own Orca pane. */\n orca: boolean\n /**\n * app \u2192 (route path \u2192 source) overrides, as DECLARED by the preset.\n *\n * Not an input to proxy resolution, and never has been: the vite helper derives a route's source from\n * the dev-context fragments the runner writes, so a route is local iff its backend is actually up. This\n * map is the declared INTENT, and it has two readers:\n * - `validatePresetProxy` \u2014 the STATIC check, run by `infra-kit audit` and the bare-invocation wizard.\n * Note it does NOT run on the `infra-kit dev <preset>` path, so it cannot be relied on to have\n * caught anything by the time a run starts;\n * - `local-pairing.ts` \u2014 the RUNTIME check, which folds a `local` pin into the set of packages the run\n * intended to serve locally, and refuses when one of them is not actually up.\n */\n proxy: Record<string, Record<string, ProxySource>>\n /** Apps whose `api` part is launched \u2014 their backends are local (derived). */\n localApps: string[]\n /** Concretely-named `<app>/<part>` targets that matched no discovered app/part (for a warning). */\n unmatched: string[]\n}\n\n/** The target keys resolution falls back to when a preset omits `apps`: every discovered package. */\nconst ALL_TARGETS_KEYS: NonNullable<DevPreset['apps']> = { '*/api': {}, '*/ui': {} }\n\n/** A preset target key that does not name an `<app>/<part>` package. */\nexport interface PresetKeyIssue {\n /** Preset name the bad key is under. */\n preset: string\n /** The offending key, verbatim. */\n key: string\n /** Human-readable, actionable explanation (already prefixed with the preset name). */\n message: string\n}\n\ninterface ParsedKey {\n /** App name or `*` (all discovered apps). */\n appGlob: string\n /** The single part the key selects. */\n part: AppPart\n}\n\n/**\n * Explain why `key` is not a valid target, or null when it parses. Keys name one workspace\n * package, so the `/api`|`/ui` part is mandatory \u2014 a bare `client` names a folder, not a package.\n */\nexport const explainTargetKey = (key: string): string | null => {\n const segments = key.split('/')\n const [appGlob, part] = segments\n\n if (segments.length !== 2 || !appGlob) {\n return `devServersPresets: invalid target \"${key}\" (expected \"<app>/api\" or \"<app>/ui\")`\n }\n\n if (part !== 'api' && part !== 'ui') {\n return `devServersPresets: invalid target part \"${part}\" in \"${key}\" (expected \"api\" or \"ui\")`\n }\n\n return null\n}\n\n/**\n * Parse a preset target key into an app glob + its part. Throws when the key is not an\n * `<app>/<part>` package identity (see {@link explainTargetKey}).\n *\n * A `*` app glob is legal (`*` plus a part), and expands to every discovered app.\n *\n * @example\n * parseTargetKey('client/api') // => { appGlob: 'client', part: 'api' }\n */\nexport const parseTargetKey = (key: string): ParsedKey => {\n const error = explainTargetKey(key)\n\n if (error) {\n throw new Error(error)\n }\n\n const [appGlob, part] = key.split('/') as [string, AppPart]\n\n return { appGlob, part }\n}\n\n/** Every `preset \u2192 invalid target key` in the map, with the reason (empty when all keys parse). */\nexport const validatePresetKeys = (presets: DevPresets): PresetKeyIssue[] => {\n const issues: PresetKeyIssue[] = []\n\n for (const [preset, def] of Object.entries(presets)) {\n for (const key of Object.keys(def.apps ?? {})) {\n const error = explainTargetKey(key)\n\n if (error) {\n issues.push({ preset, key, message: `preset \"${preset}\": ${error}` })\n }\n }\n }\n\n return issues\n}\n\n/** App names that have `part` on disk, per the discovery result. */\nconst appsWithPart = (discovered: DiscoveredParts, part: AppPart): string[] => {\n return part === 'api' ? discovered.api : discovered.ui\n}\n\n/** Every discovered app name (union of api + ui halves), sorted for deterministic output. */\nconst allApps = (discovered: DiscoveredParts): string[] => {\n return [...new Set([...discovered.api, ...discovered.ui])].sort()\n}\n\n/** Stable `app/part` identity key for de-duplicating targets across preset keys. */\nconst targetId = (app: string, part: AppPart): string => {\n return `${app}/${part}`\n}\n\n/** A resolved target plus the provenance the merge needs to order later keys by specificity. */\ninterface ResolvedTargetInternal extends ResolvedTarget {\n /** Specificity rank of the key that set `watchDeps` (see {@link keyRank}) \u2014 a higher rank wins. */\n rank: number\n /** Whether `watchDeps` came from an explicit preset value (vs the participate-default). */\n explicitValue: boolean\n}\n\ninterface ResolveState {\n targets: Map<string, ResolvedTargetInternal>\n proxy: Record<string, Record<string, ProxySource>>\n unmatched: string[]\n}\n\n/**\n * Specificity rank of a preset key, higher = more specific. Every key names a part, so the\n * only axis left is the app: a concrete `client/api` (1) beats a `*` glob key (0).\n */\nconst keyRank = (isGlob: boolean): number => {\n return isGlob ? 0 : 1\n}\n\n/**\n * Merge a preset key's `watchDeps` into any prior resolution for the same target. A key that\n * omits `watchDeps` never clobbers a prior explicit value (and, absent any explicit value,\n * seeds the participate-default `true`). A more-specific key ({@link keyRank}) wins in either\n * direction, so a `*` glob cannot override a concrete `client/api` and vice-versa. Two explicit\n * keys can never tie: each target is named by at most one key per rank (one glob, one concrete),\n * so the merge is order-independent.\n */\nconst resolveWatch = (\n prior: ResolvedTargetInternal | undefined,\n next: { watchDeps: boolean | undefined; rank: number },\n): { watchDeps: boolean; rank: number; explicitValue: boolean } => {\n // This key configured nothing \u2192 keep the prior resolution, or seed the participate-default.\n if (next.watchDeps === undefined) {\n return prior ?? { watchDeps: true, rank: next.rank, explicitValue: false }\n }\n\n // No prior explicit value (fresh, or only a default) \u2192 this explicit value takes it.\n if (!prior || !prior.explicitValue) {\n return { watchDeps: next.watchDeps, rank: next.rank, explicitValue: true }\n }\n\n // Two explicit values: the more-specific key wins, in either direction.\n return next.rank > prior.rank ? { watchDeps: next.watchDeps, rank: next.rank, explicitValue: true } : prior\n}\n\n/**\n * Fold one (app, part) into the accumulator: record a target when the part exists,\n * merge `watchDeps` with any prior target of the same identity by specificity\n * ({@link resolveWatch}), and flag a named-but-missing package as unmatched\n * (glob-expanded misses are silent).\n */\nconst addTarget = (\n state: ResolveState,\n discovered: DiscoveredParts,\n spec: { app: string; part: AppPart; watchDeps: boolean | undefined; isGlob: boolean },\n): void => {\n const { app, part, watchDeps, isGlob } = spec\n\n if (!appsWithPart(discovered, part).includes(app)) {\n // A glob expands over discovery, so its misses are expected; a concretely-named\n // `<app>/<part>` that can't be found is a mistake worth surfacing.\n if (!isGlob) {\n state.unmatched.push(targetId(app, part))\n }\n\n return\n }\n\n const id = targetId(app, part)\n const merged = resolveWatch(state.targets.get(id), { watchDeps, rank: keyRank(isGlob) })\n\n state.targets.set(id, { app, part, ...merged })\n}\n\n/**\n * Resolve a preset against the discovered app parts. Expands `*` app globs,\n * de-duplicates targets, derives the local-backend set from the launched `api`\n * targets, and collects per-app proxy overrides. Unknown app/route names are\n * tolerated (a missing named target lands in `unmatched`, not an exception) so a\n * stale preset degrades gracefully \u2014 but a key that is not an `<app>/<part>`\n * package identity throws, since it can't be resolved at all.\n *\n * @example\n * resolvePreset(\n * { apps: { 'client/ui': {}, 'client/api': { watchDeps: false } } },\n * { api: ['client'], ui: ['client'] },\n * )\n * // => { targets: [{ app: 'client', part: 'ui', watchDeps: true }, // default participate\n * // { app: 'client', part: 'api', watchDeps: false }], // explicit opt-out\n * // orca: false, proxy: {}, localApps: ['client'], unmatched: [] }\n */\nexport const resolvePreset = (preset: DevPreset, discovered: DiscoveredParts): ResolvedPreset => {\n const entries = Object.entries(preset.apps ?? ALL_TARGETS_KEYS)\n const state: ResolveState = { targets: new Map(), proxy: {}, unmatched: [] }\n\n for (const [key, cfg] of entries) {\n const { appGlob, part } = parseTargetKey(key)\n const isGlob = appGlob === '*'\n const apps = isGlob ? allApps(discovered) : [appGlob]\n\n for (const app of apps) {\n addTarget(state, discovered, { app, part, watchDeps: cfg.watchDeps, isGlob })\n\n if (cfg.proxy) {\n state.proxy[app] = { ...(state.proxy[app] ?? {}), ...cfg.proxy }\n }\n }\n }\n\n const targets: ResolvedTarget[] = [...state.targets.values()].map(({ app, part, watchDeps }) => {\n return { app, part, watchDeps }\n })\n const localApps = [\n ...new Set(\n targets\n .filter((t) => {\n return t.part === 'api'\n })\n .map((t) => {\n return t.app\n }),\n ),\n ]\n\n return { targets, orca: preset.orca ?? false, proxy: state.proxy, localApps, unmatched: state.unmatched }\n}\n\n/** What the run launched, as passed to {@link deriveTargetLabel}. */\nexport interface TargetLabelInput {\n /** Named preset (`infra-kit dev <preset>`) \u2014 its name is the label when present. */\n preset?: string\n /** The `<app>/<part>` package keys actually being launched, after preset resolution and `--app`. */\n running: string[]\n /** Every `<app>/<part>` package key discovered in the monorepo. */\n discovered: string[]\n}\n\n/**\n * The header's target label. A named preset labels itself; otherwise the label is the set of\n * `<app>/<part>` packages actually launching, collapsing to `*` when that set is everything\n * discovered. Never a bare app name: `client` is not a target anywhere in this system (see\n * {@link parseTargetKey}) and would hide which half of the app is running \u2014 the whole point of\n * the wizard's part-level selection.\n *\n * @example\n * deriveTargetLabel({ running: ['client/ui', 'client/api'], discovered: ['client/api', 'client/ui', 'seo/ui'] })\n * // => 'client/api + client/ui'\n * deriveTargetLabel({ running: ['client/api'], discovered: ['client/api'] }) // => '*'\n * deriveTargetLabel({ preset: 'full', running: ['client/api'], discovered: ['client/api', 'seo/ui'] }) // => 'full'\n */\nexport const deriveTargetLabel = (input: TargetLabelInput): string => {\n if (input.preset != null) {\n return input.preset\n }\n if (input.running.length === 0) {\n return 'nothing'\n }\n\n const running = new Set(input.running)\n const isEverything = input.discovered.every((key) => {\n return running.has(key)\n })\n\n return isEverything ? '*' : [...running].sort().join(' + ')\n}\n\n/** A devServersPresets proxy-locality violation surfaced by the audit. */\nexport interface PresetProxyIssue {\n /** Preset name the violation is in. */\n preset: string\n /** Frontend app folder the override is under (e.g. `client`). */\n app: string\n /** Route path forced to a source (e.g. `/api`). */\n route: string\n /** Backend pkg the route maps to; undefined when the route is not declared in the frontend config. */\n pkg?: string\n /** `unknown-route` = route absent from the frontend config; `backend-not-launched` = local target not launched. */\n kind: 'unknown-route' | 'backend-not-launched'\n /** Human-readable, actionable explanation. */\n message: string\n}\n\n/**\n * Cross-file lookups the proxy validator needs, kept injectable so the rule stays\n * filesystem-free (and unit-testable). The impure side (audit) builds these from\n * discovery + each frontend's loaded `infra-kit.config.ts`.\n */\nexport interface PresetProxyContext {\n /** Discovered app parts, for resolving each preset's launch set. */\n discovered: DiscoveredParts\n /** App folder name \u2192 its `apps/<app>/api` package name. */\n apiPkgByApp: Record<string, string>\n /** (frontend app folder, route path) \u2192 backend pkg from that frontend's config; undefined when the route is absent. */\n routePkg: (app: string, route: string) => string | undefined\n}\n\ninterface CheckLocalRouteArgs {\n preset: string\n app: string\n route: string\n launchedPkgs: ReadonlySet<string>\n ctx: PresetProxyContext\n}\n\n/** App folder whose `api` package is `pkg` (for the remediation hint), or undefined. */\nconst ownerApp = (apiPkgByApp: Record<string, string>, pkg: string): string | undefined => {\n return Object.keys(apiPkgByApp).find((app) => {\n return apiPkgByApp[app] === pkg\n })\n}\n\n/**\n * Validate one `route \u2192 'local'` override: the route must be declared in the\n * frontend config, and the backend pkg it maps to must be in the preset's launched\n * set. Returns the issue, or null when the override is satisfiable.\n */\nconst checkLocalRoute = ({ preset, app, route, launchedPkgs, ctx }: CheckLocalRouteArgs): PresetProxyIssue | null => {\n const pkg = ctx.routePkg(app, route)\n\n if (pkg === undefined) {\n return {\n preset,\n app,\n route,\n kind: 'unknown-route',\n message: `preset \"${preset}\": proxy override \"${route}\" on \"${app}\" names a route not declared in ${app}'s infra-kit.config.ts dev.proxy.routes`,\n }\n }\n\n if (launchedPkgs.has(pkg)) {\n return null\n }\n\n const owner = ownerApp(ctx.apiPkgByApp, pkg)\n const hint = owner ? `add \"${owner}/api\" to the preset` : `launch the api whose package is \"${pkg}\"`\n\n return {\n preset,\n app,\n route,\n pkg,\n kind: 'backend-not-launched',\n message: `preset \"${preset}\": proxy override \"${route}\" \u2192 \"local\" requires backend \"${pkg}\" to run locally, but the preset does not launch it \u2014 ${hint}, or set \"${route}\" to \"cloud\"`,\n }\n}\n\n/**\n * Audit every preset's per-route proxy overrides: a route pinned to `local` is only\n * valid when the backend package it resolves to (per the frontend's\n * `infra-kit.config.ts`) is actually launched by that same preset. Catches the\n * `{ \"client/ui\": { \"proxy\": { \"/api\": \"local\" } } }` case where no local backend\n * is running to serve `/api`. `cloud` overrides are always satisfiable and skipped.\n *\n * @example\n * validatePresetProxy(\n * { 'client-remote': { apps: { 'client/ui': { proxy: { '/api': 'local' } } } } },\n * { discovered: { api: ['client'], ui: ['client'] }, apiPkgByApp: { client: 'backend-api' },\n * routePkg: () => 'backend-api' },\n * )\n * // => [{ preset: 'client-remote', app: 'client', route: '/api', pkg: 'backend-api',\n * // kind: 'backend-not-launched', message: '\u2026' }]\n */\nexport const validatePresetProxy = (presets: DevPresets, ctx: PresetProxyContext): PresetProxyIssue[] => {\n const issues: PresetProxyIssue[] = []\n\n for (const [preset, def] of Object.entries(presets)) {\n const resolved = resolvePreset(def, ctx.discovered)\n const launchedPkgs = new Set(\n resolved.localApps\n .map((app) => {\n return ctx.apiPkgByApp[app]\n })\n .filter((pkg): pkg is string => {\n return pkg !== undefined\n }),\n )\n\n for (const [app, routes] of Object.entries(resolved.proxy)) {\n for (const [route, source] of Object.entries(routes)) {\n if (source !== 'local') {\n continue\n }\n\n const issue = checkLocalRoute({ preset, app, route, launchedPkgs, ctx })\n\n if (issue) {\n issues.push(issue)\n }\n }\n }\n }\n\n return issues\n}\n"],
5
+ "mappings": "AAQA,UAAYA,MAAQ,UACpB,UAAYC,MAAU,YAYf,SAASC,EAAiBC,EAA0B,CACzD,IAAIC,EAAaD,EAEjB,QAASE,EAAI,EAAGA,EAAI,GAAIA,IAAK,CAC3B,IAAMC,EAAqB,OAAKF,EAAY,qBAAqB,EAEjE,GAAO,aAAWE,CAAa,EAC7B,OAAOF,EAETA,EAAkB,UAAQA,CAAU,CACtC,CAEA,MAAM,IAAI,MAAM,oDAAoD,CACtE,CAGO,SAASG,EAAeC,EAAiBC,EAAyB,CACvE,IAAMC,EAAe,OAAKF,EAAS,cAAc,EAEjD,GAAI,CAAI,aAAWE,CAAO,EAAG,OAAOD,EAEpC,GAAI,CACF,IAAME,EAAM,KAAK,MAAS,eAAaD,EAAS,OAAO,CAAC,EAExD,OAAO,OAAOC,EAAI,MAAS,SAAWA,EAAI,KAAOF,CACnD,MAAQ,CACN,OAAOA,CACT,CACF,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F,IAAQ,OACV,MAAO,CACL,OAAA9B,EACA,IAAAM,EACA,MAAA0B,EACA,KAAM,gBACN,QAAS,WAAWhC,CAAM,sBAAsBgC,CAAK,SAAS1B,CAAG,mCAAmCA,CAAG,yCACzG,EAGF,GAAI2B,EAAa,IAAIH,CAAG,EACtB,OAAO,KAGT,IAAMK,EAAQP,EAASM,EAAI,YAAaJ,CAAG,EACrCM,EAAOD,EAAQ,QAAQA,CAAK,sBAAwB,oCAAoCL,CAAG,IAEjG,MAAO,CACL,OAAA9B,EACA,IAAAM,EACA,MAAA0B,EACA,IAAAF,EACA,KAAM,uBACN,QAAS,WAAW9B,CAAM,sBAAsBgC,CAAK,sCAAiCF,CAAG,8DAAyDM,CAAI,aAAaJ,CAAK,cAC1K,CACF,EAkBaK,EAAsB,CAACvC,EAAqBoC,IAAgD,CACvG,IAAMnC,EAA6B,CAAC,EAEpC,OAAW,CAACC,EAAQC,CAAG,IAAK,OAAO,QAAQH,CAAO,EAAG,CACnD,IAAMwC,EAAWpB,EAAcjB,EAAKiC,EAAI,UAAU,EAC5CD,EAAe,IAAI,IACvBK,EAAS,UACN,IAAKhC,GACG4B,EAAI,YAAY5B,CAAG,CAC3B,EACA,OAAQwB,GACAA,IAAQ,MAChB,CACL,EAEA,OAAW,CAACxB,EAAKiC,CAAM,IAAK,OAAO,QAAQD,EAAS,KAAK,EACvD,OAAW,CAACN,EAAOQ,CAAM,IAAK,OAAO,QAAQD,CAAM,EAAG,CACpD,GAAIC,IAAW,QACb,SAGF,IAAMC,EAAQV,EAAgB,CAAE,OAAA/B,EAAQ,IAAAM,EAAK,MAAA0B,EAAO,aAAAC,EAAc,IAAAC,CAAI,CAAC,EAEnEO,GACF1C,EAAO,KAAK0C,CAAK,CAErB,CAEJ,CAEA,OAAO1C,CACT",
6
+ "names": ["fs", "path", "findMonorepoRoot", "startDir", "currentDir", "i", "workspaceFile", "getPackageName", "apiPath", "appName", "pkgPath", "pkg", "discoverApiApps", "root", "appsDir", "apps", "appDirs", "dirent", "serverlessPath", "VITE_CONFIG_FILES", "INFRA_KIT_VITE_SPECIFIERS", "usesInfraKitVite", "dir", "file", "configPath", "source", "specifier", "usesInfraKitVitePlugin", "hasDevScript", "discoverUiApps", "uiPath", "normalizeAppInclude", "include", "filtered", "resolveSelfAppName", "relative", "firstSegment", "APP_PART_DIRS", "existingDistDir", "distDir", "subdirNames", "d", "getPackageDistDirs", "dirs", "name", "app", "part", "partDir", "getAppDistDirs", "classifyDistChange", "changedPath", "appDistDirs", "packageDistDirs", "normalized", "isInside", "normalizedDir", "matchedPackageDir", "ALL_TARGETS_KEYS", "explainTargetKey", "key", "segments", "appGlob", "part", "parseTargetKey", "error", "validatePresetKeys", "presets", "issues", "preset", "def", "appsWithPart", "discovered", "allApps", "targetId", "app", "keyRank", "isGlob", "resolveWatch", "prior", "next", "addTarget", "state", "spec", "watchDeps", "id", "merged", "resolvePreset", "entries", "cfg", "apps", "targets", "localApps", "t", "deriveTargetLabel", "input", "running", "ownerApp", "apiPkgByApp", "pkg", "checkLocalRoute", "route", "launchedPkgs", "ctx", "owner", "hint", "validatePresetProxy", "resolved", "routes", "source", "issue"]
7
+ }
@@ -1,10 +1,10 @@
1
- import{P as f,l as G,pa as $,r as F}from"./chunk-J7KIXQRB.js";import{execFile as ne,execFileSync as ae}from"node:child_process";import b from"node:process";var se=5e3,ie=100,W=2e3,J="/bin/ps",ce=1e3,B=["-eo","pid=,ppid=,pgid=,lstart="],V=8<<20,H=e=>e.split(`
2
- `).flatMap(r=>{let[t,o,n,...a]=r.trim().split(/\s+/);if(t==null||o==null||n==null)return[];let c=Number(t),s=Number(o),l=Number(n);return!Number.isInteger(c)||!Number.isInteger(s)||!Number.isInteger(l)?[]:[{pid:c,ppid:s,pgid:l,lstart:a.join(" ")}]}),j=e=>{let r=new Map;for(let t of e)t.pid===t.pgid&&r.set(t.pgid,t.lstart);return r},le=(e,r,t)=>{let o=j(r);return q(e,r,t).flatMap(n=>{let a=o.get(n);return a==null||a===""?[]:[{pgid:n,leaderStart:a}]})},K=(e,r)=>{let t=j(r);return e.flatMap(({pgid:o,leaderStart:n})=>t.get(o)===n?[o]:[])},U=(e,r)=>K(e,r).flatMap(t=>{try{b.kill(-t,"SIGKILL")}catch{return[]}return[t]}),q=(e,r,t)=>{let o=new Map;for(let s of r){let l=o.get(s.ppid);l?l.push(s):o.set(s.ppid,[s])}let n=new Set([e]),a=new Set([e]),c=[e];for(let s=0;s<c.length;s+=1)for(let l of o.get(c[s]??-1)??[])a.has(l.pid)||(a.add(l.pid),n.add(l.pgid),c.push(l.pid));return[...n].filter(s=>s>1&&s!==t)},L=()=>{try{return H(ae(J,[...B],{encoding:"utf8",maxBuffer:V}))}catch{return[]}},ue=async()=>new Promise(e=>{ne(J,[...B],{encoding:"utf8",maxBuffer:V},(r,t)=>{e(r?[]:H(t))})}),pe=(e,r,t)=>t.some(o=>o.pid===e&&o.ppid===r),A=(e,r)=>{let t=r.find(o=>o.pid===b.pid)?.pgid;return q(e,r,t)},z=e=>{try{return b.kill(-e,0),!0}catch{return!1}},C=(e,r)=>{for(let t of e)try{b.kill(-t,r)}catch{}},P=new Set,de=(e,r,t)=>{let o=A(e,r),n=t.flatMap(a=>K(a,r));return[...new Set([...o,...n])]},X=()=>{let e=L(),r=[...P].map(t=>t());C(de(b.pid,e,r),"SIGKILL")},me=async e=>new Promise(r=>{setTimeout(r,e)}),_=async(e,r)=>{let t=Date.now()+r,o=e;for(;o.length>0&&Date.now()<t&&(o=o.filter(z),o.length!==0);)await me(ie);return o};function ur(e,r=se,t,o=L){e.unref();let n=!1,a=!1,c=[],s=null,l=()=>c;P.add(l);let m=()=>{s&&clearInterval(s),s=null},w=async()=>{await _(c.map(i=>i.pgid),W),P.delete(l)},y=i=>{let u=e.pid;if(u==null||a||n||i.length===0)return;let T=i.find(v=>v.pid===b.pid)?.pgid,S=le(u,i,T);S.length>0&&(c=S)},h=async()=>{e.pid==null||a||n||y(await ue())};y(L()),s=setInterval(()=>{h()},ce),s.unref();let R=i=>{n||t?.(i)};return e.on("exit",(i,u)=>{a=!0,m(),n||(U(c,o()),w()),R(`exited unexpectedly (code=${i??"null"}, signal=${u??"null"})`)}),e.on("error",i=>{R(`failed to spawn: ${i.message}`)}),{kill:async()=>{n=!0,m();let i=e.pid;if(i==null){P.delete(l);return}if(e.exitCode!==null||e.signalCode!==null){U(c,o()),await w();return}let u=o();if(u.length>0&&!pe(i,b.pid,u))return;let T=A(i,u);C(T,"SIGTERM");let S=await _(T,r);if(S.length===0){P.delete(l);return}let v=A(i,o()),D=[...new Set([...S,...v])].filter(z);C(D,"SIGKILL"),await _(D,W),P.delete(l)}}}import{constants as fe}from"node:os";import k from"node:process";var ge=["SIGINT","SIGTERM","SIGHUP"],Oe=fe.signals,be=2,N=e=>128+(Oe[e]??be),we=2e4,ye=e=>{k.exit(e)},he=(e,r)=>{k.on(e,r)},Pe=(e,r)=>{k.off(e,r)},xe=(e,r)=>{let t=setTimeout(e,r);return t.unref(),()=>{clearTimeout(t)}},I=e=>{try{k.stderr.write(e)}catch{}},Se=(e,r)=>{let t=r instanceof Error?`${r.message}
1
+ import{l as F}from"./chunk-Y3RW74TE.js";import{P as f,l as G,r as $}from"./chunk-D76UWTR5.js";import{execFile as oe,execFileSync as ne}from"node:child_process";import b from"node:process";var ae=5e3,se=100,W=2e3,J="/bin/ps",ie=1e3,B=["-eo","pid=,ppid=,pgid=,lstart="],V=8<<20,j=e=>e.split(`
2
+ `).flatMap(r=>{let[t,o,n,...a]=r.trim().split(/\s+/);if(t==null||o==null||n==null)return[];let c=Number(t),s=Number(o),l=Number(n);return!Number.isInteger(c)||!Number.isInteger(s)||!Number.isInteger(l)?[]:[{pid:c,ppid:s,pgid:l,lstart:a.join(" ")}]}),H=e=>{let r=new Map;for(let t of e)t.pid===t.pgid&&r.set(t.pgid,t.lstart);return r},ce=(e,r,t)=>{let o=H(r);return q(e,r,t).flatMap(n=>{let a=o.get(n);return a==null||a===""?[]:[{pgid:n,leaderStart:a}]})},K=(e,r)=>{let t=H(r);return e.flatMap(({pgid:o,leaderStart:n})=>t.get(o)===n?[o]:[])},U=(e,r)=>K(e,r).flatMap(t=>{try{b.kill(-t,"SIGKILL")}catch{return[]}return[t]}),q=(e,r,t)=>{let o=new Map;for(let s of r){let l=o.get(s.ppid);l?l.push(s):o.set(s.ppid,[s])}let n=new Set([e]),a=new Set([e]),c=[e];for(let s=0;s<c.length;s+=1)for(let l of o.get(c[s]??-1)??[])a.has(l.pid)||(a.add(l.pid),n.add(l.pgid),c.push(l.pid));return[...n].filter(s=>s>1&&s!==t)},L=()=>{try{return j(ne(J,[...B],{encoding:"utf8",maxBuffer:V}))}catch{return[]}},le=async()=>new Promise(e=>{oe(J,[...B],{encoding:"utf8",maxBuffer:V},(r,t)=>{e(r?[]:j(t))})}),ue=(e,r,t)=>t.some(o=>o.pid===e&&o.ppid===r),A=(e,r)=>{let t=r.find(o=>o.pid===b.pid)?.pgid;return q(e,r,t)},z=e=>{try{return b.kill(-e,0),!0}catch{return!1}},C=(e,r)=>{for(let t of e)try{b.kill(-t,r)}catch{}},P=new Set,pe=(e,r,t)=>{let o=A(e,r),n=t.flatMap(a=>K(a,r));return[...new Set([...o,...n])]},X=()=>{let e=L(),r=[...P].map(t=>t());C(pe(b.pid,e,r),"SIGKILL")},de=async e=>new Promise(r=>{setTimeout(r,e)}),_=async(e,r)=>{let t=Date.now()+r,o=e;for(;o.length>0&&Date.now()<t&&(o=o.filter(z),o.length!==0);)await de(se);return o};function cr(e,r=ae,t,o=L){e.unref();let n=!1,a=!1,c=[],s=null,l=()=>c;P.add(l);let m=()=>{s&&clearInterval(s),s=null},w=async()=>{await _(c.map(i=>i.pgid),W),P.delete(l)},y=i=>{let u=e.pid;if(u==null||a||n||i.length===0)return;let T=i.find(v=>v.pid===b.pid)?.pgid,S=ce(u,i,T);S.length>0&&(c=S)},h=async()=>{e.pid==null||a||n||y(await le())};y(L()),s=setInterval(()=>{h()},ie),s.unref();let R=i=>{n||t?.(i)};return e.on("exit",(i,u)=>{a=!0,m(),n||(U(c,o()),w()),R(`exited unexpectedly (code=${i??"null"}, signal=${u??"null"})`)}),e.on("error",i=>{R(`failed to spawn: ${i.message}`)}),{kill:async()=>{n=!0,m();let i=e.pid;if(i==null){P.delete(l);return}if(e.exitCode!==null||e.signalCode!==null){U(c,o()),await w();return}let u=o();if(u.length>0&&!ue(i,b.pid,u))return;let T=A(i,u);C(T,"SIGTERM");let S=await _(T,r);if(S.length===0){P.delete(l);return}let v=A(i,o()),D=[...new Set([...S,...v])].filter(z);C(D,"SIGKILL"),await _(D,W),P.delete(l)}}}import{constants as me}from"node:os";import k from"node:process";var fe=["SIGINT","SIGTERM","SIGHUP"],ge=me.signals,Oe=2,N=e=>128+(ge[e]??Oe),be=2e4,we=e=>{k.exit(e)},ye=(e,r)=>{k.on(e,r)},he=(e,r)=>{k.off(e,r)},Pe=(e,r)=>{let t=setTimeout(e,r);return t.unref(),()=>{clearTimeout(t)}},I=e=>{try{k.stderr.write(e)}catch{}},xe=(e,r)=>{let t=r instanceof Error?`${r.message}
3
3
  ${r.stack??"(no stack)"}`:String(r);I(`
4
4
  \u2717 Teardown failed while handling ${e}: ${t}
5
- `)},gr=({onSignal:e,exit:r=ye,register:t=he,unregister:o=Pe,forceReap:n=X,teardownDeadlineMs:a=we,setTimer:c=xe,describeStall:s=()=>"unknown",fileReport:l=()=>{}})=>{let m=null,w=null,y=new Map,h=()=>{for(let[i,u]of y)o(i,u);y.clear()},R=i=>{if(m!==null){if(i!==m)return;I(`
5
+ `)},mr=({onSignal:e,exit:r=we,register:t=ye,unregister:o=he,forceReap:n=X,teardownDeadlineMs:a=be,setTimer:c=Pe,describeStall:s=()=>"unknown",fileReport:l=()=>{}})=>{let m=null,w=null,y=new Map,h=()=>{for(let[i,u]of y)o(i,u);y.clear()},R=i=>{if(m!==null){if(i!==m)return;I(`
6
6
  \u26A0 Received ${i} again \u2014 force-quitting.
7
7
  `),w?.(),n(),h(),r(N(i));return}m=i,w=c(()=>{let u=`
8
8
  \u26A0 Teardown deadline exceeded at stage=${s()} after ${a}ms \u2014 force-quitting.
9
- `;I(u),l(u),n(),h(),r(N(i))},a),(async()=>{try{await e(i)}catch(u){Se(i,u)}finally{w?.(),h(),r(N(i))}})()};for(let i of ge){let u=()=>R(i);y.set(i,u),t(i,u)}return h};var Re=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),Y=e=>e instanceof Error&&Re.has(e.name),br=e=>{if(Y(e))return!0;let r=e?.cause;return Y(r)};import{loadDev as Te}from"@slip-stream-kit/config/internal";import ke from"node:path";var Ee=(e,r)=>{let t=new Set;for(let o of Object.values(e))for(let n of Object.keys($(o,r).proxy))t.add(n);return[...t]},ve=async(e,r)=>{let t={},o=[];return await Promise.all(r.map(async n=>{try{let c=(await Te(ke.join(e,"apps",n,"ui")))?.proxy?.routes;if(!c)return;t[n]=Object.fromEntries(Object.entries(c).map(([s,l])=>[s,l.packageName]))}catch(a){o.push({app:n,message:a instanceof Error?a.message:String(a)})}})),{routePkg:(n,a)=>t[n]?.[a],loadErrors:o}},xr=async(e,r,t,o)=>{let{routePkg:n,loadErrors:a}=await ve(e,Ee(r,t));return{ctx:{discovered:t,apiPkgByApp:Object.fromEntries(o.map(c=>[c.name,c.packageName])),routePkg:n},loadErrors:a}};import{$ as _e}from"zx";var d=class extends Error{code;data;constructor(r){super(r.message),this.name="OrcaError",this.code=r.code,this.data=r.data}},x=class extends Error{exitCode;stderrTail;constructor(r,t){super(`orca: stdout is not a JSON envelope (exit ${r??"signal"})`),this.name="OrcaMalformedError",this.exitCode=r,this.stderrTail=t}},g=class extends Error{constructor(){super("orca: command not found \u2014 the CLI is registered from Orca \u2192 Settings \u2192 Experimental \u2192 CLI"),this.name="OrcaAbsentError"}},Le=400,Ae=127,Ce=e=>typeof e=="object"&&e!==null&&e.code==="ENOENT",Ne=async e=>{try{return await _e({nothrow:!0,quiet:!0})`orca ${e} --json`}catch(r){throw Ce(r)?new g:r}},Ie=e=>{try{let r=JSON.parse(e);return typeof r=="object"&&r!==null&&typeof r.ok=="boolean"?r:null}catch{return null}},p=async e=>{let r=await Ne(e),t=Ie(r.stdout);if(f.debug({argv:e,ok:t?.ok,code:t?.error?.code,exitCode:r.exitCode},"orca"),!t)throw r.exitCode===Ae?new g:new x(r.exitCode,r.stderr.slice(-Le));if(!t.ok)throw new d(t.error??{code:"unknown",message:"orca: ok:false without an error payload"});return t.result};var Me=async()=>{try{let e=await p(["status"]);return f.debug({appVersion:e.runtime?.appVersion},"orca: status"),e.app?.running===!0&&e.runtime?.reachable===!0?"ready":"unreachable"}catch(e){return e instanceof g?"absent":(f.debug({error:e},"orca: status probe failed"),"unreachable")}};import{realpath as De}from"node:fs/promises";var O=async e=>{try{return await De(e)}catch{return e}};var Ge=async e=>{let[{repos:r=[]},t]=await Promise.all([p(["repo","list"]),O(e)]);for(let o of r)if(await O(o.path)===t)return{registered:!0,visibility:o.externalWorktreeVisibility};return{registered:!1}},Fe=async e=>{let{repo:r}=await p(["repo","add","--path",e]);return{visibility:r?.externalWorktreeVisibility}};var $e="500",We=async(e,r)=>{let[{worktrees:t=[]},o]=await Promise.all([p(["worktree","list","--repo",`path:${e}`,"--limit",$e]),O(r)]);for(let n of t)if(await O(n.path)===o)return!0;return!1};import Ue from"node:process";var Q="::",Je=e=>{let r=e.ORCA_WORKTREE_ID;if(!r)return null;let t=r.indexOf(Q);if(t<0)return null;let o=r.slice(t+Q.length);return o.length>0?o:null},Be=async(e,r=Ue.env)=>{let t=Je(r);if(t===null)return null;let o=await O(t);for(let n of e)if(await O(n)===o)return n;return null};var Z="200",M=async e=>{try{let r=await p(["terminal","list","--worktree",`path:${e}`,"--limit",Z]),t=r.truncated===!0;return t&&f.debug({cwd:e,limit:Z},"orca: terminal list truncated"),{terminals:r.terminals??[],truncated:t}}catch(r){if(r instanceof d&&r.code==="selector_not_found")return{terminals:[],truncated:!1};throw r}};var Ve=async e=>{try{return await p(["terminal","close","--worktree",`path:${e}`,"--all"]),"retired"}catch(r){if(r instanceof d&&r.code==="selector_not_found")return"not_found";if(r instanceof d&&r.code==="terminal_close_incomplete")return f.debug({cwd:e,error:r},"orca: surfaces not retired"),"retired";throw r}},He=async e=>{let{terminals:r}=await M(e);for(let o of r)await p(["terminal","close","--terminal",o.handle]);let t=await Ve(e);return r.length===0&&t==="not_found"?{closed:!1,skipped:"not_found"}:{closed:!0,count:r.length}},je=(e,r)=>r instanceof g?{closed:!1,skipped:"absent"}:r instanceof d?{closed:!1,error:r}:r instanceof x?{closed:!1,error:new d({code:"orca_malformed_output",message:r.message,data:{exitCode:r.exitCode,stderrTail:r.stderrTail}})}:(f.debug({cwd:e,error:r},"orca: close failed outside the Orca contract"),{closed:!1,error:new d({code:"orca_close_failed",message:r instanceof Error?r.message:String(r)})}),Ke=async(e,r)=>{if(r!=="ready")return{closed:!1,skipped:r};try{return await He(e)}catch(t){return je(e,t)}};import{setTimeout as qe}from"node:timers/promises";var ze=3,Xe=300,re=(e={})=>({attempts:e.attempts??ze,delayMs:e.delayMs??Xe,exhausted:!1}),Ye=async e=>{try{return{created:await p(e)}}catch(r){if(r instanceof d&&r.code==="selector_not_found")return{notSelectable:r};throw r}},Qe=async(e,r,t)=>{let o=t.exhausted?1:t.attempts,n=Array.from({length:o},(c,s)=>s+1),a;for(let c of n){let s=await Ye(e);if("created"in s)return s.created.terminal.handle;a=s.notSelectable,c<o&&await qe(t.delayMs)}throw t.exhausted=!0,new d({code:"orca_worktree_not_selectable",message:`orca: worktree ${r} is not selectable after ${o} attempt(s): ${a?.message??""}`,data:{cwd:r,attempts:o,cause:a?.data}})},ee=async(e,r)=>(await p(["terminal","split","--terminal",e,"--direction",r])).split.handle,Ze=async e=>{let{cwd:r,title:t,focus:o,layout:n,panes:a,poll:c=re()}=e,s=["terminal","create","--worktree",`path:${r}`,"--title",t,...o?["--focus"]:[]],l=await Qe(s,r,c),m=[l];return n==="full"&&(m.push(await ee(l,"horizontal")),a==="three-pane"&&m.push(await ee(l,"vertical"))),{handles:m,layout:n}};var er=e=>{let{branch:r}=e,t=G(r);return t?F(t):r};var lt=e=>typeof e=="object",E=async e=>(await e.body?.cancel(),{kind:"foreign",status:e.status,contentType:e.headers.get("content-type")}),ut=(e,r)=>{let t=r.contentType?.split(";")[0]?.trim(),o=t==null||t===""?`${r.status}`:`${r.status} ${t}`;return`port ${e} answered ${o}, not vite's ping \u2014 liveness cannot be verified`};var te={accept:"text/x-vite-ping"},rr=e=>e.kind==="api"?`http://127.0.0.1:${e.port}/__health`:`http://127.0.0.1:${e.port}/`,tr=(e,r)=>{try{return new URL(e,r)}catch{return null}},or=async(e,r)=>{let t=await fetch(e,{signal:r});return t.ok?(await t.body?.cancel(),"ok"):E(t)},nr=async(e,r)=>{let t=await fetch(e,{headers:te,redirect:"manual",signal:r});if(t.status===204)return"ok";if(t.status<300||t.status>=400)return E(t);let o=t.headers.get("location"),n=o==null?null:tr(o,e);if(n==null||n.origin!==new URL(e).origin)return E(t);await t.body?.cancel();let a=await fetch(n,{headers:te,redirect:"manual",signal:r});return a.status!==204?E(a):(await a.body?.cancel(),"ok")},pt=async e=>{let r=rr(e),t=AbortSignal.timeout(1500);try{return e.kind==="api"?await or(r,t):await nr(r,t)}catch{return"refused"}};import{DEFAULT_RELEASE_SLUG as oe,slugifyRelease as ar}from"@slip-stream-kit/config/internal";import{execFileSync as sr}from"node:child_process";var ir=e=>{try{let r=sr("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf-8"}).trim(),t=ar(r);return t===""?oe:t}catch{return oe}};export{xr as a,X as b,ur as c,N as d,gr as e,d as f,p as g,Me as h,Be as i,M as j,Ke as k,Ge as l,Fe as m,We as n,re as o,Ze as p,er as q,lt as r,ut as s,pt as t,ir as u,br as v};
10
- //# sourceMappingURL=chunk-TT7OQ4PI.js.map
9
+ `;I(u),l(u),n(),h(),r(N(i))},a),(async()=>{try{await e(i)}catch(u){xe(i,u)}finally{w?.(),h(),r(N(i))}})()};for(let i of fe){let u=()=>R(i);y.set(i,u),t(i,u)}return h};var Se=new Set(["ExitPromptError","AbortPromptError","PromptCancelledError"]),Y=e=>e instanceof Error&&Se.has(e.name),gr=e=>{if(Y(e))return!0;let r=e?.cause;return Y(r)};import{loadDev as Re}from"@slip-stream-kit/config/internal";import Te from"node:path";var ke=(e,r)=>{let t=new Set;for(let o of Object.values(e))for(let n of Object.keys(F(o,r).proxy))t.add(n);return[...t]},Ee=async(e,r)=>{let t={},o=[];return await Promise.all(r.map(async n=>{try{let c=(await Re(Te.join(e,"apps",n,"ui")))?.proxy?.routes;if(!c)return;t[n]=Object.fromEntries(Object.entries(c).map(([s,l])=>[s,l.packageName]))}catch(a){o.push({app:n,message:a instanceof Error?a.message:String(a)})}})),{routePkg:(n,a)=>t[n]?.[a],loadErrors:o}},hr=async(e,r,t,o)=>{let{routePkg:n,loadErrors:a}=await Ee(e,ke(r,t));return{ctx:{discovered:t,apiPkgByApp:Object.fromEntries(o.map(c=>[c.name,c.packageName])),routePkg:n},loadErrors:a}};import{$ as ve}from"zx";var d=class extends Error{code;data;constructor(r){super(r.message),this.name="OrcaError",this.code=r.code,this.data=r.data}},x=class extends Error{exitCode;stderrTail;constructor(r,t){super(`orca: stdout is not a JSON envelope (exit ${r??"signal"})`),this.name="OrcaMalformedError",this.exitCode=r,this.stderrTail=t}},g=class extends Error{constructor(){super("orca: command not found \u2014 the CLI is registered from Orca \u2192 Settings \u2192 Experimental \u2192 CLI"),this.name="OrcaAbsentError"}},_e=400,Le=127,Ae=e=>typeof e=="object"&&e!==null&&e.code==="ENOENT",Ce=async e=>{try{return await ve({nothrow:!0,quiet:!0})`orca ${e} --json`}catch(r){throw Ae(r)?new g:r}},Ne=e=>{try{let r=JSON.parse(e);return typeof r=="object"&&r!==null&&typeof r.ok=="boolean"?r:null}catch{return null}},p=async e=>{let r=await Ce(e),t=Ne(r.stdout);if(f.debug({argv:e,ok:t?.ok,code:t?.error?.code,exitCode:r.exitCode},"orca"),!t)throw r.exitCode===Le?new g:new x(r.exitCode,r.stderr.slice(-_e));if(!t.ok)throw new d(t.error??{code:"unknown",message:"orca: ok:false without an error payload"});return t.result};var Ie=async()=>{try{let e=await p(["status"]);return f.debug({appVersion:e.runtime?.appVersion},"orca: status"),e.app?.running===!0&&e.runtime?.reachable===!0?"ready":"unreachable"}catch(e){return e instanceof g?"absent":(f.debug({error:e},"orca: status probe failed"),"unreachable")}};import{realpath as Me}from"node:fs/promises";var O=async e=>{try{return await Me(e)}catch{return e}};var De=async e=>{let[{repos:r=[]},t]=await Promise.all([p(["repo","list"]),O(e)]);for(let o of r)if(await O(o.path)===t)return{registered:!0,visibility:o.externalWorktreeVisibility};return{registered:!1}},Ge=async e=>{let{repo:r}=await p(["repo","add","--path",e]);return{visibility:r?.externalWorktreeVisibility}};var $e="500",Fe=async(e,r)=>{let[{worktrees:t=[]},o]=await Promise.all([p(["worktree","list","--repo",`path:${e}`,"--limit",$e]),O(r)]);for(let n of t)if(await O(n.path)===o)return!0;return!1};import We from"node:process";var Q="::",Ue=e=>{let r=e.ORCA_WORKTREE_ID;if(!r)return null;let t=r.indexOf(Q);if(t<0)return null;let o=r.slice(t+Q.length);return o.length>0?o:null},Je=async(e,r=We.env)=>{let t=Ue(r);if(t===null)return null;let o=await O(t);for(let n of e)if(await O(n)===o)return n;return null};var Z="200",M=async e=>{try{let r=await p(["terminal","list","--worktree",`path:${e}`,"--limit",Z]),t=r.truncated===!0;return t&&f.debug({cwd:e,limit:Z},"orca: terminal list truncated"),{terminals:r.terminals??[],truncated:t}}catch(r){if(r instanceof d&&r.code==="selector_not_found")return{terminals:[],truncated:!1};throw r}};var Be=async e=>{try{return await p(["terminal","close","--worktree",`path:${e}`,"--all"]),"retired"}catch(r){if(r instanceof d&&r.code==="selector_not_found")return"not_found";if(r instanceof d&&r.code==="terminal_close_incomplete")return f.debug({cwd:e,error:r},"orca: surfaces not retired"),"retired";throw r}},Ve=async e=>{let{terminals:r}=await M(e);for(let o of r)await p(["terminal","close","--terminal",o.handle]);let t=await Be(e);return r.length===0&&t==="not_found"?{closed:!1,skipped:"not_found"}:{closed:!0,count:r.length}},je=(e,r)=>r instanceof g?{closed:!1,skipped:"absent"}:r instanceof d?{closed:!1,error:r}:r instanceof x?{closed:!1,error:new d({code:"orca_malformed_output",message:r.message,data:{exitCode:r.exitCode,stderrTail:r.stderrTail}})}:(f.debug({cwd:e,error:r},"orca: close failed outside the Orca contract"),{closed:!1,error:new d({code:"orca_close_failed",message:r instanceof Error?r.message:String(r)})}),He=async(e,r)=>{if(r!=="ready")return{closed:!1,skipped:r};try{return await Ve(e)}catch(t){return je(e,t)}};import{setTimeout as Ke}from"node:timers/promises";var qe=3,ze=300,re=(e={})=>({attempts:e.attempts??qe,delayMs:e.delayMs??ze,exhausted:!1}),Xe=async e=>{try{return{created:await p(e)}}catch(r){if(r instanceof d&&r.code==="selector_not_found")return{notSelectable:r};throw r}},Ye=async(e,r,t)=>{let o=t.exhausted?1:t.attempts,n=Array.from({length:o},(c,s)=>s+1),a;for(let c of n){let s=await Xe(e);if("created"in s)return s.created.terminal.handle;a=s.notSelectable,c<o&&await Ke(t.delayMs)}throw t.exhausted=!0,new d({code:"orca_worktree_not_selectable",message:`orca: worktree ${r} is not selectable after ${o} attempt(s): ${a?.message??""}`,data:{cwd:r,attempts:o,cause:a?.data}})},ee=async(e,r)=>(await p(["terminal","split","--terminal",e,"--direction",r])).split.handle,Qe=async e=>{let{cwd:r,title:t,focus:o,layout:n,panes:a,poll:c=re()}=e,s=["terminal","create","--worktree",`path:${r}`,"--title",t,...o?["--focus"]:[]],l=await Ye(s,r,c),m=[l];return n==="full"&&(m.push(await ee(l,"horizontal")),a==="three-pane"&&m.push(await ee(l,"vertical"))),{handles:m,layout:n}};var Ze=e=>{let{branch:r}=e,t=G(r);return t?$(t):r};var it=e=>typeof e=="object",E=async e=>(await e.body?.cancel(),{kind:"foreign",status:e.status,contentType:e.headers.get("content-type")}),ct=(e,r)=>{let t=r.contentType?.split(";")[0]?.trim(),o=t==null||t===""?`${r.status}`:`${r.status} ${t}`;return`port ${e} answered ${o}, not vite's ping \u2014 liveness cannot be verified`};var te={accept:"text/x-vite-ping"},er=e=>e.kind==="api"?`http://127.0.0.1:${e.port}/__health`:`http://127.0.0.1:${e.port}/`,rr=(e,r)=>{try{return new URL(e,r)}catch{return null}},tr=async(e,r)=>{let t=await fetch(e,{signal:r});return t.ok?(await t.body?.cancel(),"ok"):E(t)},or=async(e,r)=>{let t=await fetch(e,{headers:te,redirect:"manual",signal:r});if(t.status===204)return"ok";if(t.status<300||t.status>=400)return E(t);let o=t.headers.get("location"),n=o==null?null:rr(o,e);if(n==null||n.origin!==new URL(e).origin)return E(t);await t.body?.cancel();let a=await fetch(n,{headers:te,redirect:"manual",signal:r});return a.status!==204?E(a):(await a.body?.cancel(),"ok")},lt=async e=>{let r=er(e),t=AbortSignal.timeout(1500);try{return e.kind==="api"?await tr(r,t):await or(r,t)}catch{return"refused"}};import{readRelease as nr}from"@slip-stream-kit/config/internal";var ar=e=>nr(e);export{hr as a,X as b,cr as c,N as d,mr as e,d as f,p as g,Ie as h,Je as i,M as j,He as k,De as l,Ge as m,Fe as n,re as o,Qe as p,Ze as q,it as r,ct as s,lt as t,ar as u,gr as v};
10
+ //# sourceMappingURL=chunk-Z4ZY2G4O.js.map