@slip-stream-kit/config 0.1.136

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,4 @@
1
+ export { defineConfig } from '../lib/package-config/package-config';
2
+ export type { InfraKitDev, InfraKitDevProxy, InfraKitDevProxyRoute, InfraKitDevProxySource, InfraKitPackageConfig, InfraKitPackageConfigInput, } from '../lib/package-config/package-config';
3
+ export { defineVendorConfig } from '../lib/vendor/config-schema';
4
+ export type { VendorConfig, VendorCopyItem } from '../lib/vendor/config-schema';
@@ -0,0 +1,5 @@
1
+ export { packageConfigSchema } from '../lib/package-config/package-config-schema';
2
+ export { DEFAULT_RELEASE_SLUG, slugifyHostLabel, slugifyRelease } from '../lib/release-slug/release-slug';
3
+ export { defineVendorConfig, VENDOR_CONFIG_FILE, vendorConfigSchema, vendorCopyItemSchema, } from '../lib/vendor/config-schema';
4
+ export type { VendorConfig, VendorCopyItem } from '../lib/vendor/config-schema';
5
+ export { DEV_CONTEXT_WIRE_VERSION, loadDev, readLocalContext, readLocalSet } from '../lib/vite/vite';
@@ -0,0 +1,2 @@
1
+ export { infraKitDev, infraKitProxy, resolveProxyConfig, slugifyRelease } from '../lib/vite/vite';
2
+ export type { InfraKitBasicAuth, InfraKitDevOptions, InfraKitViteProxy, InfraKitViteProxyEntry } from '../lib/vite/vite';
package/dist/index.js ADDED
@@ -0,0 +1,34 @@
1
+ // src/lib/package-config/package-config.ts
2
+ var defineConfig = (config) => {
3
+ return config;
4
+ };
5
+
6
+ // src/lib/vendor/config-schema.ts
7
+ import { z } from "zod";
8
+ var safeRelPath = z.string().refine(
9
+ (p) => {
10
+ const isAbsolute = /^(?:[/\\]|[a-z]:)/i.test(p);
11
+ const hasDotDotSegment = p.split(/[\\/]/).includes("..");
12
+ return !isAbsolute && !hasDotDotSegment && p.trim().length > 0;
13
+ },
14
+ { message: 'must be a non-empty repo-relative path without ".." segments' }
15
+ );
16
+ var vendorCopyItemSchema = z.object({
17
+ name: z.string(),
18
+ source: safeRelPath,
19
+ target: safeRelPath,
20
+ type: z.enum(["file", "directory"]),
21
+ vendored: z.boolean().optional()
22
+ });
23
+ var vendorConfigSchema = z.object({
24
+ /** Files/dirs to copy. Items with `vendored: true` land under `vendor/`. */
25
+ copy: z.array(vendorCopyItemSchema)
26
+ }).strict();
27
+ var defineVendorConfig = (config) => {
28
+ return config;
29
+ };
30
+ export {
31
+ defineConfig,
32
+ defineVendorConfig
33
+ };
34
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/package-config/package-config.ts", "../src/lib/vendor/config-schema.ts"],
4
+ "sourcesContent": ["/**\n * Validation rules for a single workspace package, declared in its\n * `infra-kit.config.ts`. Every field is optional: a key left unset falls back to\n * the active baseline, and a key set replaces that default wholesale (per-key, no\n * array concatenation) so a package can opt out with an explicit empty array.\n *\n * The baselines themselves (`DEFAULT_RULES` / `ROOT_DEFAULT_RULES`) deliberately do\n * NOT live here \u2014 they are audit POLICY, and policy belongs to the `infra-kit` CLI\n * that enforces it, not to the package a consumer installs to author a config.\n *\n * Most packages need none of these \u2014 the standard rules live in the baseline, so\n * a typical config is just `defineConfig(() => ({}))`.\n *\n * @example\n * // infra-kit.config.ts\n * import { defineConfig } from '@slip-stream-kit/config'\n *\n * export default defineConfig(() => ({}))\n */\nexport interface InfraKitPackageConfig {\n /** Scripts that must be present in the package's package.json `scripts` map. */\n requiredScripts?: string[]\n /** Files (relative to the package root) that must exist on disk. */\n requiredFiles?: string[]\n /** Turborepo expectations \u2014 only meaningful where a turbo.json lives (the root). */\n turbo?: {\n /** Tasks that must be defined in turbo.json `tasks`. */\n requiredTasks?: string[]\n }\n /** Local-dev configuration. Accepted-and-inert to the audit; consumed by the dev server. */\n dev?: InfraKitDev\n}\n\n/** A proxy route's allowed backend source. */\nexport type InfraKitDevProxySource = 'local' | 'cloud'\n\nexport interface InfraKitDevProxyRoute {\n /** Backend package this route targets when resolved locally. */\n packageName: string\n /** Capabilities this route can resolve to. Must be non-empty. */\n from: InfraKitDevProxySource[]\n /**\n * Source used when a local backend for this package isn't active. Required when\n * `from` lists more than one source; redundant (and omitted) for a single-source\n * route. When set, must be one of `from`.\n */\n default?: InfraKitDevProxySource\n}\n\nexport interface InfraKitDevProxy {\n /** URL templates. Placeholders like `<release>`/`<packageName>`/`<env>` are substituted at dev time. */\n templates: {\n local: string\n cloud: string\n }\n /** Path-prefix (e.g. `/api`, `/api/v1`, `/media`) \u2192 route definition. */\n routes: Record<string, InfraKitDevProxyRoute>\n}\n\nexport interface InfraKitDev {\n proxy?: InfraKitDevProxy\n}\n\n/**\n * Accepted shapes for a package config's default export \u2014 mirrors Vite's\n * `defineConfig` input: a plain object, a sync factory, or an async factory.\n */\nexport type InfraKitPackageConfigInput =\n InfraKitPackageConfig | (() => InfraKitPackageConfig) | (() => Promise<InfraKitPackageConfig>)\n\n/**\n * Identity helper that gives `infra-kit.config.ts` authors full type inference\n * and editor autocomplete without changing the value \u2014 exactly like Vite's\n * `defineConfig`. Resolution of the factory form happens in the CLI's loader, not here.\n *\n * @example\n * export default defineConfig(() => ({}))\n *\n * @example\n * export default defineConfig(() => ({ requiredScripts: [] }))\n */\nexport const defineConfig = (config: InfraKitPackageConfigInput): InfraKitPackageConfigInput => {\n return config\n}\n", "import { z } from 'zod'\n\n/**\n * Pure (node-free) vendor config schema + authoring helper. Kept separate from\n * `config.ts` (which imports node builtins for the runtime loader) so the public\n * lib entry can re-export `defineVendorConfig` without dragging node types into\n * the emitted `.d.ts`.\n */\n\n/**\n * Filename a source repo provides at its root to declare WHAT `vendor sync`\n * copies (`copy[]`). Lives ONLY on the write path \u2014 `vendor check` never loads it.\n * WHERE/WHICH to stamp (`workspaceDir` + `targets`) is machine-local and lives in\n * the user-global factory config (`~/.infra-kit/vendor.json`).\n */\nexport const VENDOR_CONFIG_FILE = 'vendor.config.ts'\n\n/**\n * A non-empty, repo-relative path with no `..` segments and no absolute prefix\n * (POSIX `/`, UNC/`\\`, or a Windows drive like `C:`). Containment guard for\n * vendor copy items so a malicious/typo config can't read or write outside the\n * source/target repo roots. Kept as a string/regex check (no `node:path`) to\n * respect this file's node-free constraint \u2014 `sync-ops.ts` does the resolved\n * runtime containment assert as defense in depth.\n */\nconst safeRelPath = z.string().refine(\n (p) => {\n const isAbsolute = /^(?:[/\\\\]|[a-z]:)/i.test(p)\n const hasDotDotSegment = p.split(/[\\\\/]/).includes('..')\n\n return !isAbsolute && !hasDotDotSegment && p.trim().length > 0\n },\n { message: 'must be a non-empty repo-relative path without \"..\" segments' },\n)\n\n/**\n * One item to sync from the source repo into each target. `vendored: true` marks\n * workspace packages that must land under `vendor/` (the single-source-of-truth\n * code); everything else is root-level tooling that stays at the repo root.\n */\nexport const vendorCopyItemSchema = z.object({\n name: z.string(),\n source: safeRelPath,\n target: safeRelPath,\n type: z.enum(['file', 'directory']),\n vendored: z.boolean().optional(),\n})\n\nexport const vendorConfigSchema = z\n .object({\n /** Files/dirs to copy. Items with `vendored: true` land under `vendor/`. */\n copy: z.array(vendorCopyItemSchema),\n })\n // Reject stray keys so a leftover `targets` (now machine-local, in\n // ~/.infra-kit/vendor.json) yields a clear \"unrecognized key\" error rather\n // than being silently ignored.\n .strict()\n\nexport type VendorCopyItem = z.infer<typeof vendorCopyItemSchema>\nexport type VendorConfig = z.infer<typeof vendorConfigSchema>\n\n/**\n * Identity helper for authoring a type-safe `vendor.config.ts` in a source repo.\n * Re-exported from the public lib entry so a source repo can\n * `import { defineVendorConfig } from 'infra-kit'`.\n *\n * NOTE: a `vendor.config.ts` must be type-strippable \u2014 Node's native type\n * stripping (Node >= 24) loads it without a build step, which forbids `enum`,\n * `namespace`, and parameter properties.\n *\n * @example\n * export default defineVendorConfig({\n * copy: [{ name: 'Configs', source: 'vendor/configs', target: 'vendor/configs', type: 'directory', vendored: true }],\n * })\n */\nexport const defineVendorConfig = (config: VendorConfig): VendorConfig => {\n return config\n}\n"],
5
+ "mappings": ";AAiFO,IAAM,eAAe,CAAC,WAAmE;AAC9F,SAAO;AACT;;;ACnFA,SAAS,SAAS;AAyBlB,IAAM,cAAc,EAAE,OAAO,EAAE;AAAA,EAC7B,CAAC,MAAM;AACL,UAAM,aAAa,qBAAqB,KAAK,CAAC;AAC9C,UAAM,mBAAmB,EAAE,MAAM,OAAO,EAAE,SAAS,IAAI;AAEvD,WAAO,CAAC,cAAc,CAAC,oBAAoB,EAAE,KAAK,EAAE,SAAS;AAAA,EAC/D;AAAA,EACA,EAAE,SAAS,+DAA+D;AAC5E;AAOO,IAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,MAAM,EAAE,OAAO;AAAA,EACf,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,MAAM,EAAE,KAAK,CAAC,QAAQ,WAAW,CAAC;AAAA,EAClC,UAAU,EAAE,QAAQ,EAAE,SAAS;AACjC,CAAC;AAEM,IAAM,qBAAqB,EAC/B,OAAO;AAAA;AAAA,EAEN,MAAM,EAAE,MAAM,oBAAoB;AACpC,CAAC,EAIA,OAAO;AAmBH,IAAM,qBAAqB,CAAC,WAAuC;AACxE,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -0,0 +1,211 @@
1
+ // src/lib/package-config/package-config-schema.ts
2
+ import { z } from "zod";
3
+ var packageConfigSchema = z.strictObject({
4
+ requiredScripts: z.array(z.string().min(1)).optional(),
5
+ requiredFiles: z.array(z.string().min(1)).optional(),
6
+ turbo: z.strictObject({
7
+ requiredTasks: z.array(z.string().min(1)).optional()
8
+ }).optional(),
9
+ dev: z.strictObject({
10
+ proxy: z.strictObject({
11
+ templates: z.strictObject({
12
+ local: z.string().min(1),
13
+ cloud: z.string().min(1)
14
+ }),
15
+ routes: z.record(
16
+ z.string().min(1),
17
+ z.strictObject({
18
+ packageName: z.string().min(1),
19
+ from: z.array(z.enum(["local", "cloud"])).min(1),
20
+ default: z.enum(["local", "cloud"]).optional()
21
+ }).refine(
22
+ (route) => {
23
+ return route.from.length <= 1 || route.default !== void 0;
24
+ },
25
+ {
26
+ message: "default is required when `from` has more than one source"
27
+ }
28
+ ).refine(
29
+ (route) => {
30
+ return route.default === void 0 || route.from.includes(route.default);
31
+ },
32
+ {
33
+ message: "default must be listed in `from`"
34
+ }
35
+ )
36
+ )
37
+ }).optional()
38
+ }).optional()
39
+ });
40
+
41
+ // src/lib/release-slug/release-slug.ts
42
+ var slugifyHostLabel = (label) => {
43
+ const runs = label.toLowerCase().match(/[a-z0-9]+/g);
44
+ return runs ? runs.join("-") : "";
45
+ };
46
+ var slugifyRelease = (branch) => {
47
+ return slugifyHostLabel(branch.replace(/^(?:feature|feat|release|hotfix|bugfix|fix|chore)\//i, ""));
48
+ };
49
+ var DEFAULT_RELEASE_SLUG = "local";
50
+
51
+ // src/lib/vendor/config-schema.ts
52
+ import { z as z2 } from "zod";
53
+ var VENDOR_CONFIG_FILE = "vendor.config.ts";
54
+ var safeRelPath = z2.string().refine(
55
+ (p) => {
56
+ const isAbsolute = /^(?:[/\\]|[a-z]:)/i.test(p);
57
+ const hasDotDotSegment = p.split(/[\\/]/).includes("..");
58
+ return !isAbsolute && !hasDotDotSegment && p.trim().length > 0;
59
+ },
60
+ { message: 'must be a non-empty repo-relative path without ".." segments' }
61
+ );
62
+ var vendorCopyItemSchema = z2.object({
63
+ name: z2.string(),
64
+ source: safeRelPath,
65
+ target: safeRelPath,
66
+ type: z2.enum(["file", "directory"]),
67
+ vendored: z2.boolean().optional()
68
+ });
69
+ var vendorConfigSchema = z2.object({
70
+ /** Files/dirs to copy. Items with `vendored: true` land under `vendor/`. */
71
+ copy: z2.array(vendorCopyItemSchema)
72
+ }).strict();
73
+ var defineVendorConfig = (config) => {
74
+ return config;
75
+ };
76
+
77
+ // src/lib/vite/vite.ts
78
+ import fs from "node:fs";
79
+ import path from "node:path";
80
+ import process from "node:process";
81
+ import { pathToFileURL } from "node:url";
82
+ import { z as z3 } from "zod";
83
+ var PACKAGE_CONFIG_FILE = "infra-kit.config.ts";
84
+ var DEV_CONTEXT_DIR = path.join(".infra-kit", "dev-context");
85
+ var DEV_CONTEXT_FILE = path.join(".infra-kit", "dev-context.json");
86
+ var devContextFragmentSchema = z3.object({
87
+ package: z3.string(),
88
+ port: z3.number(),
89
+ pid: z3.number().optional(),
90
+ writtenAt: z3.number().optional(),
91
+ release: z3.string().optional(),
92
+ alias: z3.string().optional(),
93
+ proxyPort: z3.number().optional(),
94
+ origin: z3.string().optional(),
95
+ v: z3.number().optional()
96
+ });
97
+ var DEV_CONTEXT_WIRE_VERSION = 2;
98
+ var loadDev = async (cwd) => {
99
+ const configPath = path.join(cwd, PACKAGE_CONFIG_FILE);
100
+ if (!fs.existsSync(configPath)) return void 0;
101
+ const stat = fs.statSync(configPath);
102
+ const moduleUrl = `${pathToFileURL(configPath).href}?mtime=${Number(stat.mtimeMs)}`;
103
+ const imported = await import(moduleUrl);
104
+ const rawExport = imported.default;
105
+ if (rawExport === void 0) return void 0;
106
+ const resolved = typeof rawExport === "function" ? await rawExport() : rawExport;
107
+ const parsed = packageConfigSchema.safeParse(resolved);
108
+ if (!parsed.success) {
109
+ throw new Error(
110
+ `@slip-stream-kit/config/vite: invalid ${PACKAGE_CONFIG_FILE} at ${configPath}: ${z3.prettifyError(parsed.error)}`
111
+ );
112
+ }
113
+ return parsed.data.dev;
114
+ };
115
+ var extractPackages = (parsed) => {
116
+ if (Array.isArray(parsed)) {
117
+ return parsed.filter((v) => {
118
+ return typeof v === "string";
119
+ });
120
+ }
121
+ if (parsed !== null && typeof parsed === "object") {
122
+ const candidate = parsed.packages ?? parsed.localPackages;
123
+ if (Array.isArray(candidate)) {
124
+ return candidate.filter((v) => {
125
+ return typeof v === "string";
126
+ });
127
+ }
128
+ }
129
+ return [];
130
+ };
131
+ var findUp = (start, relative) => {
132
+ let dir = path.resolve(start);
133
+ for (; ; ) {
134
+ const candidate = path.join(dir, relative);
135
+ if (fs.existsSync(candidate)) return candidate;
136
+ const parent = path.dirname(dir);
137
+ if (parent === dir) return void 0;
138
+ dir = parent;
139
+ }
140
+ };
141
+ var emptyLocalContext = () => {
142
+ return { packages: /* @__PURE__ */ new Set(), info: /* @__PURE__ */ new Map() };
143
+ };
144
+ var isFragmentWriterAlive = (pid) => {
145
+ if (pid == null) return true;
146
+ try {
147
+ process.kill(pid, 0);
148
+ return true;
149
+ } catch (error) {
150
+ return error.code === "EPERM";
151
+ }
152
+ };
153
+ var readFragmentDir = (dir) => {
154
+ let entries;
155
+ try {
156
+ entries = fs.readdirSync(dir);
157
+ } catch {
158
+ return emptyLocalContext();
159
+ }
160
+ const packages = /* @__PURE__ */ new Set();
161
+ const info = /* @__PURE__ */ new Map();
162
+ for (const name of entries) {
163
+ if (!name.endsWith(".json")) continue;
164
+ try {
165
+ const parsed = devContextFragmentSchema.safeParse(JSON.parse(fs.readFileSync(path.join(dir, name), "utf-8")));
166
+ if (!parsed.success) continue;
167
+ if (!isFragmentWriterAlive(parsed.data.pid)) continue;
168
+ packages.add(parsed.data.package);
169
+ info.set(parsed.data.package, {
170
+ port: parsed.data.port,
171
+ origin: parsed.data.origin,
172
+ release: parsed.data.release,
173
+ alias: parsed.data.alias,
174
+ proxyPort: parsed.data.proxyPort,
175
+ wire: parsed.data.v
176
+ });
177
+ } catch {
178
+ continue;
179
+ }
180
+ }
181
+ return { packages, info };
182
+ };
183
+ var readLocalContext = (cwd) => {
184
+ const dir = findUp(cwd, DEV_CONTEXT_DIR);
185
+ if (dir) return readFragmentDir(dir);
186
+ const legacy = findUp(cwd, DEV_CONTEXT_FILE);
187
+ if (!legacy) return emptyLocalContext();
188
+ try {
189
+ return { packages: new Set(extractPackages(JSON.parse(fs.readFileSync(legacy, "utf-8")))), info: /* @__PURE__ */ new Map() };
190
+ } catch {
191
+ return emptyLocalContext();
192
+ }
193
+ };
194
+ var readLocalSet = (cwd) => {
195
+ return readLocalContext(cwd).packages;
196
+ };
197
+ export {
198
+ DEFAULT_RELEASE_SLUG,
199
+ DEV_CONTEXT_WIRE_VERSION,
200
+ VENDOR_CONFIG_FILE,
201
+ defineVendorConfig,
202
+ loadDev,
203
+ packageConfigSchema,
204
+ readLocalContext,
205
+ readLocalSet,
206
+ slugifyHostLabel,
207
+ slugifyRelease,
208
+ vendorConfigSchema,
209
+ vendorCopyItemSchema
210
+ };
211
+ //# sourceMappingURL=internal.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/package-config/package-config-schema.ts", "../src/lib/release-slug/release-slug.ts", "../src/lib/vendor/config-schema.ts", "../src/lib/vite/vite.ts"],
4
+ "sourcesContent": ["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", "/**\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", "import { z } from 'zod'\n\n/**\n * Pure (node-free) vendor config schema + authoring helper. Kept separate from\n * `config.ts` (which imports node builtins for the runtime loader) so the public\n * lib entry can re-export `defineVendorConfig` without dragging node types into\n * the emitted `.d.ts`.\n */\n\n/**\n * Filename a source repo provides at its root to declare WHAT `vendor sync`\n * copies (`copy[]`). Lives ONLY on the write path \u2014 `vendor check` never loads it.\n * WHERE/WHICH to stamp (`workspaceDir` + `targets`) is machine-local and lives in\n * the user-global factory config (`~/.infra-kit/vendor.json`).\n */\nexport const VENDOR_CONFIG_FILE = 'vendor.config.ts'\n\n/**\n * A non-empty, repo-relative path with no `..` segments and no absolute prefix\n * (POSIX `/`, UNC/`\\`, or a Windows drive like `C:`). Containment guard for\n * vendor copy items so a malicious/typo config can't read or write outside the\n * source/target repo roots. Kept as a string/regex check (no `node:path`) to\n * respect this file's node-free constraint \u2014 `sync-ops.ts` does the resolved\n * runtime containment assert as defense in depth.\n */\nconst safeRelPath = z.string().refine(\n (p) => {\n const isAbsolute = /^(?:[/\\\\]|[a-z]:)/i.test(p)\n const hasDotDotSegment = p.split(/[\\\\/]/).includes('..')\n\n return !isAbsolute && !hasDotDotSegment && p.trim().length > 0\n },\n { message: 'must be a non-empty repo-relative path without \"..\" segments' },\n)\n\n/**\n * One item to sync from the source repo into each target. `vendored: true` marks\n * workspace packages that must land under `vendor/` (the single-source-of-truth\n * code); everything else is root-level tooling that stays at the repo root.\n */\nexport const vendorCopyItemSchema = z.object({\n name: z.string(),\n source: safeRelPath,\n target: safeRelPath,\n type: z.enum(['file', 'directory']),\n vendored: z.boolean().optional(),\n})\n\nexport const vendorConfigSchema = z\n .object({\n /** Files/dirs to copy. Items with `vendored: true` land under `vendor/`. */\n copy: z.array(vendorCopyItemSchema),\n })\n // Reject stray keys so a leftover `targets` (now machine-local, in\n // ~/.infra-kit/vendor.json) yields a clear \"unrecognized key\" error rather\n // than being silently ignored.\n .strict()\n\nexport type VendorCopyItem = z.infer<typeof vendorCopyItemSchema>\nexport type VendorConfig = z.infer<typeof vendorConfigSchema>\n\n/**\n * Identity helper for authoring a type-safe `vendor.config.ts` in a source repo.\n * Re-exported from the public lib entry so a source repo can\n * `import { defineVendorConfig } from 'infra-kit'`.\n *\n * NOTE: a `vendor.config.ts` must be type-strippable \u2014 Node's native type\n * stripping (Node >= 24) loads it without a build step, which forbids `enum`,\n * `namespace`, and parameter properties.\n *\n * @example\n * export default defineVendorConfig({\n * copy: [{ name: 'Configs', source: 'vendor/configs', target: 'vendor/configs', type: 'directory', vendored: true }],\n * })\n */\nexport const defineVendorConfig = (config: VendorConfig): VendorConfig => {\n return config\n}\n", "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 v: z.number().optional(),\n})\n\n/**\n * Wire version of the dev-context fragment \u2014 the ONE contract between the `infra-kit` CLI (which writes\n * fragments) and this helper (which reads them). They ship as SEPARATE npm packages on separate cadences,\n * so this number is the only thing either side can trust about the other.\n *\n * `v >= 2` is a PROMISE that `origin` is present and authoritative.\n *\n * That promise is what makes the guard in {@link resolveLocalTarget} possible. Without it, a missing\n * `origin` is ambiguous \u2014 it means BOTH \"an old CLI wrote this, legacy mode is correct\" AND \"a current\n * CLI wrote a broken fragment, legacy mode is catastrophic\" \u2014 and the helper has to guess. It guesses\n * legacy, rebuilds the target from a `templates.local` that says `http://`, and proxies plain HTTP into\n * a TLS listener. Silently, because portless answers :80 with a 302 rather than refusing.\n *\n * A fragment with NO `v` is a pre-v2 (legacy) writer and must still be honoured: rejecting it would drop\n * a running package to `cloud` instead of falling into legacy mode, and that rollback path is exactly why\n * the schema above is lenient and un-`refine`d. Absent or unknown `v` therefore NEVER rejects.\n */\nexport const DEV_CONTEXT_WIRE_VERSION = 2\n\n/**\n * A single Vite `server.proxy` entry. `changeOrigin` is always set. `cookieDomainRewrite` is cloud-only\n * (it keeps an HTTPS cloud BE's cookies usable from a local FE). `secure: false` appears on BOTH sources\n * but for different reasons: a cloud target may serve a cert the local store rejects, and a local target\n * is served by portless from its own private CA \u2014 set there only for a loopback host (see\n * {@link isLoopbackTarget}). `headers` is present only when HTTP Basic Auth is injected (see\n * {@link buildBasicAuthHeader}) \u2014 it carries the `Authorization` header applied\n * uniformly to every route so upstream environments behind auth (e2e/staging)\n * stay reachable.\n */\nexport interface InfraKitViteProxyEntry {\n target: string\n changeOrigin: true\n secure?: false\n cookieDomainRewrite?: 'localhost'\n headers?: Record<string, string>\n}\n\n/** A Vite `server.proxy`-shaped map: path-prefix \u2192 proxy entry. */\nexport type InfraKitViteProxy = Record<string, InfraKitViteProxyEntry>\n\n/** Explicit HTTP Basic Auth credentials, overriding the `E2E__BASIC_AUTH_*` env vars. */\nexport interface InfraKitBasicAuth {\n username: string\n password: string\n}\n\nexport interface InfraKitDevOptions {\n /** Package dir whose `infra-kit.config.ts` is loaded. Defaults to `process.cwd()`. */\n cwd?: string\n /**\n * Explicit HTTP Basic Auth credentials injected into every proxy route as an\n * `Authorization` header. Takes precedence over the `E2E__BASIC_AUTH_USERNAME`\n * / `E2E__BASIC_AUTH_PASSWORD` env vars. Omit to use the env-based default.\n */\n basicAuth?: InfraKitBasicAuth\n /**\n * Vite's `command`. Pass it (`defineConfig(async ({ command }) => ({ server: await infraKitDev({ command }) }))`)\n * so `build` is a no-op: `server` is irrelevant to a build and proxy resolution would otherwise\n * fail-fast on a cloud route with no sourced env. Omit (or `'serve'`) for the dev-server config.\n */\n command?: 'build' | 'serve'\n /**\n * Explicit dev-server port. Omit for a **per-worktree dynamic** free port (a fresh OS-assigned\n * port) so N simultaneous git worktrees never collide on Vite's default `5173`; Vite prints the\n * chosen URL. Pass a fixed number only when an external contract pins the port.\n */\n port?: number\n /**\n * Interface the dev server binds. Defaults to {@link LOOPBACK_V4} so a portless alias can reach it\n * (Vite's own `localhost` default binds `[::1]` only, which the proxy cannot dial). Override when\n * the dev server must be reachable off the loopback \u2014 `'0.0.0.0'` or `true` inside a container, on\n * a LAN, or for an e2e runner on another host.\n */\n host?: string | boolean\n}\n\n/**\n * Build the `Authorization: Basic <base64(user:pass)>` header value. Credentials\n * come from `override` when given, else from `E2E__BASIC_AUTH_USERNAME` /\n * `E2E__BASIC_AUTH_PASSWORD` (NOTE: double underscore). Returns `undefined` when\n * either half is missing, so callers add no `headers` key at all.\n */\nconst buildBasicAuthHeader = (env: NodeJS.ProcessEnv, override?: InfraKitBasicAuth): string | undefined => {\n const username = override?.username ?? env.E2E__BASIC_AUTH_USERNAME\n const password = override?.password ?? env.E2E__BASIC_AUTH_PASSWORD\n\n if (!username || !password) return undefined\n\n const encoded = Buffer.from(`${username}:${password}`).toString('base64')\n\n return `Basic ${encoded}`\n}\n\n/**\n * Re-exported from the shared, dependency-light `lib/release-slug` module so the\n * published `infra-kit/vite` surface (`entry/vite.ts:7`) is unchanged while the\n * dev-server's fragment writer derives `<release>` from the SAME implementation\n * (no slug drift). See {@link slugifyRelease}.\n */\nexport { slugifyRelease }\n\n/** Fill the `<release>`/`<packageName>`/`<env>` placeholders in a URL template. */\nconst interpolate = (template: string, values: { release: string; packageName: string; env: string }): string => {\n return template\n .replaceAll('<release>', values.release)\n .replaceAll('<packageName>', values.packageName)\n .replaceAll('<env>', values.env)\n}\n\n/** The port a bare `http://` target implies, and the proxy's default \u2014 never spelled out in a URL. */\nconst DEFAULT_HTTP_PORT = 80\n\n/**\n * The interface the vite dev server binds. Pinned to IPv4 loopback because portless dials its routes\n * on `127.0.0.1`, while vite's default `host: 'localhost'` combined with its\n * `dns.setDefaultResultOrder('verbatim')` binds `[::1]` ONLY \u2014 the alias then resolves, the proxy\n * connects, and the connection is refused, surfacing as a 502 on every UI request. Backends never hit\n * this because `ServerlessLocalRun` already binds `127.0.0.1`. Still loopback-only: this narrows the\n * address family, it does not expose the dev server to the network.\n */\nconst LOOPBACK_V4 = '127.0.0.1'\n\n/**\n * Graft the proxy's listen port onto an interpolated local target. The `dev.proxy` local template is\n * written port-free (`https://<release>.<packageName>.localhost`) because the proxy serves TLS on `:443`,\n * the only port a port-free HTTPS URL can come from. A consumer who trades the clean URL for a zero-sudo\n * unprivileged port still needs the frontend to reach it, so the runner records the port it actually bound\n * and we append it here. A template that already pins its own port keeps it.\n */\nconst withProxyPort = (target: string, proxyPort: number | undefined): string => {\n if (proxyPort == null || proxyPort === DEFAULT_HTTP_PORT) return target\n\n let url: URL\n\n try {\n url = new URL(target)\n } catch {\n throw new Error(\n `@slip-stream-kit/config/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 // The fragment declared a wire version, which PROMISES an `origin` \u2014 and there isn't one. Falling into\n // legacy mode here would rebuild the target from `templates.local` and downgrade it to `http://`, i.e.\n // proxy plain HTTP into portless's TLS listener. That failure is silent (:80 answers with a 302 rather\n // than refusing), so nothing downstream would catch it. A fragment with NO `v` is a genuinely old writer\n // and still falls through to legacy below \u2014 that rollback path is intact. This branch is only the\n // impossible one: a writer that announced v2 and then broke its own promise.\n if (info?.wire != null) {\n throw new Error(\n `@slip-stream-kit/config/vite: the dev-context fragment for \"${route.packageName}\" declares wire v${info.wire} but ` +\n `carries no \\`origin\\`. A v${DEV_CONTEXT_WIRE_VERSION} writer must publish the exact origin it ` +\n `registered. Refusing to guess a target rather than silently proxy plain HTTP at a TLS listener \u2014 ` +\n `restart \\`infra-kit dev\\`, and if it persists the CLI and this helper are incompatible.`,\n )\n }\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 `@slip-stream-kit/config/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 *\n * Reached from two different processes, and only one of them is ours. Under the\n * CLI (`infra-kit dev`, `audit`) the entry has installed\n * {@link ../node-warnings.suppressTypelessPackageJsonWarning}, so a consumer package\n * with no `\"type\"` loads quietly. Under `infraKitDev()` in a consumer's own\n * `vite.config.ts` we are a library in their process and do NOT patch their globals,\n * so such a package still prints Node's MODULE_TYPELESS_PACKAGE_JSON banner there.\n * Harmless (it is a double-parse notice), and latent while consumer UI packages\n * declare `\"type\": \"module\"`.\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(\n `@slip-stream-kit/config/vite: invalid ${PACKAGE_CONFIG_FILE} at ${configPath}: ${z.prettifyError(parsed.error)}`,\n )\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 /**\n * The fragment's declared wire version (see {@link DEV_CONTEXT_WIRE_VERSION}). Absent \u2192 a pre-v2 writer,\n * so legacy mode is the correct reading. Present \u2192 the writer PROMISED an `origin`, and a missing one is\n * a broken fragment rather than an old one.\n */\n wire?: number\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 wire: parsed.data.v,\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"],
5
+ "mappings": ";AAAA,SAAS,SAAS;AAUX,IAAM,sBAAsB,EAAE,aAAa;AAAA,EAChD,iBAAiB,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS;AAAA,EACrD,eAAe,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS;AAAA,EACnD,OAAO,EACJ,aAAa;AAAA,IACZ,eAAe,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS;AAAA,EACrD,CAAC,EACA,SAAS;AAAA,EACZ,KAAK,EACF,aAAa;AAAA,IACZ,OAAO,EACJ,aAAa;AAAA,MACZ,WAAW,EAAE,aAAa;AAAA,QACxB,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,QACvB,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,MACzB,CAAC;AAAA,MACD,QAAQ,EAAE;AAAA,QACR,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,QAChB,EACG,aAAa;AAAA,UACZ,aAAa,EAAE,OAAO,EAAE,IAA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kBAAkB;AAAA,EAC3B;AACF;AAOO,IAAM,eAAe,CAAC,QAAqC;AAChE,SAAO,iBAAiB,GAAG,EAAE;AAC/B;",
6
+ "names": ["z", "z", "z", "z"]
7
+ }
@@ -0,0 +1,35 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Schema for the resolved (post-factory) package config object. `strictObject`
4
+ * rejects unknown keys so typos in `infra-kit.config.ts` surface as validation
5
+ * errors instead of being silently ignored.
6
+ *
7
+ * Kept in its own module — separate from the public `defineConfig`/types entry —
8
+ * so the published `infra-kit` type surface stays free of a `zod` import.
9
+ */
10
+ export declare const packageConfigSchema: z.ZodObject<{
11
+ requiredScripts: z.ZodOptional<z.ZodArray<z.ZodString>>;
12
+ requiredFiles: z.ZodOptional<z.ZodArray<z.ZodString>>;
13
+ turbo: z.ZodOptional<z.ZodObject<{
14
+ requiredTasks: z.ZodOptional<z.ZodArray<z.ZodString>>;
15
+ }, z.core.$strict>>;
16
+ dev: z.ZodOptional<z.ZodObject<{
17
+ proxy: z.ZodOptional<z.ZodObject<{
18
+ templates: z.ZodObject<{
19
+ local: z.ZodString;
20
+ cloud: z.ZodString;
21
+ }, z.core.$strict>;
22
+ routes: z.ZodRecord<z.ZodString, z.ZodObject<{
23
+ packageName: z.ZodString;
24
+ from: z.ZodArray<z.ZodEnum<{
25
+ local: "local";
26
+ cloud: "cloud";
27
+ }>>;
28
+ default: z.ZodOptional<z.ZodEnum<{
29
+ local: "local";
30
+ cloud: "cloud";
31
+ }>>;
32
+ }, z.core.$strict>>;
33
+ }, z.core.$strict>>;
34
+ }, z.core.$strict>>;
35
+ }, z.core.$strict>;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Validation rules for a single workspace package, declared in its
3
+ * `infra-kit.config.ts`. Every field is optional: a key left unset falls back to
4
+ * the active baseline, and a key set replaces that default wholesale (per-key, no
5
+ * array concatenation) so a package can opt out with an explicit empty array.
6
+ *
7
+ * The baselines themselves (`DEFAULT_RULES` / `ROOT_DEFAULT_RULES`) deliberately do
8
+ * NOT live here — they are audit POLICY, and policy belongs to the `infra-kit` CLI
9
+ * that enforces it, not to the package a consumer installs to author a config.
10
+ *
11
+ * Most packages need none of these — the standard rules live in the baseline, so
12
+ * a typical config is just `defineConfig(() => ({}))`.
13
+ *
14
+ * @example
15
+ * // infra-kit.config.ts
16
+ * import { defineConfig } from '@slip-stream-kit/config'
17
+ *
18
+ * export default defineConfig(() => ({}))
19
+ */
20
+ export interface InfraKitPackageConfig {
21
+ /** Scripts that must be present in the package's package.json `scripts` map. */
22
+ requiredScripts?: string[];
23
+ /** Files (relative to the package root) that must exist on disk. */
24
+ requiredFiles?: string[];
25
+ /** Turborepo expectations — only meaningful where a turbo.json lives (the root). */
26
+ turbo?: {
27
+ /** Tasks that must be defined in turbo.json `tasks`. */
28
+ requiredTasks?: string[];
29
+ };
30
+ /** Local-dev configuration. Accepted-and-inert to the audit; consumed by the dev server. */
31
+ dev?: InfraKitDev;
32
+ }
33
+ /** A proxy route's allowed backend source. */
34
+ export type InfraKitDevProxySource = 'local' | 'cloud';
35
+ export interface InfraKitDevProxyRoute {
36
+ /** Backend package this route targets when resolved locally. */
37
+ packageName: string;
38
+ /** Capabilities this route can resolve to. Must be non-empty. */
39
+ from: InfraKitDevProxySource[];
40
+ /**
41
+ * Source used when a local backend for this package isn't active. Required when
42
+ * `from` lists more than one source; redundant (and omitted) for a single-source
43
+ * route. When set, must be one of `from`.
44
+ */
45
+ default?: InfraKitDevProxySource;
46
+ }
47
+ export interface InfraKitDevProxy {
48
+ /** URL templates. Placeholders like `<release>`/`<packageName>`/`<env>` are substituted at dev time. */
49
+ templates: {
50
+ local: string;
51
+ cloud: string;
52
+ };
53
+ /** Path-prefix (e.g. `/api`, `/api/v1`, `/media`) → route definition. */
54
+ routes: Record<string, InfraKitDevProxyRoute>;
55
+ }
56
+ export interface InfraKitDev {
57
+ proxy?: InfraKitDevProxy;
58
+ }
59
+ /**
60
+ * Accepted shapes for a package config's default export — mirrors Vite's
61
+ * `defineConfig` input: a plain object, a sync factory, or an async factory.
62
+ */
63
+ export type InfraKitPackageConfigInput = InfraKitPackageConfig | (() => InfraKitPackageConfig) | (() => Promise<InfraKitPackageConfig>);
64
+ /**
65
+ * Identity helper that gives `infra-kit.config.ts` authors full type inference
66
+ * and editor autocomplete without changing the value — exactly like Vite's
67
+ * `defineConfig`. Resolution of the factory form happens in the CLI's loader, not here.
68
+ *
69
+ * @example
70
+ * export default defineConfig(() => ({}))
71
+ *
72
+ * @example
73
+ * export default defineConfig(() => ({ requiredScripts: [] }))
74
+ */
75
+ export declare const defineConfig: (config: InfraKitPackageConfigInput) => InfraKitPackageConfigInput;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Shared, dependency-light release-slug helper.
3
+ *
4
+ * Extracted from `lib/vite/vite.ts` so BOTH the published `infra-kit/vite` helper
5
+ * (which re-exports it) and the dev-server's dev-context fragment writer derive the
6
+ * `<release>` hostname segment from ONE implementation — the recorded slug and the
7
+ * helper-computed slug can never drift. Pure (regex only, no imports) so importing it
8
+ * into the lightweight `infra-kit/vite` bundle stays cheap.
9
+ */
10
+ /**
11
+ * Slugify an arbitrary string into a single DNS label: lowercase, collapse every
12
+ * non-alphanumeric run to `-`, and drop leading/trailing separators. Returns `''`
13
+ * when the input carries no alphanumeric run (the caller must treat that as "no label").
14
+ *
15
+ * portless rejects any hostname outside `[a-z0-9.-]`, so every segment fed into a
16
+ * `<release>.<packageName>.localhost` alias must pass through here. A scoped npm name
17
+ * (`@hulyo/client-ui`) is the motivating case: registering it raw fails with
18
+ * `Invalid hostname`, and because the driver swallows that into a best-effort `false`,
19
+ * the whole hero-URL path degrades silently to `localhost:<port>`.
20
+ *
21
+ * Distinct from {@link slugifyRelease}: this does NOT strip a git-flow prefix, so a
22
+ * package legitimately named `fix-utils` keeps its `fix-` prefix.
23
+ *
24
+ * @example
25
+ * slugifyHostLabel('@hulyo/client-ui') // => 'hulyo-client-ui'
26
+ * slugifyHostLabel('backend-api') // => 'backend-api'
27
+ */
28
+ export declare const slugifyHostLabel: (label: string) => string;
29
+ /**
30
+ * Slugify a git branch into a `<release>` token: strip a leading git-flow prefix
31
+ * (`feature/`, `release/`, …), then reduce the remainder to a single DNS label.
32
+ *
33
+ * @example
34
+ * slugifyRelease('release/2.4') // => '2-4'
35
+ * slugifyRelease('feature/HUL-123') // => 'hul-123'
36
+ */
37
+ export declare const slugifyRelease: (branch: string) => string;
38
+ /**
39
+ * The `<release>` label used when no git branch resolves (outside a repo, or a branch that slugifies to
40
+ * nothing). Both the dev-server's alias writer and `infra-kit/vite`'s template interpolation fall back
41
+ * to this SAME constant — a divergence here would emit a hostname no alias backs.
42
+ */
43
+ export declare const DEFAULT_RELEASE_SLUG = "local";
@@ -0,0 +1,58 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Pure (node-free) vendor config schema + authoring helper. Kept separate from
4
+ * `config.ts` (which imports node builtins for the runtime loader) so the public
5
+ * lib entry can re-export `defineVendorConfig` without dragging node types into
6
+ * the emitted `.d.ts`.
7
+ */
8
+ /**
9
+ * Filename a source repo provides at its root to declare WHAT `vendor sync`
10
+ * copies (`copy[]`). Lives ONLY on the write path — `vendor check` never loads it.
11
+ * WHERE/WHICH to stamp (`workspaceDir` + `targets`) is machine-local and lives in
12
+ * the user-global factory config (`~/.infra-kit/vendor.json`).
13
+ */
14
+ export declare const VENDOR_CONFIG_FILE = "vendor.config.ts";
15
+ /**
16
+ * One item to sync from the source repo into each target. `vendored: true` marks
17
+ * workspace packages that must land under `vendor/` (the single-source-of-truth
18
+ * code); everything else is root-level tooling that stays at the repo root.
19
+ */
20
+ export declare const vendorCopyItemSchema: z.ZodObject<{
21
+ name: z.ZodString;
22
+ source: z.ZodString;
23
+ target: z.ZodString;
24
+ type: z.ZodEnum<{
25
+ file: "file";
26
+ directory: "directory";
27
+ }>;
28
+ vendored: z.ZodOptional<z.ZodBoolean>;
29
+ }, z.core.$strip>;
30
+ export declare const vendorConfigSchema: z.ZodObject<{
31
+ copy: z.ZodArray<z.ZodObject<{
32
+ name: z.ZodString;
33
+ source: z.ZodString;
34
+ target: z.ZodString;
35
+ type: z.ZodEnum<{
36
+ file: "file";
37
+ directory: "directory";
38
+ }>;
39
+ vendored: z.ZodOptional<z.ZodBoolean>;
40
+ }, z.core.$strip>>;
41
+ }, z.core.$strict>;
42
+ export type VendorCopyItem = z.infer<typeof vendorCopyItemSchema>;
43
+ export type VendorConfig = z.infer<typeof vendorConfigSchema>;
44
+ /**
45
+ * Identity helper for authoring a type-safe `vendor.config.ts` in a source repo.
46
+ * Re-exported from the public lib entry so a source repo can
47
+ * `import { defineVendorConfig } from 'infra-kit'`.
48
+ *
49
+ * NOTE: a `vendor.config.ts` must be type-strippable — Node's native type
50
+ * stripping (Node >= 24) loads it without a build step, which forbids `enum`,
51
+ * `namespace`, and parameter properties.
52
+ *
53
+ * @example
54
+ * export default defineVendorConfig({
55
+ * copy: [{ name: 'Configs', source: 'vendor/configs', target: 'vendor/configs', type: 'directory', vendored: true }],
56
+ * })
57
+ */
58
+ export declare const defineVendorConfig: (config: VendorConfig) => VendorConfig;