@caelo-cms/shared 0.10.23 → 0.10.24

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.
Files changed (59) hide show
  1. package/dist/ai-tools.d.ts +0 -60
  2. package/dist/ai-tools.d.ts.map +1 -1
  3. package/dist/ai-tools.js +1 -59
  4. package/dist/ai-tools.js.map +1 -1
  5. package/dist/base-css.d.ts +11 -0
  6. package/dist/base-css.d.ts.map +1 -1
  7. package/dist/base-css.js +13 -1
  8. package/dist/base-css.js.map +1 -1
  9. package/dist/design-draft-shell.d.ts +21 -0
  10. package/dist/design-draft-shell.d.ts.map +1 -0
  11. package/dist/design-draft-shell.js +81 -0
  12. package/dist/design-draft-shell.js.map +1 -0
  13. package/dist/genesis.d.ts +43 -3
  14. package/dist/genesis.d.ts.map +1 -1
  15. package/dist/genesis.js +72 -5
  16. package/dist/genesis.js.map +1 -1
  17. package/dist/i18n.d.ts +0 -50
  18. package/dist/i18n.d.ts.map +1 -1
  19. package/dist/i18n.js +8 -149
  20. package/dist/i18n.js.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/preview-compose.d.ts +9 -15
  26. package/dist/preview-compose.d.ts.map +1 -1
  27. package/dist/preview-compose.js +3 -43
  28. package/dist/preview-compose.js.map +1 -1
  29. package/dist/seo.d.ts +8 -21
  30. package/dist/seo.d.ts.map +1 -1
  31. package/dist/seo.js +4 -22
  32. package/dist/seo.js.map +1 -1
  33. package/dist/structured-sets.d.ts +0 -36
  34. package/dist/structured-sets.d.ts.map +1 -1
  35. package/dist/structured-sets.js +1 -52
  36. package/dist/structured-sets.js.map +1 -1
  37. package/dist/version.d.ts +2 -2
  38. package/dist/version.js +1 -1
  39. package/package.json +2 -2
  40. package/src/ai-tools.ts +1 -75
  41. package/src/base-css.ts +13 -1
  42. package/src/design-draft-shell.test.ts +85 -0
  43. package/src/design-draft-shell.ts +109 -0
  44. package/src/genesis.ts +76 -5
  45. package/src/i18n.test.ts +1 -217
  46. package/src/i18n.ts +8 -186
  47. package/src/index.ts +1 -1
  48. package/src/preview-compose.test.ts +35 -0
  49. package/src/preview-compose.ts +3 -56
  50. package/src/seo.test.ts +0 -40
  51. package/src/seo.ts +8 -36
  52. package/src/structured-sets.ts +1 -67
  53. package/src/version.ts +1 -1
  54. package/dist/translation.d.ts +0 -127
  55. package/dist/translation.d.ts.map +0 -1
  56. package/dist/translation.js +0 -208
  57. package/dist/translation.js.map +0 -1
  58. package/src/translation.test.ts +0 -160
  59. package/src/translation.ts +0 -295
@@ -1,208 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
- /**
3
- * P10 — translation primitives shared between the AI prompt builder,
4
- * the Mode 1 / Mode 2 op handlers, and the dashboard.
5
- *
6
- * computeBlockDiff(source, variant) — block-level diff per
7
- * CMS_REQUIREMENTS §7.6: matches modules by (block_name, position),
8
- * returns typed `changed` / `added` / `removed` operations. Pure
9
- * function; the AI receives this as Mode 2 prompt context.
10
- *
11
- * buildModeOnePrompt(...) / buildModeTwoPrompt(...) — assemble the
12
- * §7.6 sample-payload shapes with glossary + style guide injected.
13
- * Returns the prompt + a structured payload for unit-tests to
14
- * assert against.
15
- */
16
- import { z } from "zod";
17
- /**
18
- * Diff a source page's modules against a variant's modules. Match by
19
- * (blockName, position) — the §7.5 contract is that translations
20
- * share STRUCTURE with the source (block + position alignment) and
21
- * differ only in CONTENT (html / alt / caption per locale). Anything
22
- * mis-aligned is `added` (source has it, variant doesn't) or
23
- * `removed` (variant has it, source doesn't).
24
- *
25
- * `changed` rows contain BOTH before + after so the AI prompt can
26
- * show the structured diff per the §7.6 sample payload.
27
- */
28
- export function computeBlockDiff(source, variant) {
29
- const ops = [];
30
- const variantBy = new Map();
31
- for (const v of variant)
32
- variantBy.set(`${v.blockName}|${v.position}`, v);
33
- const sourceBy = new Map();
34
- for (const s of source)
35
- sourceBy.set(`${s.blockName}|${s.position}`, s);
36
- for (const s of source) {
37
- const key = `${s.blockName}|${s.position}`;
38
- const v = variantBy.get(key);
39
- if (!v) {
40
- ops.push({ kind: "added", blockName: s.blockName, position: s.position, module: s });
41
- continue;
42
- }
43
- if (s.html !== v.html || s.altText !== v.altText || s.caption !== v.caption) {
44
- ops.push({
45
- kind: "changed",
46
- blockName: s.blockName,
47
- position: s.position,
48
- moduleId: v.moduleId,
49
- before: v,
50
- after: s,
51
- });
52
- }
53
- }
54
- for (const v of variant) {
55
- const key = `${v.blockName}|${v.position}`;
56
- if (!sourceBy.has(key)) {
57
- ops.push({ kind: "removed", blockName: v.blockName, position: v.position, module: v });
58
- }
59
- }
60
- return ops;
61
- }
62
- /**
63
- * The AI returns this shape for both Mode 1 and Mode 2: one entry per
64
- * source module slot, with the translated content fields. The handler
65
- * matches entries back to the variant page's module rows by
66
- * (blockName, position).
67
- *
68
- * Mode 1 returns one entry per source module.
69
- * Mode 2 returns entries ONLY for changed blocks (preserves prior
70
- * translation on unchanged ones).
71
- */
72
- export const translationResultModule = z
73
- .object({
74
- blockName: z.string().min(1),
75
- position: z.number().int().min(0),
76
- /** Translated module HTML body. */
77
- html: z.string(),
78
- altText: z.string().nullable().optional(),
79
- caption: z.string().nullable().optional(),
80
- })
81
- .strict();
82
- export const translationResultPayload = z
83
- .object({
84
- modules: z.array(translationResultModule),
85
- })
86
- .strict();
87
- function renderGlossaryBlock(glossary) {
88
- if (glossary.length === 0)
89
- return "";
90
- const lines = glossary.map((g) => g.context
91
- ? `- "${g.sourceTerm}" → "${g.translation}" (${g.context})`
92
- : `- "${g.sourceTerm}" → "${g.translation}"`);
93
- return ["", "## Glossary (use these exact translations)", ...lines].join("\n");
94
- }
95
- function renderStyleGuideBlock(styleGuide) {
96
- if (!styleGuide || styleGuide.trim().length === 0)
97
- return "";
98
- return ["", "## Style guide", styleGuide.trim()].join("\n");
99
- }
100
- function renderSourceModulesBlock(modules) {
101
- const rendered = modules.map((m) => {
102
- const parts = [
103
- `### Module ${m.moduleSlug} (block=${m.blockName}, position=${m.position})`,
104
- "HTML:",
105
- "```html",
106
- m.html,
107
- "```",
108
- ];
109
- if (m.altText !== null)
110
- parts.push(`alt: ${m.altText}`);
111
- if (m.caption !== null)
112
- parts.push(`caption: ${m.caption}`);
113
- return parts.join("\n");
114
- });
115
- return rendered.join("\n\n");
116
- }
117
- export function buildModeOnePrompt(input) {
118
- const targetLabel = input.targetLocaleDisplayName ?? input.targetLocale;
119
- const system = [
120
- "You are translating a web page from one locale to another.",
121
- `Source locale: ${input.sourceLocale}.`,
122
- `Target locale: ${input.targetLocale} (${targetLabel}).`,
123
- "",
124
- "STRUCTURAL LOCK — the page's module layout (block names + positions) is identical across locales. You may NOT add, remove, or reorder modules. Translate ONLY the content fields (html, alt, caption) of each existing module.",
125
- "",
126
- "Translate every module listed below into the target locale. Preserve every HTML tag, attribute, class, id, href, and inline style verbatim — only the human-readable text inside tags + the alt/caption fields are translated. Numbers, code samples, and untranslatable proper nouns stay as-is.",
127
- "",
128
- 'Respond with a JSON object matching: {"modules": [{"blockName": str, "position": int, "html": str, "altText": str|null, "caption": str|null}, ...]}. Return ONE entry per source module — same blockName + position.',
129
- renderGlossaryBlock(input.glossary),
130
- renderStyleGuideBlock(input.styleGuide),
131
- ]
132
- .filter((s) => s.length > 0)
133
- .join("\n");
134
- const user = [
135
- `# Source page modules (${input.sourceLocale} → ${input.targetLocale})`,
136
- "",
137
- renderSourceModulesBlock(input.sourceModules),
138
- ].join("\n");
139
- return { system, user };
140
- }
141
- export function buildModeTwoPrompt(input) {
142
- const targetLabel = input.targetLocaleDisplayName ?? input.targetLocale;
143
- const changed = input.diff.filter((d) => d.kind === "changed");
144
- const added = input.diff.filter((d) => d.kind === "added");
145
- const removed = input.diff.filter((d) => d.kind === "removed");
146
- const system = [
147
- "You are updating an existing translation of a web page after the source changed.",
148
- `Source locale: ${input.sourceLocale}.`,
149
- `Target locale: ${input.targetLocale} (${targetLabel}).`,
150
- "",
151
- "STRUCTURAL LOCK — the page's module layout (block names + positions) is identical across locales. You may NOT add, remove, or reorder modules. Translate ONLY the content fields (html, alt, caption) that have CHANGED on the source. Preserve the existing translation verbatim for unchanged modules.",
152
- "",
153
- "Numbers, code samples, and untranslatable proper nouns stay as-is. Preserve every HTML tag/attribute/class/id/href/inline style in the source verbatim.",
154
- "",
155
- 'Respond with a JSON object matching: {"modules": [{"blockName": str, "position": int, "html": str, "altText": str|null, "caption": str|null}, ...]}. Return ONE entry per CHANGED module — do NOT include unchanged modules in the response.',
156
- renderGlossaryBlock(input.glossary),
157
- renderStyleGuideBlock(input.styleGuide),
158
- ]
159
- .filter((s) => s.length > 0)
160
- .join("\n");
161
- const userLines = [
162
- `# Update translation: ${input.sourceLocale} → ${input.targetLocale}`,
163
- "",
164
- "## Current source (full, for context)",
165
- "",
166
- renderSourceModulesBlock(input.sourceModules),
167
- "",
168
- "## Existing translation (preserve unchanged modules verbatim)",
169
- "",
170
- renderSourceModulesBlock(input.variantModules),
171
- "",
172
- "## Structured diff",
173
- ];
174
- if (changed.length === 0 && added.length === 0 && removed.length === 0) {
175
- userLines.push("(no changes detected — return an empty `modules` array)");
176
- }
177
- for (const c of changed) {
178
- if (c.kind !== "changed")
179
- continue;
180
- userLines.push("");
181
- userLines.push(`### CHANGED — block=${c.blockName} position=${c.position} module=${c.moduleId}`);
182
- userLines.push("Before (existing translation):");
183
- userLines.push("```html");
184
- userLines.push(c.before.html);
185
- userLines.push("```");
186
- userLines.push("Source after (current source HTML to re-translate):");
187
- userLines.push("```html");
188
- userLines.push(c.after.html);
189
- userLines.push("```");
190
- }
191
- for (const a of added) {
192
- if (a.kind !== "added")
193
- continue;
194
- userLines.push("");
195
- userLines.push(`### ADDED in source — block=${a.blockName} position=${a.position} (must translate)`);
196
- userLines.push("```html");
197
- userLines.push(a.module.html);
198
- userLines.push("```");
199
- }
200
- for (const r of removed) {
201
- if (r.kind !== "removed")
202
- continue;
203
- userLines.push("");
204
- userLines.push(`### REMOVED from source — block=${r.blockName} position=${r.position} (drop from the translation)`);
205
- }
206
- return { system, user: userLines.join("\n") };
207
- }
208
- //# sourceMappingURL=translation.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"translation.js","sourceRoot":"","sources":["../src/translation.ts"],"names":[],"mappings":"AAAA,mCAAmC;AAEnC;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA+BxB;;;;;;;;;;GAUG;AACH,MAAM,UAAU,gBAAgB,CAC9B,MAAkC,EAClC,OAAmC;IAEnC,MAAM,GAAG,GAAkB,EAAE,CAAC;IAC9B,MAAM,SAAS,GAAG,IAAI,GAAG,EAA2B,CAAC;IACrD,KAAK,MAAM,CAAC,IAAI,OAAO;QAAE,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC;IAC1E,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA2B,CAAC;IACpD,KAAK,MAAM,CAAC,IAAI,MAAM;QAAE,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC;IAExE,KAAK,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;QACvB,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC3C,MAAM,CAAC,GAAG,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC7B,IAAI,CAAC,CAAC,EAAE,CAAC;YACP,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;YACrF,SAAS;QACX,CAAC;QACD,IAAI,C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CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC9B,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACxB,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,IAAI,CAAC,CAAC,IAAI,KAAK,SAAS;YAAE,SAAS;QACnC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACnB,SAAS,CAAC,IAAI,CACZ,mCAAmC,CAAC,CAAC,SAAS,aAAa,CAAC,CAAC,QAAQ,8BAA8B,CACpG,CAAC;IACJ,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAChD,CAAC"}
@@ -1,160 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- import { describe, expect, it } from "bun:test";
4
- import {
5
- buildModeOnePrompt,
6
- buildModeTwoPrompt,
7
- computeBlockDiff,
8
- type GlossaryEntry,
9
- type ModuleBlockSlot,
10
- translationResultPayload,
11
- } from "./translation.js";
12
-
13
- const SLOT = (overrides: Partial<ModuleBlockSlot> = {}): ModuleBlockSlot => ({
14
- blockName: "content",
15
- position: 0,
16
- moduleId: "11111111-1111-4111-8111-111111111111",
17
- moduleSlug: "hero",
18
- html: "<h1>Welcome</h1>",
19
- altText: null,
20
- caption: null,
21
- ...overrides,
22
- });
23
-
24
- describe("computeBlockDiff", () => {
25
- it("returns empty when source and variant align", () => {
26
- const slot = SLOT();
27
- expect(computeBlockDiff([slot], [slot])).toEqual([]);
28
- });
29
-
30
- it("emits changed when html differs", () => {
31
- const source = SLOT({ html: "<h1>Welcome — updated</h1>" });
32
- const variant = SLOT({ html: "<h1>Willkommen</h1>" });
33
- const ops = computeBlockDiff([source], [variant]);
34
- expect(ops.length).toBe(1);
35
- const [op] = ops;
36
- if (op?.kind !== "changed") throw new Error("expected changed");
37
- expect(op.before.html).toBe("<h1>Willkommen</h1>");
38
- expect(op.after.html).toBe("<h1>Welcome — updated</h1>");
39
- });
40
-
41
- it("emits added when source has a slot variant lacks", () => {
42
- const source = [SLOT({ position: 0 }), SLOT({ position: 1, html: "<p>New</p>" })];
43
- const variant = [SLOT({ position: 0 })];
44
- const ops = computeBlockDiff(source, variant);
45
- expect(ops.length).toBe(1);
46
- expect(ops[0]?.kind).toBe("added");
47
- });
48
-
49
- it("emits removed when variant has a slot source lacks", () => {
50
- const source = [SLOT({ position: 0 })];
51
- const variant = [SLOT({ position: 0 }), SLOT({ position: 1, html: "<p>Stale</p>" })];
52
- const ops = computeBlockDiff(source, variant);
53
- expect(ops.length).toBe(1);
54
- expect(ops[0]?.kind).toBe("removed");
55
- });
56
-
57
- it("matches by (blockName, position) — same blockName different position is added/removed", () => {
58
- const source = [SLOT({ position: 0 })];
59
- const variant = [SLOT({ position: 1 })];
60
- const ops = computeBlockDiff(source, variant);
61
- expect(ops.length).toBe(2);
62
- expect(ops.map((o) => o.kind).sort()).toEqual(["added", "removed"]);
63
- });
64
-
65
- it("alt/caption changes count as changed", () => {
66
- const source = SLOT({ altText: "A cat" });
67
- const variant = SLOT({ altText: "Eine Katze" });
68
- const ops = computeBlockDiff([source], [variant]);
69
- expect(ops[0]?.kind).toBe("changed");
70
- });
71
- });
72
-
73
- const GLOSSARY: GlossaryEntry[] = [
74
- { sourceTerm: "Caelo", translation: "Caelo", context: "brand name — never translate" },
75
- { sourceTerm: "CMS", translation: "CMS", context: null },
76
- ];
77
-
78
- describe("buildModeOnePrompt", () => {
79
- it("includes locale codes, structural lock, glossary, style guide", () => {
80
- const { system, user } = buildModeOnePrompt({
81
- sourceLocale: "en",
82
- targetLocale: "de-AT",
83
- targetLocaleDisplayName: "German (Austria)",
84
- sourceModules: [SLOT()],
85
- glossary: GLOSSARY,
86
- styleGuide: "Use Sie form (formal).",
87
- });
88
- expect(system).toContain("Source locale: en");
89
- expect(system).toContain("Target locale: de-AT (German (Austria))");
90
- expect(system).toContain("STRUCTURAL LOCK");
91
- expect(system).toContain("Caelo");
92
- expect(system).toContain("Use Sie form");
93
- expect(user).toContain("Welcome");
94
- });
95
-
96
- it("omits empty glossary block", () => {
97
- const { system } = buildModeOnePrompt({
98
- sourceLocale: "en",
99
- targetLocale: "de",
100
- sourceModules: [SLOT()],
101
- glossary: [],
102
- styleGuide: null,
103
- });
104
- expect(system).not.toContain("## Glossary");
105
- expect(system).not.toContain("## Style guide");
106
- });
107
- });
108
-
109
- describe("buildModeTwoPrompt", () => {
110
- it("renders structured diff with before/after for changed blocks", () => {
111
- const source = SLOT({ html: "<h1>Welcome — Spring sale</h1>" });
112
- const variant = SLOT({ html: "<h1>Willkommen</h1>" });
113
- const diff = computeBlockDiff([source], [variant]);
114
- const { system, user } = buildModeTwoPrompt({
115
- sourceLocale: "en",
116
- targetLocale: "de",
117
- sourceModules: [source],
118
- variantModules: [variant],
119
- diff,
120
- glossary: [],
121
- styleGuide: null,
122
- });
123
- expect(system).toContain("STRUCTURAL LOCK");
124
- expect(system).toContain("Return ONE entry per CHANGED module");
125
- expect(user).toContain("Existing translation");
126
- expect(user).toContain("Willkommen"); // before
127
- expect(user).toContain("Spring sale"); // after
128
- expect(user).toContain("CHANGED");
129
- });
130
-
131
- it("renders empty diff hint when no ops", () => {
132
- const slot = SLOT();
133
- const { user } = buildModeTwoPrompt({
134
- sourceLocale: "en",
135
- targetLocale: "de",
136
- sourceModules: [slot],
137
- variantModules: [slot],
138
- diff: [],
139
- glossary: [],
140
- styleGuide: null,
141
- });
142
- expect(user).toContain("no changes detected");
143
- });
144
- });
145
-
146
- describe("translationResultPayload", () => {
147
- it("accepts the expected AI output shape", () => {
148
- const ok = translationResultPayload.safeParse({
149
- modules: [{ blockName: "content", position: 0, html: "<h1>Willkommen</h1>", altText: null }],
150
- });
151
- expect(ok.success).toBe(true);
152
- });
153
-
154
- it("rejects unknown fields (.strict)", () => {
155
- const bad = translationResultPayload.safeParse({
156
- modules: [{ blockName: "content", position: 0, html: "<h1>x</h1>", extra: 1 }],
157
- });
158
- expect(bad.success).toBe(false);
159
- });
160
- });
@@ -1,295 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- /**
4
- * P10 — translation primitives shared between the AI prompt builder,
5
- * the Mode 1 / Mode 2 op handlers, and the dashboard.
6
- *
7
- * computeBlockDiff(source, variant) — block-level diff per
8
- * CMS_REQUIREMENTS §7.6: matches modules by (block_name, position),
9
- * returns typed `changed` / `added` / `removed` operations. Pure
10
- * function; the AI receives this as Mode 2 prompt context.
11
- *
12
- * buildModeOnePrompt(...) / buildModeTwoPrompt(...) — assemble the
13
- * §7.6 sample-payload shapes with glossary + style guide injected.
14
- * Returns the prompt + a structured payload for unit-tests to
15
- * assert against.
16
- */
17
-
18
- import { z } from "zod";
19
-
20
- export interface ModuleBlockSlot {
21
- /** The block (e.g. "content", "header") this module sits in. */
22
- blockName: string;
23
- /** Position within the block. Blocks are ordered + 0-based. */
24
- position: number;
25
- /** Module id — locked across locales (translations share refs). */
26
- moduleId: string;
27
- /** Display name shown to the AI for context. */
28
- moduleSlug: string;
29
- /** The translatable fields of the module. P10 supports HTML body
30
- * and three SEO-style metadata fields. Extend as new typed fields
31
- * land (e.g. structured-content blocks in P12A). */
32
- html: string;
33
- altText: string | null;
34
- caption: string | null;
35
- }
36
-
37
- export type BlockDiffOp =
38
- | {
39
- kind: "changed";
40
- blockName: string;
41
- position: number;
42
- moduleId: string;
43
- before: ModuleBlockSlot;
44
- after: ModuleBlockSlot;
45
- }
46
- | { kind: "added"; blockName: string; position: number; module: ModuleBlockSlot }
47
- | { kind: "removed"; blockName: string; position: number; module: ModuleBlockSlot };
48
-
49
- /**
50
- * Diff a source page's modules against a variant's modules. Match by
51
- * (blockName, position) — the §7.5 contract is that translations
52
- * share STRUCTURE with the source (block + position alignment) and
53
- * differ only in CONTENT (html / alt / caption per locale). Anything
54
- * mis-aligned is `added` (source has it, variant doesn't) or
55
- * `removed` (variant has it, source doesn't).
56
- *
57
- * `changed` rows contain BOTH before + after so the AI prompt can
58
- * show the structured diff per the §7.6 sample payload.
59
- */
60
- export function computeBlockDiff(
61
- source: readonly ModuleBlockSlot[],
62
- variant: readonly ModuleBlockSlot[],
63
- ): BlockDiffOp[] {
64
- const ops: BlockDiffOp[] = [];
65
- const variantBy = new Map<string, ModuleBlockSlot>();
66
- for (const v of variant) variantBy.set(`${v.blockName}|${v.position}`, v);
67
- const sourceBy = new Map<string, ModuleBlockSlot>();
68
- for (const s of source) sourceBy.set(`${s.blockName}|${s.position}`, s);
69
-
70
- for (const s of source) {
71
- const key = `${s.blockName}|${s.position}`;
72
- const v = variantBy.get(key);
73
- if (!v) {
74
- ops.push({ kind: "added", blockName: s.blockName, position: s.position, module: s });
75
- continue;
76
- }
77
- if (s.html !== v.html || s.altText !== v.altText || s.caption !== v.caption) {
78
- ops.push({
79
- kind: "changed",
80
- blockName: s.blockName,
81
- position: s.position,
82
- moduleId: v.moduleId,
83
- before: v,
84
- after: s,
85
- });
86
- }
87
- }
88
- for (const v of variant) {
89
- const key = `${v.blockName}|${v.position}`;
90
- if (!sourceBy.has(key)) {
91
- ops.push({ kind: "removed", blockName: v.blockName, position: v.position, module: v });
92
- }
93
- }
94
- return ops;
95
- }
96
-
97
- // ---------------------------------------------------------------------
98
- // Prompt builders
99
- // ---------------------------------------------------------------------
100
-
101
- export interface GlossaryEntry {
102
- sourceTerm: string;
103
- translation: string;
104
- context: string | null;
105
- }
106
-
107
- export interface ModeOnePromptInput {
108
- /** Source-locale code (e.g. 'en'). */
109
- sourceLocale: string;
110
- /** Target locale code (e.g. 'de-AT'). */
111
- targetLocale: string;
112
- /** Optional locale displayName for context (e.g. "German (Austria)"). */
113
- targetLocaleDisplayName?: string;
114
- /** Source-page modules. The AI translates each per (blockName, position). */
115
- sourceModules: readonly ModuleBlockSlot[];
116
- glossary: readonly GlossaryEntry[];
117
- styleGuide: string | null;
118
- }
119
-
120
- export interface ModeTwoPromptInput {
121
- sourceLocale: string;
122
- targetLocale: string;
123
- targetLocaleDisplayName?: string;
124
- sourceModules: readonly ModuleBlockSlot[];
125
- /** The CURRENT variant — passed in full so the AI keeps the prior
126
- * translation quality on unchanged blocks. */
127
- variantModules: readonly ModuleBlockSlot[];
128
- /** Pre-computed diff (call computeBlockDiff first). */
129
- diff: readonly BlockDiffOp[];
130
- glossary: readonly GlossaryEntry[];
131
- styleGuide: string | null;
132
- }
133
-
134
- /**
135
- * The AI returns this shape for both Mode 1 and Mode 2: one entry per
136
- * source module slot, with the translated content fields. The handler
137
- * matches entries back to the variant page's module rows by
138
- * (blockName, position).
139
- *
140
- * Mode 1 returns one entry per source module.
141
- * Mode 2 returns entries ONLY for changed blocks (preserves prior
142
- * translation on unchanged ones).
143
- */
144
- export const translationResultModule = z
145
- .object({
146
- blockName: z.string().min(1),
147
- position: z.number().int().min(0),
148
- /** Translated module HTML body. */
149
- html: z.string(),
150
- altText: z.string().nullable().optional(),
151
- caption: z.string().nullable().optional(),
152
- })
153
- .strict();
154
-
155
- export const translationResultPayload = z
156
- .object({
157
- modules: z.array(translationResultModule),
158
- })
159
- .strict();
160
- export type TranslationResultPayload = z.infer<typeof translationResultPayload>;
161
-
162
- function renderGlossaryBlock(glossary: readonly GlossaryEntry[]): string {
163
- if (glossary.length === 0) return "";
164
- const lines = glossary.map((g) =>
165
- g.context
166
- ? `- "${g.sourceTerm}" → "${g.translation}" (${g.context})`
167
- : `- "${g.sourceTerm}" → "${g.translation}"`,
168
- );
169
- return ["", "## Glossary (use these exact translations)", ...lines].join("\n");
170
- }
171
-
172
- function renderStyleGuideBlock(styleGuide: string | null): string {
173
- if (!styleGuide || styleGuide.trim().length === 0) return "";
174
- return ["", "## Style guide", styleGuide.trim()].join("\n");
175
- }
176
-
177
- function renderSourceModulesBlock(modules: readonly ModuleBlockSlot[]): string {
178
- const rendered = modules.map((m) => {
179
- const parts = [
180
- `### Module ${m.moduleSlug} (block=${m.blockName}, position=${m.position})`,
181
- "HTML:",
182
- "```html",
183
- m.html,
184
- "```",
185
- ];
186
- if (m.altText !== null) parts.push(`alt: ${m.altText}`);
187
- if (m.caption !== null) parts.push(`caption: ${m.caption}`);
188
- return parts.join("\n");
189
- });
190
- return rendered.join("\n\n");
191
- }
192
-
193
- export function buildModeOnePrompt(input: ModeOnePromptInput): {
194
- system: string;
195
- user: string;
196
- } {
197
- const targetLabel = input.targetLocaleDisplayName ?? input.targetLocale;
198
- const system = [
199
- "You are translating a web page from one locale to another.",
200
- `Source locale: ${input.sourceLocale}.`,
201
- `Target locale: ${input.targetLocale} (${targetLabel}).`,
202
- "",
203
- "STRUCTURAL LOCK — the page's module layout (block names + positions) is identical across locales. You may NOT add, remove, or reorder modules. Translate ONLY the content fields (html, alt, caption) of each existing module.",
204
- "",
205
- "Translate every module listed below into the target locale. Preserve every HTML tag, attribute, class, id, href, and inline style verbatim — only the human-readable text inside tags + the alt/caption fields are translated. Numbers, code samples, and untranslatable proper nouns stay as-is.",
206
- "",
207
- 'Respond with a JSON object matching: {"modules": [{"blockName": str, "position": int, "html": str, "altText": str|null, "caption": str|null}, ...]}. Return ONE entry per source module — same blockName + position.',
208
- renderGlossaryBlock(input.glossary),
209
- renderStyleGuideBlock(input.styleGuide),
210
- ]
211
- .filter((s) => s.length > 0)
212
- .join("\n");
213
- const user = [
214
- `# Source page modules (${input.sourceLocale} → ${input.targetLocale})`,
215
- "",
216
- renderSourceModulesBlock(input.sourceModules),
217
- ].join("\n");
218
- return { system, user };
219
- }
220
-
221
- export function buildModeTwoPrompt(input: ModeTwoPromptInput): {
222
- system: string;
223
- user: string;
224
- } {
225
- const targetLabel = input.targetLocaleDisplayName ?? input.targetLocale;
226
- const changed = input.diff.filter((d) => d.kind === "changed");
227
- const added = input.diff.filter((d) => d.kind === "added");
228
- const removed = input.diff.filter((d) => d.kind === "removed");
229
-
230
- const system = [
231
- "You are updating an existing translation of a web page after the source changed.",
232
- `Source locale: ${input.sourceLocale}.`,
233
- `Target locale: ${input.targetLocale} (${targetLabel}).`,
234
- "",
235
- "STRUCTURAL LOCK — the page's module layout (block names + positions) is identical across locales. You may NOT add, remove, or reorder modules. Translate ONLY the content fields (html, alt, caption) that have CHANGED on the source. Preserve the existing translation verbatim for unchanged modules.",
236
- "",
237
- "Numbers, code samples, and untranslatable proper nouns stay as-is. Preserve every HTML tag/attribute/class/id/href/inline style in the source verbatim.",
238
- "",
239
- 'Respond with a JSON object matching: {"modules": [{"blockName": str, "position": int, "html": str, "altText": str|null, "caption": str|null}, ...]}. Return ONE entry per CHANGED module — do NOT include unchanged modules in the response.',
240
- renderGlossaryBlock(input.glossary),
241
- renderStyleGuideBlock(input.styleGuide),
242
- ]
243
- .filter((s) => s.length > 0)
244
- .join("\n");
245
-
246
- const userLines: string[] = [
247
- `# Update translation: ${input.sourceLocale} → ${input.targetLocale}`,
248
- "",
249
- "## Current source (full, for context)",
250
- "",
251
- renderSourceModulesBlock(input.sourceModules),
252
- "",
253
- "## Existing translation (preserve unchanged modules verbatim)",
254
- "",
255
- renderSourceModulesBlock(input.variantModules),
256
- "",
257
- "## Structured diff",
258
- ];
259
- if (changed.length === 0 && added.length === 0 && removed.length === 0) {
260
- userLines.push("(no changes detected — return an empty `modules` array)");
261
- }
262
- for (const c of changed) {
263
- if (c.kind !== "changed") continue;
264
- userLines.push("");
265
- userLines.push(
266
- `### CHANGED — block=${c.blockName} position=${c.position} module=${c.moduleId}`,
267
- );
268
- userLines.push("Before (existing translation):");
269
- userLines.push("```html");
270
- userLines.push(c.before.html);
271
- userLines.push("```");
272
- userLines.push("Source after (current source HTML to re-translate):");
273
- userLines.push("```html");
274
- userLines.push(c.after.html);
275
- userLines.push("```");
276
- }
277
- for (const a of added) {
278
- if (a.kind !== "added") continue;
279
- userLines.push("");
280
- userLines.push(
281
- `### ADDED in source — block=${a.blockName} position=${a.position} (must translate)`,
282
- );
283
- userLines.push("```html");
284
- userLines.push(a.module.html);
285
- userLines.push("```");
286
- }
287
- for (const r of removed) {
288
- if (r.kind !== "removed") continue;
289
- userLines.push("");
290
- userLines.push(
291
- `### REMOVED from source — block=${r.blockName} position=${r.position} (drop from the translation)`,
292
- );
293
- }
294
- return { system, user: userLines.join("\n") };
295
- }