@mandujs/core 0.48.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mandujs/core",
3
- "version": "0.48.0",
3
+ "version": "0.50.0",
4
4
  "description": "Mandu Framework Core - Spec, Generator, Guard, Runtime",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -57,6 +57,15 @@ export {
57
57
  type BrainInferenceOptions,
58
58
  } from "./inference/brain";
59
59
 
60
+ export {
61
+ extractExplicitIntents,
62
+ mergeExplicitIntents,
63
+ type ExplicitIntentEntry,
64
+ type ExplicitIntentError,
65
+ type ExtractExplicitIntentsOptions,
66
+ type ExtractExplicitIntentsResult,
67
+ } from "./inference/filling-extract";
68
+
60
69
  export {
61
70
  planDeploy,
62
71
  planHasChanges,
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Build-time extractor for `.deploy()` intents on `Mandu.filling()`
3
+ * route modules.
4
+ *
5
+ * Issue #250 M5. Bridges the runtime DSL (filling.deploy) and the
6
+ * build-time cache (`.mandu/deploy.intent.json`):
7
+ *
8
+ * 1. For every route in the manifest, dynamically `import()` the
9
+ * module file.
10
+ * 2. If the default export looks like a `ManduFilling` instance and
11
+ * its `getDeployIntent()` returns a non-null value, capture it
12
+ * as a Zod-validated `DeployIntent`.
13
+ * 3. The CLI / MCP merges captured entries into the previous cache
14
+ * with `source: "explicit"` BEFORE calling `planDeploy()` —
15
+ * explicit entries are protected from inference (M1) so the
16
+ * user's `.deploy()` always wins.
17
+ *
18
+ * Failure modes (non-fatal — extractor returns the offending route in
19
+ * `errors[]`, planner falls back to inference for it):
20
+ *
21
+ * - Module file cannot be imported (syntax error, missing dep).
22
+ * - Default export is not a filling instance.
23
+ * - `.deploy({...})` payload fails Zod validation (this throws at
24
+ * module load, so the import error path catches it).
25
+ *
26
+ * The extractor uses dynamic import rather than AST parsing because
27
+ * the manifest is built by importing routes anyway (for static
28
+ * params, slot metadata, etc.) — adding another loader would
29
+ * duplicate work. Side effects in route modules ARE a concern, but
30
+ * Mandu's convention is to put side effects in `loader()` / `get()`
31
+ * callbacks (which the extractor never invokes).
32
+ */
33
+
34
+ import path from "node:path";
35
+ import { pathToFileURL } from "node:url";
36
+ import { promises as fs } from "node:fs";
37
+ import { DeployIntent, type DeployIntent as DeployIntentType } from "../intent";
38
+ import type { RoutesManifest, RouteSpec } from "../../spec/schema";
39
+
40
+ export interface ExplicitIntentEntry {
41
+ routeId: string;
42
+ pattern: string;
43
+ /** Fully-validated, defaults-applied intent. */
44
+ intent: DeployIntentType;
45
+ }
46
+
47
+ export interface ExplicitIntentError {
48
+ routeId: string;
49
+ pattern: string;
50
+ module: string;
51
+ reason: string;
52
+ }
53
+
54
+ export interface ExtractExplicitIntentsResult {
55
+ entries: ExplicitIntentEntry[];
56
+ errors: ExplicitIntentError[];
57
+ }
58
+
59
+ export interface ExtractExplicitIntentsOptions {
60
+ /**
61
+ * Override the dynamic import for tests. Receives the absolute file
62
+ * URL the extractor would have imported and returns whatever module
63
+ * shape the test wants to inject.
64
+ */
65
+ importer?: (fileUrl: string) => Promise<unknown>;
66
+ /**
67
+ * Skip routes whose modules don't exist on disk. Default `true` —
68
+ * a missing route is a manifest staleness issue, not an extractor
69
+ * concern.
70
+ */
71
+ skipMissing?: boolean;
72
+ }
73
+
74
+ /**
75
+ * Walk the manifest, import each route, and capture explicit deploy
76
+ * intents from `Mandu.filling().deploy({...})` declarations.
77
+ */
78
+ export async function extractExplicitIntents(
79
+ rootDir: string,
80
+ manifest: RoutesManifest,
81
+ options: ExtractExplicitIntentsOptions = {},
82
+ ): Promise<ExtractExplicitIntentsResult> {
83
+ const importer = options.importer ?? defaultImporter;
84
+ const skipMissing = options.skipMissing ?? true;
85
+ const entries: ExplicitIntentEntry[] = [];
86
+ const errors: ExplicitIntentError[] = [];
87
+
88
+ for (const route of manifest.routes) {
89
+ const modulePath = path.resolve(rootDir, route.module);
90
+ if (skipMissing) {
91
+ const exists = await pathExists(modulePath);
92
+ if (!exists) continue;
93
+ }
94
+
95
+ let mod: unknown;
96
+ try {
97
+ const url = pathToFileURL(modulePath).href;
98
+ mod = await importer(url);
99
+ } catch (err) {
100
+ errors.push({
101
+ routeId: route.id,
102
+ pattern: route.pattern,
103
+ module: route.module,
104
+ reason: `import failed: ${err instanceof Error ? err.message : String(err)}`,
105
+ });
106
+ continue;
107
+ }
108
+
109
+ const filling = pickDefaultFilling(mod);
110
+ if (!filling) continue;
111
+
112
+ let raw: unknown;
113
+ try {
114
+ raw = filling.getDeployIntent();
115
+ } catch (err) {
116
+ errors.push({
117
+ routeId: route.id,
118
+ pattern: route.pattern,
119
+ module: route.module,
120
+ reason: `getDeployIntent threw: ${err instanceof Error ? err.message : String(err)}`,
121
+ });
122
+ continue;
123
+ }
124
+
125
+ if (raw === undefined || raw === null) continue;
126
+
127
+ // Validate + apply schema defaults so downstream code (cache,
128
+ // adapters) never sees half-typed shapes.
129
+ const parsed = DeployIntent.safeParse(raw);
130
+ if (!parsed.success) {
131
+ errors.push({
132
+ routeId: route.id,
133
+ pattern: route.pattern,
134
+ module: route.module,
135
+ reason: `.deploy() validation failed: ${parsed.error.errors.map((e) => e.message).join("; ")}`,
136
+ });
137
+ continue;
138
+ }
139
+
140
+ entries.push({
141
+ routeId: route.id,
142
+ pattern: route.pattern,
143
+ intent: parsed.data,
144
+ });
145
+ }
146
+
147
+ return { entries, errors };
148
+ }
149
+
150
+ // ─── Internals ────────────────────────────────────────────────────────
151
+
152
+ /**
153
+ * Loose duck-type check for ManduFilling. We can't `instanceof`
154
+ * because the imported module's `ManduFilling` constructor may not be
155
+ * the one this package was bundled with (workspace symlinks, package
156
+ * upgrades, etc.). Instead, we look for the public `getDeployIntent`
157
+ * method that ships in the same release as `.deploy()` — versions
158
+ * without the M5 method silently no-op (no entry captured).
159
+ */
160
+ type FillingLike = { getDeployIntent: () => unknown };
161
+
162
+ function isFillingLike(value: unknown): value is FillingLike {
163
+ return (
164
+ value != null &&
165
+ typeof value === "object" &&
166
+ "getDeployIntent" in value &&
167
+ typeof (value as { getDeployIntent: unknown }).getDeployIntent === "function"
168
+ );
169
+ }
170
+
171
+ function pickDefaultFilling(mod: unknown): FillingLike | null {
172
+ if (!mod || typeof mod !== "object") return null;
173
+ const candidate = (mod as { default?: unknown }).default;
174
+ return isFillingLike(candidate) ? candidate : null;
175
+ }
176
+
177
+ async function defaultImporter(fileUrl: string): Promise<unknown> {
178
+ return await import(fileUrl);
179
+ }
180
+
181
+ async function pathExists(p: string): Promise<boolean> {
182
+ try {
183
+ await fs.access(p);
184
+ return true;
185
+ } catch {
186
+ return false;
187
+ }
188
+ }
189
+
190
+ // ─── Cache merge helper ───────────────────────────────────────────────
191
+
192
+ import type { DeployIntentCache, DeployIntentCacheEntry } from "../cache";
193
+ import { hashSource } from "./context";
194
+
195
+ /**
196
+ * Merge extractor entries into a cache, marking each one as
197
+ * `source: "explicit"`. Existing entries with the same route id are
198
+ * overwritten — the user's `.deploy()` always wins.
199
+ *
200
+ * `sourceHash` is set from the file's current bytes so the planner
201
+ * can detect drift between the cached intent and the live source.
202
+ * The cache's `generatedAt` and `brainModel` are left untouched so
203
+ * the merge step doesn't pretend to be a re-plan.
204
+ */
205
+ export async function mergeExplicitIntents(
206
+ cache: DeployIntentCache,
207
+ entries: ReadonlyArray<ExplicitIntentEntry>,
208
+ rootDir: string,
209
+ manifest: RoutesManifest,
210
+ ): Promise<DeployIntentCache> {
211
+ if (entries.length === 0) return cache;
212
+ const next: DeployIntentCache = {
213
+ ...cache,
214
+ intents: { ...cache.intents },
215
+ };
216
+ const routeById = new Map<string, RouteSpec>(
217
+ manifest.routes.map((r) => [r.id, r]),
218
+ );
219
+
220
+ for (const entry of entries) {
221
+ const route = routeById.get(entry.routeId);
222
+ if (!route) continue;
223
+ const modulePath = path.resolve(rootDir, route.module);
224
+ let source = "";
225
+ try {
226
+ source = await fs.readFile(modulePath, "utf8");
227
+ } catch {
228
+ // Route file vanished between extraction and merge — keep
229
+ // going with an empty hash; the planner will catch the
230
+ // missing-source case on its own.
231
+ }
232
+ const cacheEntry: DeployIntentCacheEntry = {
233
+ intent: entry.intent,
234
+ source: "explicit",
235
+ rationale:
236
+ cache.intents[entry.routeId]?.source === "explicit"
237
+ ? cache.intents[entry.routeId]?.rationale ?? "explicit .deploy() override"
238
+ : "explicit .deploy() override",
239
+ sourceHash: hashSource(source),
240
+ };
241
+ next.intents[entry.routeId] = cacheEntry;
242
+ }
243
+
244
+ return next;
245
+ }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Issue #245 M3 — Tailwind v4 `@theme` compiler tests.
3
+ *
4
+ * Pin the contract every other tool (CLI sync, MCP discovery,
5
+ * dev-mode watcher) depends on:
6
+ *
7
+ * - DESIGN.md tokens → CSS variable naming (Tailwind v4 convention).
8
+ * - Slug normalisation handles the human-friendly names DESIGN.md
9
+ * authors actually write.
10
+ * - Markered region merge preserves user-edited regions.
11
+ * - Conflicts surface explicitly so the user can reconcile.
12
+ */
13
+
14
+ import { describe, it, expect } from "bun:test";
15
+ import { parseDesignMd } from "../parser";
16
+ import {
17
+ compileTailwindTheme,
18
+ mergeThemeIntoCss,
19
+ slugifyTokenName,
20
+ stripMarkeredBlock,
21
+ THEME_MARKER_END,
22
+ THEME_MARKER_START,
23
+ } from "../tailwind-theme";
24
+
25
+ describe("slugifyTokenName", () => {
26
+ it("kebab-cases multi-word names", () => {
27
+ expect(slugifyTokenName("Hot Peach")).toBe("hot-peach");
28
+ expect(slugifyTokenName("Body Small")).toBe("body-small");
29
+ expect(slugifyTokenName("h1 hero")).toBe("h1-hero");
30
+ });
31
+
32
+ it("collapses runs of whitespace and underscores", () => {
33
+ expect(slugifyTokenName("primary color")).toBe("primary-color");
34
+ expect(slugifyTokenName("warm_cream")).toBe("warm-cream");
35
+ });
36
+
37
+ it("strips characters that aren't word/space/dash", () => {
38
+ expect(slugifyTokenName("primary!")).toBe("primary");
39
+ expect(slugifyTokenName("orange (500)")).toBe("orange-500");
40
+ });
41
+
42
+ it("lowercases ASCII", () => {
43
+ expect(slugifyTokenName("Primary")).toBe("primary");
44
+ });
45
+ });
46
+
47
+ describe("compileTailwindTheme — color palette", () => {
48
+ it("emits --color-<slug> per token", () => {
49
+ const spec = parseDesignMd(`# Test
50
+ ## Color Palette
51
+ - Primary — #FF8C42 — brand accent
52
+ - Surface — #FFF8F0 — neutral background
53
+ `);
54
+ const compiled = compileTailwindTheme(spec);
55
+ const vars = compiled.entries.map((e) => [e.variable, e.value]);
56
+ expect(vars).toContainEqual(["--color-primary", "#FF8C42"]);
57
+ expect(vars).toContainEqual(["--color-surface", "#FFF8F0"]);
58
+ });
59
+
60
+ it("warns and skips tokens with no parseable value", () => {
61
+ const spec = parseDesignMd(`# Test
62
+ ## Color Palette
63
+ - Primary — see Stripe brand docs
64
+ - Surface — #FFF8F0
65
+ `);
66
+ const compiled = compileTailwindTheme(spec);
67
+ expect(compiled.entries.find((e) => e.variable === "--color-primary")).toBeUndefined();
68
+ expect(compiled.warnings.some((w) => w.kind === "missing-value" && w.tokenName === "Primary")).toBe(true);
69
+ });
70
+
71
+ it("flags slug collisions", () => {
72
+ const spec = parseDesignMd(`# Test
73
+ ## Color Palette
74
+ - Primary — #ff0000
75
+ - primary — #00ff00
76
+ `);
77
+ const compiled = compileTailwindTheme(spec);
78
+ expect(compiled.warnings.some((w) => w.kind === "slug-collision")).toBe(true);
79
+ // First wins.
80
+ expect(compiled.entries.find((e) => e.variable === "--color-primary")?.value).toBe("#ff0000");
81
+ });
82
+ });
83
+
84
+ describe("compileTailwindTheme — emit order + section comments", () => {
85
+ it("groups entries by section with comment dividers", () => {
86
+ const spec = parseDesignMd(`# Test
87
+ ## Color Palette
88
+ - Primary — #FF8C42
89
+
90
+ ## Layout
91
+ - sm: 0.5rem
92
+ - md: 1rem
93
+ `);
94
+ const compiled = compileTailwindTheme(spec);
95
+ expect(compiled.cssBody).toContain("/* Colors */");
96
+ expect(compiled.cssBody).toContain("--color-primary: #FF8C42;");
97
+ expect(compiled.cssBody).toContain("/* Spacing */");
98
+ expect(compiled.cssBody).toContain("--spacing-sm: 0.5rem;");
99
+ });
100
+ });
101
+
102
+ describe("mergeThemeIntoCss", () => {
103
+ it("inserts a fresh markered block when none exists", () => {
104
+ const spec = parseDesignMd(`# Test
105
+ ## Color Palette
106
+ - Primary — #FF8C42
107
+ `);
108
+ const compiled = compileTailwindTheme(spec);
109
+ const result = mergeThemeIntoCss("@import 'tailwindcss';\n", compiled);
110
+ expect(result.inserted).toBe(true);
111
+ expect(result.css).toContain(THEME_MARKER_START);
112
+ expect(result.css).toContain(THEME_MARKER_END);
113
+ expect(result.css).toContain("--color-primary: #FF8C42;");
114
+ expect(result.css).toContain("@import 'tailwindcss';");
115
+ });
116
+
117
+ it("replaces the markered region only — leaves surrounding content untouched", () => {
118
+ const initial = `@import 'tailwindcss';
119
+
120
+ /* user comment */
121
+ ${THEME_MARKER_START}
122
+ @theme {
123
+ --color-primary: oldvalue;
124
+ }
125
+ ${THEME_MARKER_END}
126
+
127
+ .user-class { color: red; }
128
+ `;
129
+ const spec = parseDesignMd(`# Test
130
+ ## Color Palette
131
+ - Primary — #FF8C42
132
+ `);
133
+ const compiled = compileTailwindTheme(spec);
134
+ const result = mergeThemeIntoCss(initial, compiled);
135
+ expect(result.inserted).toBe(false);
136
+ expect(result.css).toContain("/* user comment */");
137
+ expect(result.css).toContain(".user-class { color: red; }");
138
+ expect(result.css).toContain("--color-primary: #FF8C42;");
139
+ expect(result.css).not.toContain("oldvalue");
140
+ });
141
+
142
+ it("flags conflicts when a hand-written @theme variable contradicts DESIGN.md", () => {
143
+ const initial = `@import 'tailwindcss';
144
+ @theme {
145
+ --color-primary: #000000;
146
+ }
147
+ `;
148
+ const spec = parseDesignMd(`# Test
149
+ ## Color Palette
150
+ - Primary — #FF8C42
151
+ `);
152
+ const compiled = compileTailwindTheme(spec);
153
+ const result = mergeThemeIntoCss(initial, compiled);
154
+ expect(result.conflicts).toHaveLength(1);
155
+ expect(result.conflicts[0]!.variable).toBe("--color-primary");
156
+ expect(result.conflicts[0]!.fromDesign).toBe("#FF8C42");
157
+ expect(result.conflicts[0]!.fromCss).toBe("#000000");
158
+ });
159
+
160
+ it("emits an empty markered region (no orphans) when DESIGN.md has no tokens", () => {
161
+ const spec = parseDesignMd("# Empty\n");
162
+ const compiled = compileTailwindTheme(spec);
163
+ const result = mergeThemeIntoCss("body { margin: 0; }\n", compiled);
164
+ expect(result.css).toContain(THEME_MARKER_START);
165
+ expect(result.css).toContain(THEME_MARKER_END);
166
+ expect(result.css).toContain("body { margin: 0; }");
167
+ });
168
+ });
169
+
170
+ describe("stripMarkeredBlock", () => {
171
+ it("removes only the markered region", () => {
172
+ const css = `@import 'tailwindcss';
173
+ ${THEME_MARKER_START}
174
+ @theme {
175
+ --color-primary: #FF8C42;
176
+ }
177
+ ${THEME_MARKER_END}
178
+ .user { color: red; }
179
+ `;
180
+ const result = stripMarkeredBlock(css);
181
+ expect(result).not.toContain("--color-primary");
182
+ expect(result).toContain("@import 'tailwindcss';");
183
+ expect(result).toContain(".user { color: red; }");
184
+ });
185
+
186
+ it("is a no-op when no markers are present", () => {
187
+ const css = `@import 'tailwindcss';\n`;
188
+ expect(stripMarkeredBlock(css)).toBe(css);
189
+ });
190
+ });
191
+
192
+ describe("end-to-end — stripe-like DESIGN.md → Tailwind theme", () => {
193
+ it("compiles a full multi-section DESIGN.md into one cohesive @theme", () => {
194
+ const designMd = `# Stripe-like
195
+
196
+ ## Color Palette
197
+ - Primary — #635BFF — brand
198
+ - Surface — #FFFFFF — page background
199
+ - Text — #1A1F36 — body text
200
+
201
+ ## Typography
202
+ - body: font-family: "Inter", sans-serif; size: 16px; line-height: 1.5
203
+ - h1 hero: font-family: "Inter", sans-serif; size: 48px; line-height: 1.1
204
+
205
+ ## Layout
206
+ - xs: 0.25rem
207
+ - sm: 0.5rem
208
+ - md: 1rem
209
+
210
+ ## Depth & Elevation
211
+ - card — 0 1px 3px rgba(0,0,0,0.1)
212
+ - modal — 0 25px 50px rgba(0,0,0,0.25)
213
+ `;
214
+ const spec = parseDesignMd(designMd);
215
+ const compiled = compileTailwindTheme(spec);
216
+
217
+ // Colors
218
+ expect(compiled.cssBody).toContain("--color-primary: #635BFF;");
219
+ expect(compiled.cssBody).toContain("--color-surface: #FFFFFF;");
220
+ // Typography (font + text)
221
+ expect(compiled.cssBody).toContain("--font-body:");
222
+ expect(compiled.cssBody).toContain("--text-h1-hero: 48px / 1.1;");
223
+ // Spacing
224
+ expect(compiled.cssBody).toContain("--spacing-md: 1rem;");
225
+ // Shadows
226
+ expect(compiled.cssBody).toContain("--shadow-card:");
227
+ expect(compiled.cssBody).toContain("--shadow-modal:");
228
+ });
229
+ });
@@ -20,6 +20,20 @@ export {
20
20
  AWESOME_DESIGN_MD_RAW_BASE,
21
21
  } from "./scaffold";
22
22
 
23
+ export {
24
+ compileTailwindTheme,
25
+ mergeThemeIntoCss,
26
+ stripMarkeredBlock,
27
+ slugifyTokenName,
28
+ THEME_MARKER_START,
29
+ THEME_MARKER_END,
30
+ type CompiledTheme,
31
+ type CompiledThemeEntry,
32
+ type CompiledThemeWarning,
33
+ type ThemeMergeConflict,
34
+ type ThemeMergeResult,
35
+ } from "./tailwind-theme";
36
+
23
37
  export type {
24
38
  AgentPrompt,
25
39
  AgentPromptsSection,
@@ -0,0 +1,441 @@
1
+ /**
2
+ * DESIGN.md → Tailwind v4 `@theme` compiler (Token Bridge).
3
+ *
4
+ * Issue #245 M3 — Team E. Reads structured tokens from a parsed
5
+ * `DesignSpec` and emits the CSS `@theme` block Tailwind v4 inlines
6
+ * to generate utility classes. The compiler is the **only** authoritative
7
+ * source for the CSS variable names — Tailwind's naming convention is
8
+ * baked in here so other tools (Guard, MCP) consult one place when
9
+ * they need to map a token name to its `--var`.
10
+ *
11
+ * # Variable naming (Tailwind v4 convention)
12
+ *
13
+ * - `--color-<name>` — color palette
14
+ * - `--font-<name>` — typography (font family)
15
+ * - `--text-<name>` — typography (font size + line-height)
16
+ * - `--spacing-<scale>` — layout / spacing
17
+ * - `--shadow-<name>` — depth / elevation
18
+ *
19
+ * # Token name normalisation
20
+ *
21
+ * DESIGN.md author writes tokens in human form ("Hot Peach", "Body
22
+ * Small"). Tailwind variables need kebab-case ASCII-safe identifiers.
23
+ * `slugifyTokenName()` is the canonical normaliser:
24
+ *
25
+ * "Hot Peach" → "hot-peach"
26
+ * "Body Small" → "body-small"
27
+ * "h1 hero" → "h1-hero"
28
+ *
29
+ * Collisions (two tokens that slugify the same) are flagged as
30
+ * `conflicts[]` so the caller can surface them — the compiler keeps
31
+ * the first occurrence and skips duplicates.
32
+ *
33
+ * # Conflict detection
34
+ *
35
+ * `compileTailwindTheme` also emits warnings when a DESIGN.md token
36
+ * contradicts an existing `@theme` block: same variable name, different
37
+ * value. The merge step (`mergeThemeIntoCss`) preserves user-edited
38
+ * regions outside the markers, so this is the only place the conflict
39
+ * can be detected.
40
+ */
41
+
42
+ import type { DesignSpec } from "./types";
43
+
44
+ // ─── Marker constants ────────────────────────────────────────────────
45
+
46
+ /**
47
+ * Marker comments wrapping the auto-generated `@theme` body.
48
+ *
49
+ * Mandu only ever rewrites the region between these markers. Anything
50
+ * outside is treated as user-owned and preserved verbatim. The marker
51
+ * format is intentionally noisy so a casual reader can tell at a
52
+ * glance "this is generated, don't hand-edit".
53
+ */
54
+ export const THEME_MARKER_START = "/* @mandu-design-sync:start — generated from DESIGN.md, do not edit */";
55
+ export const THEME_MARKER_END = "/* @mandu-design-sync:end */";
56
+
57
+ // ─── Public surface ───────────────────────────────────────────────────
58
+
59
+ export interface CompiledThemeEntry {
60
+ /** Tailwind v4 CSS variable name (`--color-primary`). */
61
+ variable: string;
62
+ value: string;
63
+ /** Origin token from the DesignSpec (e.g. "Hot Peach"). */
64
+ sourceTokenName: string;
65
+ /** Section the token came from. */
66
+ section: "color-palette" | "typography" | "layout" | "shadows";
67
+ }
68
+
69
+ export interface CompiledThemeWarning {
70
+ kind: "missing-value" | "slug-collision";
71
+ message: string;
72
+ /** Token name as it appears in DESIGN.md. */
73
+ tokenName: string;
74
+ section: CompiledThemeEntry["section"];
75
+ }
76
+
77
+ export interface CompiledTheme {
78
+ /** Flat list of variables in emit order. */
79
+ entries: CompiledThemeEntry[];
80
+ /** Non-fatal issues — missing values, slug collisions. */
81
+ warnings: CompiledThemeWarning[];
82
+ /** The `@theme { ... }` body as it would be written to disk. */
83
+ cssBody: string;
84
+ }
85
+
86
+ export interface ThemeMergeConflict {
87
+ variable: string;
88
+ fromDesign: string;
89
+ fromCss: string;
90
+ }
91
+
92
+ export interface ThemeMergeResult {
93
+ /** Updated CSS — markered region replaced, rest preserved. */
94
+ css: string;
95
+ /**
96
+ * Variables that collide with manual `@theme` declarations OUTSIDE
97
+ * the marker region. The caller surfaces these in CLI output so the
98
+ * user knows to reconcile.
99
+ */
100
+ conflicts: ThemeMergeConflict[];
101
+ /** Whether the markered region already existed (vs. was inserted). */
102
+ inserted: boolean;
103
+ }
104
+
105
+ /**
106
+ * Compile a `DesignSpec` into a Tailwind v4 `@theme` block.
107
+ *
108
+ * Tokens with no parseable value are skipped with a `missing-value`
109
+ * warning — they're declarative-only entries (e.g. "primary — see
110
+ * docs"). Slug collisions also warn but never throw.
111
+ */
112
+ export function compileTailwindTheme(spec: DesignSpec): CompiledTheme {
113
+ const entries: CompiledThemeEntry[] = [];
114
+ const warnings: CompiledThemeWarning[] = [];
115
+ const seen = new Set<string>();
116
+
117
+ // Color palette → --color-<slug>
118
+ for (const token of spec.sections["color-palette"].tokens) {
119
+ const variable = `--color-${slugifyTokenName(token.name)}`;
120
+ if (!token.value) {
121
+ warnings.push({
122
+ kind: "missing-value",
123
+ message: `color "${token.name}" has no parseable value — skipped`,
124
+ tokenName: token.name,
125
+ section: "color-palette",
126
+ });
127
+ continue;
128
+ }
129
+ if (seen.has(variable)) {
130
+ warnings.push({
131
+ kind: "slug-collision",
132
+ message: `color "${token.name}" collides with an earlier token on ${variable} — skipped`,
133
+ tokenName: token.name,
134
+ section: "color-palette",
135
+ });
136
+ continue;
137
+ }
138
+ seen.add(variable);
139
+ entries.push({
140
+ variable,
141
+ value: token.value,
142
+ sourceTokenName: token.name,
143
+ section: "color-palette",
144
+ });
145
+ }
146
+
147
+ // Typography → --font-<slug> + --text-<slug>
148
+ for (const token of spec.sections.typography.tokens) {
149
+ const slug = slugifyTokenName(token.name);
150
+ if (token.fontFamily) {
151
+ const variable = `--font-${slug}`;
152
+ if (!seen.has(variable)) {
153
+ seen.add(variable);
154
+ entries.push({
155
+ variable,
156
+ value: token.fontFamily,
157
+ sourceTokenName: token.name,
158
+ section: "typography",
159
+ });
160
+ } else {
161
+ warnings.push({
162
+ kind: "slug-collision",
163
+ message: `typography "${token.name}" collides on ${variable}`,
164
+ tokenName: token.name,
165
+ section: "typography",
166
+ });
167
+ }
168
+ }
169
+ if (token.size) {
170
+ const variable = `--text-${slug}`;
171
+ const value = token.lineHeight ? `${token.size} / ${token.lineHeight}` : token.size;
172
+ if (!seen.has(variable)) {
173
+ seen.add(variable);
174
+ entries.push({
175
+ variable,
176
+ value,
177
+ sourceTokenName: token.name,
178
+ section: "typography",
179
+ });
180
+ } else {
181
+ warnings.push({
182
+ kind: "slug-collision",
183
+ message: `typography "${token.name}" collides on ${variable}`,
184
+ tokenName: token.name,
185
+ section: "typography",
186
+ });
187
+ }
188
+ }
189
+ if (!token.fontFamily && !token.size) {
190
+ warnings.push({
191
+ kind: "missing-value",
192
+ message: `typography "${token.name}" has neither fontFamily nor size — skipped`,
193
+ tokenName: token.name,
194
+ section: "typography",
195
+ });
196
+ }
197
+ }
198
+
199
+ // Layout / spacing → --spacing-<slug>
200
+ for (const token of spec.sections.layout.tokens) {
201
+ if (!token.value) {
202
+ warnings.push({
203
+ kind: "missing-value",
204
+ message: `spacing "${token.name}" has no value — skipped`,
205
+ tokenName: token.name,
206
+ section: "layout",
207
+ });
208
+ continue;
209
+ }
210
+ const variable = `--spacing-${slugifyTokenName(token.name)}`;
211
+ if (seen.has(variable)) {
212
+ warnings.push({
213
+ kind: "slug-collision",
214
+ message: `spacing "${token.name}" collides on ${variable}`,
215
+ tokenName: token.name,
216
+ section: "layout",
217
+ });
218
+ continue;
219
+ }
220
+ seen.add(variable);
221
+ entries.push({
222
+ variable,
223
+ value: token.value,
224
+ sourceTokenName: token.name,
225
+ section: "layout",
226
+ });
227
+ }
228
+
229
+ // Shadows → --shadow-<slug>
230
+ for (const token of spec.sections.shadows.tokens) {
231
+ if (!token.value) {
232
+ warnings.push({
233
+ kind: "missing-value",
234
+ message: `shadow "${token.name}" has no value — skipped`,
235
+ tokenName: token.name,
236
+ section: "shadows",
237
+ });
238
+ continue;
239
+ }
240
+ const variable = `--shadow-${slugifyTokenName(token.name)}`;
241
+ if (seen.has(variable)) {
242
+ warnings.push({
243
+ kind: "slug-collision",
244
+ message: `shadow "${token.name}" collides on ${variable}`,
245
+ tokenName: token.name,
246
+ section: "shadows",
247
+ });
248
+ continue;
249
+ }
250
+ seen.add(variable);
251
+ entries.push({
252
+ variable,
253
+ value: token.value,
254
+ sourceTokenName: token.name,
255
+ section: "shadows",
256
+ });
257
+ }
258
+
259
+ return {
260
+ entries,
261
+ warnings,
262
+ cssBody: formatThemeBody(entries),
263
+ };
264
+ }
265
+
266
+ /**
267
+ * Merge a compiled `@theme` body into an existing CSS file. The
268
+ * markered region (between `THEME_MARKER_START` and `_END`) is
269
+ * **replaced**; everything outside is preserved verbatim.
270
+ *
271
+ * If the markers are absent, the merger inserts a fresh markered block:
272
+ * - Inside the first existing `@theme { ... }` block when one exists
273
+ * (so users get to keep their hand-written palette and the
274
+ * generated block sits alongside it).
275
+ * - Otherwise as a top-level `@theme { ... }` block prepended to the
276
+ * file. The user can move it later — we err on the side of
277
+ * "visible at the top" rather than "buried somewhere".
278
+ *
279
+ * Conflicts: variables declared both inside the generated region AND
280
+ * inside a hand-written `@theme` block elsewhere in the file are
281
+ * surfaced in `conflicts[]`. The auto-generated value wins inside the
282
+ * markered region; the user's value stays in their own block. The
283
+ * caller decides what to do with the warning.
284
+ */
285
+ export function mergeThemeIntoCss(
286
+ existingCss: string,
287
+ compiled: CompiledTheme,
288
+ ): ThemeMergeResult {
289
+ const generatedBlock = renderMarkeredBlock(compiled.cssBody);
290
+
291
+ const startIdx = existingCss.indexOf(THEME_MARKER_START);
292
+ const endIdx = existingCss.indexOf(THEME_MARKER_END);
293
+
294
+ let merged: string;
295
+ let inserted: boolean;
296
+ if (startIdx >= 0 && endIdx > startIdx) {
297
+ const before = existingCss.slice(0, startIdx);
298
+ const after = existingCss.slice(endIdx + THEME_MARKER_END.length);
299
+ merged = `${before}${generatedBlock}${after}`;
300
+ inserted = false;
301
+ } else {
302
+ merged = insertMarkeredBlock(existingCss, generatedBlock);
303
+ inserted = true;
304
+ }
305
+
306
+ const conflicts = detectMergeConflicts(existingCss, compiled);
307
+ return { css: merged, conflicts, inserted };
308
+ }
309
+
310
+ /**
311
+ * Strip the markered block from a CSS file — used by `mandu design
312
+ * sync --remove` and tests.
313
+ */
314
+ export function stripMarkeredBlock(css: string): string {
315
+ const startIdx = css.indexOf(THEME_MARKER_START);
316
+ const endIdx = css.indexOf(THEME_MARKER_END);
317
+ if (startIdx < 0 || endIdx < startIdx) return css;
318
+ const before = css.slice(0, startIdx).replace(/\n*$/, "\n");
319
+ const after = css.slice(endIdx + THEME_MARKER_END.length).replace(/^\n+/, "");
320
+ return `${before}${after}`;
321
+ }
322
+
323
+ /**
324
+ * Slugify a human-friendly token name into a kebab-case ASCII slug
325
+ * Tailwind v4 accepts as a CSS variable suffix.
326
+ */
327
+ export function slugifyTokenName(name: string): string {
328
+ return name
329
+ .normalize("NFKD")
330
+ .replace(/[^\w\s-]/g, "")
331
+ .trim()
332
+ .replace(/\s+/g, "-")
333
+ .replace(/_/g, "-")
334
+ .replace(/-+/g, "-")
335
+ .toLowerCase();
336
+ }
337
+
338
+ // ─── Internals ────────────────────────────────────────────────────────
339
+
340
+ function formatThemeBody(entries: CompiledThemeEntry[]): string {
341
+ if (entries.length === 0) return "";
342
+ const lines: string[] = [];
343
+ let lastSection: CompiledThemeEntry["section"] | null = null;
344
+ for (const entry of entries) {
345
+ if (entry.section !== lastSection) {
346
+ if (lastSection !== null) lines.push("");
347
+ lines.push(` /* ${humanizeSection(entry.section)} */`);
348
+ lastSection = entry.section;
349
+ }
350
+ lines.push(` ${entry.variable}: ${entry.value};`);
351
+ }
352
+ return lines.join("\n");
353
+ }
354
+
355
+ function humanizeSection(section: CompiledThemeEntry["section"]): string {
356
+ switch (section) {
357
+ case "color-palette":
358
+ return "Colors";
359
+ case "typography":
360
+ return "Typography";
361
+ case "layout":
362
+ return "Spacing";
363
+ case "shadows":
364
+ return "Shadows";
365
+ }
366
+ }
367
+
368
+ function renderMarkeredBlock(themeBody: string): string {
369
+ if (themeBody.trim().length === 0) {
370
+ // Even an empty body keeps the markers — re-running sync after
371
+ // emptying DESIGN.md should remove old vars, not orphan them.
372
+ return `${THEME_MARKER_START}\n@theme {\n}\n${THEME_MARKER_END}`;
373
+ }
374
+ return `${THEME_MARKER_START}\n@theme {\n${themeBody}\n}\n${THEME_MARKER_END}`;
375
+ }
376
+
377
+ /**
378
+ * Insert a fresh markered block. Prefer to nest it inside an existing
379
+ * `@theme` block when one exists; otherwise prepend.
380
+ */
381
+ function insertMarkeredBlock(css: string, block: string): string {
382
+ // Try to find the END of the first `@theme { ... }` block.
383
+ const themeStart = /@theme\s*\{/.exec(css);
384
+ if (themeStart) {
385
+ let depth = 0;
386
+ let i = themeStart.index;
387
+ for (; i < css.length; i++) {
388
+ const ch = css[i];
389
+ if (ch === "{") depth++;
390
+ else if (ch === "}") {
391
+ depth--;
392
+ if (depth === 0) break;
393
+ }
394
+ }
395
+ if (i < css.length) {
396
+ // Insert just before the closing `}` of the existing @theme block,
397
+ // unwrapping our generated block (which contains its own @theme).
398
+ // The cleanest move: replace the whole existing @theme block with
399
+ // a concatenation of "user's content" + generated body. But that
400
+ // risks re-ordering. So instead, append the generated block AFTER
401
+ // the existing one — Tailwind merges multiple @theme blocks at
402
+ // build time.
403
+ const before = css.slice(0, i + 1);
404
+ const after = css.slice(i + 1);
405
+ return `${before}\n\n${block}\n${after}`;
406
+ }
407
+ }
408
+ // No existing @theme → prepend.
409
+ return `${block}\n\n${css}`.replace(/\n{3,}/g, "\n\n");
410
+ }
411
+
412
+ function detectMergeConflicts(
413
+ existingCss: string,
414
+ compiled: CompiledTheme,
415
+ ): ThemeMergeConflict[] {
416
+ // Strip the markered region — anything inside is owned by Mandu and
417
+ // can't conflict with itself.
418
+ const outside = stripMarkeredBlock(existingCss);
419
+ const conflicts: ThemeMergeConflict[] = [];
420
+ for (const entry of compiled.entries) {
421
+ const re = new RegExp(
422
+ `${escapeRegex(entry.variable)}\\s*:\\s*([^;\\n]+);`,
423
+ "m",
424
+ );
425
+ const m = re.exec(outside);
426
+ if (!m) continue;
427
+ const fromCss = m[1]!.trim();
428
+ if (fromCss !== entry.value.trim()) {
429
+ conflicts.push({
430
+ variable: entry.variable,
431
+ fromDesign: entry.value,
432
+ fromCss,
433
+ });
434
+ }
435
+ }
436
+ return conflicts;
437
+ }
438
+
439
+ function escapeRegex(s: string): string {
440
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
441
+ }
@@ -31,6 +31,10 @@ import {
31
31
  type ExecuteOptions,
32
32
  } from "../runtime/lifecycle";
33
33
  import type { SlotMetadata, SlotConstraints } from "../guard/semantic-slots";
34
+ import {
35
+ DeployIntentInput,
36
+ type DeployIntentInput as DeployIntentInputType,
37
+ } from "../deploy/intent";
34
38
 
35
39
  /** Handler function type */
36
40
  export type Handler = (ctx: ManduContext) => Response | Promise<Response>;
@@ -112,6 +116,19 @@ interface FillingConfig<TLoaderData = unknown> {
112
116
  middleware: MiddlewareEntry[];
113
117
  /** Semantic slot metadata */
114
118
  semantic: SlotMetadata;
119
+ /**
120
+ * Issue #250 M5 — explicit deploy intent override. When present,
121
+ * `mandu deploy:plan` records this entry as `source: "explicit"`,
122
+ * which the planner never overwrites via inference. The shape is
123
+ * the partial-input form so users can declare just the fields they
124
+ * care about (typically `runtime` + maybe `regions`).
125
+ *
126
+ * Use this to escape-hatch the heuristic / brain when you know
127
+ * better than they do — e.g. an API route that imports a DB driver
128
+ * but is actually called from a build-only script and you want it
129
+ * to ship as `static`.
130
+ */
131
+ deploy?: DeployIntentInputType;
115
132
  }
116
133
 
117
134
  export class ManduFilling<TLoaderData = unknown> {
@@ -201,6 +218,49 @@ export class ManduFilling<TLoaderData = unknown> {
201
218
  return { ...this.config.semantic };
202
219
  }
203
220
 
221
+ /**
222
+ * Deploy intent override — pin the runtime / cache / regions for this
223
+ * route so `mandu deploy:plan` never overrides it via inference.
224
+ *
225
+ * Issue #250 M5. The shape mirrors the cache schema's partial-input
226
+ * form: declare only the fields you care about; the rest fall to
227
+ * the heuristic / brain. The `deploy:plan` command records the
228
+ * entry as `source: "explicit"` and protects it from re-inference.
229
+ *
230
+ * @example Pin an API route to bun + Seoul region:
231
+ * ```typescript
232
+ * Mandu.filling()
233
+ * .deploy({ runtime: "bun", regions: ["icn1"] })
234
+ * .post(async (ctx) => { ... });
235
+ * ```
236
+ *
237
+ * @example Force a dynamic page to render statically (only valid when
238
+ * `generateStaticParams` covers every parameter set):
239
+ * ```typescript
240
+ * Mandu.filling()
241
+ * .deploy({ runtime: "static" })
242
+ * .loader(async () => ({ ... }));
243
+ * ```
244
+ *
245
+ * The intent is validated immediately so a typo (`runtime: "lambdda"`)
246
+ * fails at module load instead of silently shipping the wrong shape.
247
+ */
248
+ deploy(intent: DeployIntentInputType): this {
249
+ this.config.deploy = DeployIntentInput.parse(intent);
250
+ return this;
251
+ }
252
+
253
+ /**
254
+ * Read the explicit deploy intent for this route, if any.
255
+ *
256
+ * Returns `undefined` when the user did not call `.deploy()`. The
257
+ * build-time extractor consults this to decide whether to mark the
258
+ * cache entry as `source: "explicit"` or pass through to inference.
259
+ */
260
+ getDeployIntent(): DeployIntentInputType | undefined {
261
+ return this.config.deploy;
262
+ }
263
+
204
264
  /**
205
265
  * SSR 데이터 로더 등록
206
266
  *