`) so all
+ * sections stay uniform and controllable via site layout and design tokens.
+ */
+export const sectionLayoutTokensRule: ChaiDesignRule = {
+ id: "section-layout-tokens",
+ run: (graph, ctx) => {
+ if (ctx.isPartial) return [];
+ const required = SECTION_LAYOUT_TOKENS.filter((token) => !ctx.designTokens?.[token]?.archived);
+ if (required.length === 0) return [];
+
+ return graph.roots.flatMap((root) => {
+ if ((root.type !== "Box" && root.type !== "EmptyBox") || root.tag !== "section") return [];
+ const present = collectSubtreeTokens(graph, root);
+ const missing = required.filter((token) => !present.has(token));
+ if (missing.length === 0) return [];
+ return [
+ blockFinding(
+ "section-layout-tokens",
+ "warn",
+ root,
+ `Page section is missing layout design token(s): ${missing.join(", ")}.`,
+ "Put dt#content-gutter-y on the outer
and dt#site-content-width dt#content-gutter-x on its inner content wrapper (never hand-write section py-/px-/max-w- or prefix dt# tokens with breakpoints).",
+ ),
+ ];
+ });
+ },
+};
+
+export const STRUCTURE_RULES = [
+ sectionLayoutTokensRule,
+ nestedCardsRule,
+ repeatedSectionLayoutRule,
+ identicalEntranceAnimationRule,
+];
// Exported for the interaction rules, which share the notion of a painted surface.
export const paintsSurface = (utilities: string[]) =>
diff --git a/src/utils/design-checks/run-design-checks.test.ts b/src/utils/design-checks/run-design-checks.test.ts
index 43afad989..f02270610 100644
--- a/src/utils/design-checks/run-design-checks.test.ts
+++ b/src/utils/design-checks/run-design-checks.test.ts
@@ -15,15 +15,16 @@ describe("runDesignChecks", () => {
it("returns nothing for an empty page and a clean, themed section", () => {
expect(check([])).toEqual([]);
const clean = [
- b("s", "Box", { tag: "section", styles: S("bg-background py-24") }),
+ b("s", "Box", { tag: "section", styles: S("dt#content-gutter-y bg-background") }),
+ b("inner", "Box", { tag: "div", styles: S("dt#site-content-width dt#content-gutter-x") }, "s"),
b(
"h",
"Heading",
{ tag: "h1", content: "Bread, slowly", styles: S("font-heading text-5xl text-foreground") },
- "s",
+ "inner",
),
- b("p", "Paragraph", { content: "Baked overnight.", styles: S("max-w-prose text-muted-foreground") }, "s"),
- b("a", "Button", { content: "See the menu", styles: S("dt#btn dt#btn-primary") }, "s"),
+ b("p", "Paragraph", { content: "Baked overnight.", styles: S("max-w-prose text-muted-foreground") }, "inner"),
+ b("a", "Button", { content: "See the menu", styles: S("dt#btn dt#btn-primary") }, "inner"),
];
expect(check(clean)).toEqual([]);
});
@@ -400,6 +401,45 @@ describe("runDesignChecks", () => {
});
});
+ describe("section-layout-tokens", () => {
+ it("warns when a top-level page section omits site-content-width or content-gutter tokens", () => {
+ const findings = check([
+ b("s1", "Box", { tag: "section", styles: S("bg-background py-20") }),
+ b("inner1", "Box", { tag: "div", styles: S("mx-auto max-w-6xl px-6") }, "s1"),
+ ]);
+ expect(only(findings, "section-layout-tokens")).toMatchObject([
+ {
+ severity: "warn",
+ blockId: "s1",
+ message: expect.stringContaining("dt#site-content-width, dt#content-gutter-x, dt#content-gutter-y"),
+ },
+ ]);
+ });
+
+ it("passes when outer section uses dt#content-gutter-y and inner wrapper uses dt#site-content-width dt#content-gutter-x", () => {
+ const findings = check([
+ b("s1", "Box", { tag: "section", styles: S("dt#content-gutter-y bg-background") }),
+ b("inner1", "Box", { tag: "div", styles: S("dt#site-content-width dt#content-gutter-x") }, "s1"),
+ ]);
+ expect(only(findings, "section-layout-tokens")).toEqual([]);
+ });
+
+ it("skips partials and archived layout tokens", () => {
+ const bareSection = [b("s1", "Box", { tag: "section", styles: S("bg-background py-8") })];
+ expect(only(check(bareSection, { isPartial: true }), "section-layout-tokens")).toEqual([]);
+
+ const archivedFindings = check(
+ [b("s1", "Box", { tag: "section", styles: S("dt#site-content-width dt#content-gutter-x") })],
+ {
+ designTokens: {
+ "dt#content-gutter-y": { name: "Content-Gutter-Y", value: "py-8", archived: true },
+ },
+ },
+ );
+ expect(only(archivedFindings, "section-layout-tokens")).toEqual([]);
+ });
+ });
+
describe("ordering, filtering and formatting", () => {
const blocks = [
b("s", "Box", { styles: S("bg-blue-500") }),
diff --git a/src/utils/import-html/restore-block-prop-types.ts b/src/utils/import-html/restore-block-prop-types.ts
index 69550cb9c..8c0eb0141 100644
--- a/src/utils/import-html/restore-block-prop-types.ts
+++ b/src/utils/import-html/restore-block-prop-types.ts
@@ -64,7 +64,11 @@ function schemaAllowsNull(schema: SchemaNode | undefined): boolean {
return Array.isArray(schema?.enum) && schema!.enum.includes(null);
}
-export function restoreBlockPropTypes(blocks: ChaiBlock[]): ChaiBlock[] {
+export function restoreBlockPropTypes(
+ blocks: ChaiBlock[],
+ options: { htmlBooleanEmpty?: boolean } = {},
+): ChaiBlock[] {
+ const htmlBooleanEmpty = options.htmlBooleanEmpty ?? true;
return blocks.map((block) => {
const registered = getRegisteredChaiBlock(block._type) as
| { props?: { schema?: SchemaNode }; schema?: SchemaNode }
@@ -79,7 +83,12 @@ export function restoreBlockPropTypes(blocks: ChaiBlock[]): ChaiBlock[] {
for (const [key, propSchema] of Object.entries(properties)) {
const value = block[key];
if (typeof value !== "string") continue;
- const restored = coerceToSchemaType(coercibleType(propSchema), value, schemaAllowsNull(propSchema));
+ const restored = coerceToSchemaType(
+ coercibleType(propSchema),
+ value,
+ schemaAllowsNull(propSchema),
+ htmlBooleanEmpty,
+ );
if (restored === value) continue;
next = next ?? { ...block };
next[key] = restored;
@@ -89,7 +98,12 @@ export function restoreBlockPropTypes(blocks: ChaiBlock[]): ChaiBlock[] {
}
/** Parse a stringified value back to `type`; anything ambiguous is returned unchanged. */
-export function coerceToSchemaType(type: string | undefined, value: string, nullable = false): unknown {
+export function coerceToSchemaType(
+ type: string | undefined,
+ value: string,
+ nullable = false,
+ htmlBooleanEmpty = true,
+): unknown {
// Restore JSON null only when the schema actually admits null (a `null` type,
// a type union including null, or an enum including null). A stray "null" on a
// non-nullable prop stays a string rather than silently flipping behavior.
@@ -100,8 +114,8 @@ export function coerceToSchemaType(type: string | undefined, value: string, null
// (e.g. `{"href":"{{page.url}}"}`) still parses back to its typed value.
if (type === "boolean") {
// A valueless HTML boolean attribute (`required`, `multiple`) is imported as
- // "" (getSanitizedValue(null) -> ""); treat that as true.
- return value === "true" || value === "" ? true : value === "false" ? false : value;
+ // "" (getSanitizedValue(null) -> ""); treat that as true only for HTML input.
+ return value === "true" || (htmlBooleanEmpty && value === "") ? true : value === "false" ? false : value;
}
// Accepts exponent notation too — JSON.stringify emits e.g. 1e+21 / 1e-7.
if (type === "number") return /^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(value.trim()) ? Number(value) : value;
diff --git a/src/utils/page-lang.ts b/src/utils/page-lang.ts
new file mode 100644
index 000000000..4554a159d
--- /dev/null
+++ b/src/utils/page-lang.ts
@@ -0,0 +1,56 @@
+import { LANGUAGES } from "~/builder/pages/constants/LANGUAGES";
+
+/**
+ * Language facts about the page an AI or MCP tool is operating on.
+ *
+ * A ChaiBuilder site has one fallback language; page rows in that language
+ * store `lang: ''` and every other language is a separate row pointing at the
+ * primary page through `primaryPage`. Those language rows have no blocks of
+ * their own — they share the primary page's block tree, and per-language text
+ * lives on the same blocks under `-{lang}`-suffixed props (see
+ * `applyLanguage`).
+ */
+export type PageLangInfo = {
+ lang: string;
+ fallbackLang: string;
+ /** True when this page row is a language variant, not the primary-language page. */
+ isLanguageVariant: boolean;
+};
+
+type LangSource = { lang?: string | null; fallbackLang?: string | null };
+
+export const getPageLangInfo = (page: LangSource): PageLangInfo => {
+ const fallbackLang = page.fallbackLang || "";
+ const lang = page.lang || fallbackLang;
+ return {
+ lang,
+ fallbackLang,
+ isLanguageVariant: Boolean(lang && fallbackLang) && lang !== fallbackLang,
+ };
+};
+
+/** "French (fr)" when the code is known, otherwise the bare code. @internal */
+export const langLabel = (code: string): string => {
+ if (!code) return "unknown";
+ const name = LANGUAGES[code] ?? LANGUAGES[code.split("-")[0]];
+ return name ? `${name} (${code})` : code;
+};
+
+const VARIANT_NOTE =
+ "This page is a language variant: it shares one block tree with the primary-language page, so layout, structure and styling changes apply to every language. Its text is this language’s translation — the read tools show it and text edits here update only this language’s copy, leaving the primary-language text unchanged.";
+
+/** Human-readable language note appended to read-tool output. @internal */
+export const describePageLang = (info: PageLangInfo): string => {
+ if (!info.lang) return "";
+ const base = `Content language: ${langLabel(info.lang)}. Write all user-visible copy in this language.`;
+ if (!info.isLanguageVariant) return base;
+ return `${base} Site fallback language: ${langLabel(info.fallbackLang)}. ${VARIANT_NOTE}`;
+};
+
+/** Same facts as JSON fields, for the tools that answer with a JSON payload. */
+export const langResponseFields = (info: PageLangInfo) => ({
+ lang: info.lang,
+ fallbackLang: info.fallbackLang,
+ isLanguageVariant: info.isLanguageVariant,
+ languageNote: describePageLang(info),
+});
diff --git a/src/utils/page-seo.ts b/src/utils/page-seo.ts
new file mode 100644
index 000000000..15f488718
--- /dev/null
+++ b/src/utils/page-seo.ts
@@ -0,0 +1,315 @@
+import type { PageLangInfo } from "./page-lang";
+import { langLabel } from "./page-lang";
+
+/**
+ * Read/write helpers for the `app_pages.seo` jsonb column — shared by Builder AI
+ * and MCP `get_page_seo` / `update_page_seo` tools.
+ */
+
+export type SeoPatch = {
+ title?: string;
+ description?: string;
+ canonicalUrl?: string;
+ noIndex?: boolean;
+ noFollow?: boolean;
+ ogTitle?: string;
+ ogDescription?: string;
+ ogImage?: string;
+ metaOther?: Record;
+ /** null / {} / [] clears the document. */
+ jsonLD?: Record | unknown[] | null;
+};
+
+export type NormalizedSeo = {
+ seo: {
+ title: string;
+ description: string;
+ canonicalUrl: string;
+ noIndex: boolean;
+ noFollow: boolean;
+ };
+ metaTags: {
+ ogTitle: string;
+ ogDescription: string;
+ ogImage: string;
+ metaOther: Record;
+ };
+ jsonLD: Record | unknown[] | null;
+ jsonLDRaw?: string;
+ metaOtherRaw?: string;
+};
+
+type ParseResult = { ok: true; patch: SeoPatch } | { ok: false; message: string };
+
+export const SEO_PATCH_KEYS = [
+ "title",
+ "description",
+ "canonicalUrl",
+ "noIndex",
+ "noFollow",
+ "ogTitle",
+ "ogDescription",
+ "ogImage",
+ "metaOther",
+ "jsonLD",
+] as const;
+
+const TEXT_KEYS = ["title", "description", "canonicalUrl", "ogTitle", "ogDescription", "ogImage"] as const;
+const BOOLEAN_KEYS = ["noIndex", "noFollow"] as const;
+const URL_KEYS = ["canonicalUrl", "ogImage"] as const;
+
+const MAX_TEXT_LEN = 2000;
+const MAX_META_OTHER_ENTRIES = 50;
+const MAX_JSONLD_CHARS = 50_000;
+const EMPTY_JSON_OBJECT = "{}";
+
+export const isPlainRecord = (value: unknown): value is Record =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const asString = (value: unknown): string => (value === null || value === undefined ? "" : String(value));
+const isEmptyJsonString = (value: string): boolean => ["", "{}", "[]"].includes(value.trim());
+
+const stringPairsOnly = (source: Record): Record => {
+ const pairs: Record = {};
+ for (const [key, value] of Object.entries(source)) {
+ if (typeof value === "string") pairs[key] = value;
+ }
+ return pairs;
+};
+
+const parseMetaOtherString = (value: string): { pairs: Record; raw?: string } => {
+ if (isEmptyJsonString(value)) return { pairs: {} };
+ try {
+ const parsed = JSON.parse(value);
+ if (!isPlainRecord(parsed)) return { pairs: {}, raw: value };
+ return { pairs: stringPairsOnly(parsed) };
+ } catch {
+ return { pairs: {}, raw: value };
+ }
+};
+
+const isEmptyDocument = (value: Record | unknown[]): boolean =>
+ Array.isArray(value) ? value.length === 0 : Object.keys(value).length === 0;
+
+export const normalizeStoredSeo = (raw: unknown): NormalizedSeo => {
+ const source = isPlainRecord(raw) ? raw : {};
+ const canonicalUrl = asString(source.canonicalUrl) || asString(source.cononicalUrl);
+
+ let metaOther: Record = {};
+ let metaOtherRaw: string | undefined;
+ if (isPlainRecord(source.metaOther)) {
+ metaOther = stringPairsOnly(source.metaOther);
+ } else if (typeof source.metaOther === "string") {
+ const parsed = parseMetaOtherString(source.metaOther);
+ metaOther = parsed.pairs;
+ metaOtherRaw = parsed.raw;
+ }
+
+ let jsonLD: Record | unknown[] | null = null;
+ let jsonLDRaw: string | undefined;
+ const storedJsonLd = source.jsonLD;
+ if (isPlainRecord(storedJsonLd) || Array.isArray(storedJsonLd)) {
+ jsonLD = isEmptyDocument(storedJsonLd) ? null : storedJsonLd;
+ } else if (typeof storedJsonLd === "string") {
+ if (!isEmptyJsonString(storedJsonLd)) {
+ try {
+ const parsed = JSON.parse(storedJsonLd);
+ if (isPlainRecord(parsed) || Array.isArray(parsed)) {
+ jsonLD = isEmptyDocument(parsed) ? null : parsed;
+ } else {
+ jsonLDRaw = storedJsonLd;
+ }
+ } catch {
+ jsonLDRaw = storedJsonLd;
+ }
+ }
+ }
+
+ return {
+ seo: {
+ title: asString(source.title),
+ description: asString(source.description),
+ canonicalUrl,
+ noIndex: Boolean(source.noIndex),
+ noFollow: Boolean(source.noFollow),
+ },
+ metaTags: {
+ ogTitle: asString(source.ogTitle),
+ ogDescription: asString(source.ogDescription),
+ ogImage: asString(source.ogImage),
+ metaOther,
+ },
+ jsonLD,
+ ...(jsonLDRaw !== undefined ? { jsonLDRaw } : {}),
+ ...(metaOtherRaw !== undefined ? { metaOtherRaw } : {}),
+ };
+};
+
+const isAcceptableUrlValue = (value: string): boolean => {
+ const trimmed = value.trim();
+ if (trimmed === "") return true;
+ if (trimmed.startsWith("/")) {
+ if (/^\/[/\\]/.test(trimmed)) return false;
+ return true;
+ }
+ if (trimmed.startsWith("{{")) return true;
+ if (/^https?:\/\//i.test(trimmed)) return true;
+ return false;
+};
+
+const parseMetaOtherArg = (
+ value: unknown,
+): { ok: true; pairs: Record } | { ok: false; message: string } => {
+ if (!isPlainRecord(value)) {
+ return { ok: false, message: "Error: metaOther must be an object of meta name/content string pairs." };
+ }
+ const entries = Object.entries(value);
+ if (entries.length > MAX_META_OTHER_ENTRIES) {
+ return { ok: false, message: `Error: metaOther accepts at most ${MAX_META_OTHER_ENTRIES} entries.` };
+ }
+ const pairs: Record = {};
+ for (const [key, entryValue] of entries) {
+ if (key.trim() === "") return { ok: false, message: "Error: metaOther keys cannot be empty." };
+ if (typeof entryValue !== "string") {
+ return { ok: false, message: `Error: metaOther["${key}"] must be a string.` };
+ }
+ if (entryValue.length > MAX_TEXT_LEN) {
+ return { ok: false, message: `Error: metaOther["${key}"] must be at most ${MAX_TEXT_LEN} characters.` };
+ }
+ pairs[key] = entryValue;
+ }
+ return { ok: true, pairs };
+};
+
+const parseJsonLdArg = (
+ value: unknown,
+): { ok: true; value: Record | unknown[] | null } | { ok: false; message: string } => {
+ if (value === null) return { ok: true, value: null };
+
+ let document: unknown = value;
+ if (typeof value === "string") {
+ if (isEmptyJsonString(value)) return { ok: true, value: null };
+ try {
+ document = JSON.parse(value);
+ } catch {
+ return { ok: false, message: "Error: jsonLD is not valid JSON." };
+ }
+ }
+
+ if (!isPlainRecord(document) && !Array.isArray(document)) {
+ return {
+ ok: false,
+ message: "Error: jsonLD must be a JSON-LD object or an array of them, not a primitive value.",
+ };
+ }
+
+ if (isEmptyDocument(document)) return { ok: true, value: null };
+
+ const serialized = JSON.stringify(document);
+ if (serialized.length > MAX_JSONLD_CHARS) {
+ return { ok: false, message: `Error: jsonLD must serialize to at most ${MAX_JSONLD_CHARS} characters.` };
+ }
+
+ return { ok: true, value: document };
+};
+
+export const parseSeoPatch = (args: Record): ParseResult => {
+ const patch: SeoPatch = {};
+
+ for (const key of TEXT_KEYS) {
+ const value = args[key];
+ if (value === undefined) continue;
+ if (typeof value !== "string") return { ok: false, message: `Error: ${key} must be a string.` };
+ if (value.length > MAX_TEXT_LEN) {
+ return { ok: false, message: `Error: ${key} must be at most ${MAX_TEXT_LEN} characters.` };
+ }
+ patch[key] = value;
+ }
+
+ for (const key of URL_KEYS) {
+ const value = patch[key];
+ if (value === undefined) continue;
+ if (!isAcceptableUrlValue(value)) {
+ return {
+ ok: false,
+ message: `Error: ${key} must be an absolute http(s) URL, an absolute path starting with /, or a {{binding}} expression.`,
+ };
+ }
+ }
+
+ for (const key of BOOLEAN_KEYS) {
+ const value = args[key];
+ if (value === undefined) continue;
+ if (typeof value !== "boolean") return { ok: false, message: `Error: ${key} must be true or false.` };
+ patch[key] = value;
+ }
+
+ if (args.metaOther !== undefined) {
+ const parsed = parseMetaOtherArg(args.metaOther);
+ if (!parsed.ok) return parsed;
+ patch.metaOther = parsed.pairs;
+ }
+
+ if (args.jsonLD !== undefined) {
+ const parsed = parseJsonLdArg(args.jsonLD);
+ if (!parsed.ok) return parsed;
+ patch.jsonLD = parsed.value;
+ }
+
+ if (Object.keys(patch).length === 0) {
+ return {
+ ok: false,
+ message: `Error: Provide at least one SEO field to update (${SEO_PATCH_KEYS.join(", ")}).`,
+ };
+ }
+
+ return { ok: true, patch };
+};
+
+export const mergeSeoUpdate = (
+ current: Record,
+ patch: SeoPatch,
+): { seo: Record; changedKeys: string[] } => {
+ const seo: Record = { ...current };
+ const changedKeys: string[] = [];
+
+ for (const key of SEO_PATCH_KEYS) {
+ if (!(key in patch)) continue;
+ changedKeys.push(key);
+
+ if (key === "jsonLD") {
+ seo.jsonLD =
+ patch.jsonLD === null || patch.jsonLD === undefined ? EMPTY_JSON_OBJECT : JSON.stringify(patch.jsonLD);
+ continue;
+ }
+ if (key === "metaOther") {
+ const pairs = patch.metaOther ?? {};
+ seo.metaOther = Object.keys(pairs).length === 0 ? EMPTY_JSON_OBJECT : JSON.stringify(pairs);
+ continue;
+ }
+ if (key === "canonicalUrl") {
+ seo.canonicalUrl = patch.canonicalUrl;
+ delete seo.cononicalUrl;
+ continue;
+ }
+ seo[key] = patch[key];
+ }
+
+ if (
+ patch.ogImage !== undefined &&
+ patch.ogImage !== asString(current.ogImage) &&
+ asString(current.ogImageId) !== ""
+ ) {
+ seo.ogImageId = "";
+ changedKeys.push("ogImageId");
+ }
+
+ return { seo, changedKeys };
+};
+
+export const describeSeoPageLang = (info: PageLangInfo): string => {
+ if (!info.lang) return "";
+ const base = `Content language: ${langLabel(info.lang)}. Write all SEO text in this language.`;
+ if (!info.isLanguageVariant) return base;
+ return `${base} SEO is stored per language page: changes here apply only to the ${langLabel(info.lang)} row, and the primary-language page and other variants keep their own SEO. When this variant has no JSON-LD of its own it inherits the primary page's document at render time.`;
+};
diff --git a/src/utils/page-translations.ts b/src/utils/page-translations.ts
new file mode 100644
index 000000000..0fa2307f3
--- /dev/null
+++ b/src/utils/page-translations.ts
@@ -0,0 +1,405 @@
+import { isEqual } from "lodash-es";
+import { getRegisteredChaiBlock } from "~/registry";
+import { sanitizeAiPropValue } from "~/server/chai-actions/ai/ask-ai/ai-edit-executors";
+import type { ChaiBlock } from "~/types/common";
+import { langLabel } from "./page-lang";
+
+/**
+ * Per-language block content and binding-preservation helpers shared by
+ * Builder AI and MCP tools.
+ *
+ * ChaiBuilder keeps every language's copy on the primary page's blocks: the
+ * bare prop (`content`) holds the site fallback language and `content-{lang}`
+ * holds each translation. Only the props a block type lists in `i18nProps` are
+ * translatable, and the renderer (`applyLanguage`) shows the translation when
+ * it is non-blank, otherwise the bare prop.
+ */
+
+/** Fresh, non-global matcher: `.test`/`.match` on a shared global regex is stateful. */
+const BINDING_PATTERN = /\{\{(.*?)\}\}/g;
+
+/** All `{{...}}` substrings in `text`, in order, duplicates kept. */
+export function extractBindings(text: string): string[] {
+ return text.match(new RegExp(BINDING_PATTERN)) ?? [];
+}
+
+/**
+ * True when `output` holds exactly the same multiset of bindings as `inputBindings`.
+ * Position may differ — a translation reorders words — but nothing may be added,
+ * dropped, duplicated or altered.
+ */
+export function bindingsMatch(inputBindings: string[], output: string): boolean {
+ const outputBindings = extractBindings(output);
+ if (inputBindings.length !== outputBindings.length) return false;
+
+ const remaining = new Map();
+ for (const binding of inputBindings) {
+ remaining.set(binding, (remaining.get(binding) ?? 0) + 1);
+ }
+ for (const binding of outputBindings) {
+ const count = remaining.get(binding);
+ if (!count) return false;
+ remaining.set(binding, count - 1);
+ }
+ return true;
+}
+
+type AnyBlock = Record;
+
+export type I18nPropsOf = (type: string) => string[];
+
+export const registryI18nProps: I18nPropsOf = (type) => {
+ const props = getRegisteredChaiBlock(type)?.i18nProps;
+ return Array.isArray(props) ? props : [];
+};
+
+/** Reference blocks carry no content of their own. */
+const REFERENCE_TYPES = new Set(["PartialBlock", "GlobalBlock"]);
+
+/**
+ * Translatable props that hold a per-language asset or destination rather than
+ * copy. A language only overrides them on purpose (a localized image or link),
+ * so they are never reported as needing translation.
+ */
+const ASSET_PROPS = new Set(["image", "_imageId", "mobileImage", "_mobileImageId", "url", "customUrl", "link"]);
+
+export const translationKind = (prop: string): "text" | "asset" => (ASSET_PROPS.has(prop) ? "asset" : "text");
+
+export const translatedKey = (prop: string, lang: string) => `${prop}-${lang}`;
+
+export const isBlankValue = (value: unknown): boolean => {
+ if (value == null) return true;
+ if (typeof value === "string") return value.trim().length === 0;
+ if (typeof value === "number" || typeof value === "boolean") return false;
+ if (Array.isArray(value)) return value.length === 0;
+ if (typeof value === "object") return Object.keys(value).length === 0;
+ return false;
+};
+
+const translatableProps = (block: AnyBlock, i18nPropsOf: I18nPropsOf) => {
+ const type = block._type;
+ if (typeof type !== "string" || REFERENCE_TYPES.has(type)) return [];
+ return i18nPropsOf(type).filter((prop) => typeof prop === "string" && prop);
+};
+
+/** The value a block renders for `prop` in `lang` — same rule as applyLanguage. */
+export const resolveLangValue = (block: AnyBlock, prop: string, lang: string): unknown => {
+ const base = block[prop];
+ const translated = block[translatedKey(prop, lang)];
+ return isBlankValue(translated) ? base : translated;
+};
+
+/**
+ * Swap each translatable bare prop for the value `lang` renders, so AI-HTML and
+ * the outline show that language's copy. Blocks without a bare prop are left
+ * alone: applyLanguage ignores their suffixed props too.
+ */
+export const toLanguageView = (
+ blocks: ChaiBlock[],
+ lang: string,
+ i18nPropsOf: I18nPropsOf = registryI18nProps,
+): ChaiBlock[] =>
+ blocks.map((block) => {
+ const record = block as unknown as AnyBlock;
+ let next: AnyBlock | null = null;
+ for (const prop of translatableProps(record, i18nPropsOf)) {
+ if (!Object.prototype.hasOwnProperty.call(record, prop)) continue;
+ const value = resolveLangValue(record, prop, lang);
+ if (value === record[prop]) continue;
+ next ??= { ...record };
+ next[prop] = value;
+ }
+ return (next ?? record) as unknown as ChaiBlock;
+ });
+
+export type LanguageViewResult = {
+ blocks: ChaiBlock[];
+ /**
+ * Blocks whose translatable copy had no fallback-language value to keep, so
+ * the text written in `lang` also became their fallback-language copy.
+ */
+ seededFallbackBlockIds: string[];
+};
+
+/**
+ * Map an edited language view back to stored blocks. A translatable prop the
+ * edit changed is written to `prop-{lang}` and the stored fallback value is
+ * restored; an unchanged one keeps its stored values untouched, so reading a
+ * page in a language never invents a translation. A brand-new block (or a prop
+ * the block did not have) has no fallback copy to protect, so the text becomes
+ * both its fallback value and its `lang` translation.
+ */
+export const fromLanguageView = (
+ originalBlocks: ChaiBlock[],
+ nextViewBlocks: ChaiBlock[],
+ lang: string,
+ i18nPropsOf: I18nPropsOf = registryI18nProps,
+): LanguageViewResult => {
+ const originalById = new Map(originalBlocks.map((block) => [block._id, block as unknown as AnyBlock]));
+ const seeded = new Set();
+
+ const blocks = nextViewBlocks.map((block) => {
+ const record = { ...(block as unknown as AnyBlock) };
+ const original = originalById.get(block._id);
+ const sameType = original && original._type === record._type;
+
+ for (const prop of translatableProps(record, i18nPropsOf)) {
+ if (!Object.prototype.hasOwnProperty.call(record, prop)) continue;
+ const value = record[prop];
+ const key = translatedKey(prop, lang);
+
+ if (sameType && Object.prototype.hasOwnProperty.call(original, prop)) {
+ if (isEqual(value, resolveLangValue(original, prop, lang))) {
+ record[prop] = original[prop];
+ if (Object.prototype.hasOwnProperty.call(original, key)) {
+ record[key] = original[key];
+ } else {
+ delete record[key];
+ }
+ continue;
+ }
+ if (!isBlankValue(original[prop])) {
+ record[prop] = original[prop];
+ if (isBlankValue(value)) delete record[key];
+ else record[key] = value;
+ continue;
+ }
+ }
+
+ if (isBlankValue(value)) {
+ delete record[key];
+ continue;
+ }
+ record[key] = value;
+ seeded.add(block._id);
+ }
+ return record as unknown as ChaiBlock;
+ });
+
+ return { blocks, seededFallbackBlockIds: [...seeded] };
+};
+
+export type TranslationEntry = {
+ blockId: string;
+ blockType: string;
+ blockName?: string;
+ prop: string;
+ /** `asset` props (images, links, video URLs) are overridden per language only on purpose. */
+ kind: "text" | "asset";
+ /** Fallback-language value — the source to translate from. */
+ source: unknown;
+ /** Current `prop-{lang}` value, or null when the language renders the source. */
+ translation: unknown;
+};
+
+/** Every translatable prop with a non-blank source, in stored (document) order. */
+export const collectTranslations = (
+ blocks: ChaiBlock[],
+ lang: string,
+ options: { blockIds?: string[]; missingOnly?: boolean } = {},
+ i18nPropsOf: I18nPropsOf = registryI18nProps,
+): TranslationEntry[] => {
+ const wanted = options.blockIds && options.blockIds.length > 0 ? new Set(options.blockIds) : null;
+ const entries: TranslationEntry[] = [];
+ for (const block of blocks) {
+ if (wanted && !wanted.has(block._id)) continue;
+ const record = block as unknown as AnyBlock;
+ for (const prop of translatableProps(record, i18nPropsOf)) {
+ const source = record[prop];
+ const translation = record[translatedKey(prop, lang)];
+ if (isBlankValue(source) && isBlankValue(translation)) continue;
+ const kind = translationKind(prop);
+ if (options.missingOnly) {
+ if (kind === "asset" || !isBlankValue(translation)) continue;
+ }
+ entries.push({
+ blockId: block._id,
+ blockType: String(record._type),
+ ...(block._name ? { blockName: block._name } : {}),
+ prop,
+ kind,
+ source,
+ translation: isBlankValue(translation) ? null : translation,
+ });
+ }
+ }
+ return entries;
+};
+
+const isRemoval = (value: unknown) => value == null || (typeof value === "string" && value.trim() === "");
+
+const valueKind = (value: unknown): "string" | "array" | "object" | "other" =>
+ typeof value === "string"
+ ? "string"
+ : Array.isArray(value)
+ ? "array"
+ : value && typeof value === "object"
+ ? "object"
+ : "other";
+
+const serializeForBindings = (value: unknown): string =>
+ typeof value === "string" ? value : (JSON.stringify(value) ?? "");
+
+export type TranslationUpdate = {
+ blockId: string;
+ prop: string;
+ /** New translation; null or a blank value removes it (the source renders). */
+ value: unknown;
+};
+
+/**
+ * Write `prop-{lang}` values onto the stored blocks. Every update is validated
+ * before anything changes, so one bad entry rejects the whole batch.
+ */
+export const applyTranslations = (
+ blocks: ChaiBlock[],
+ lang: string,
+ updates: TranslationUpdate[],
+ i18nPropsOf: I18nPropsOf = registryI18nProps,
+): { blocks: ChaiBlock[] } | { error: string } => {
+ const byId = new Map(blocks.map((block) => [block._id, block]));
+ const errors: string[] = [];
+ for (const update of updates) {
+ const block = byId.get(update.blockId) as unknown as AnyBlock | undefined;
+ if (!block) {
+ errors.push(`No block with bid "${update.blockId}"`);
+ continue;
+ }
+ const props = translatableProps(block, i18nPropsOf);
+ if (!props.includes(update.prop)) {
+ errors.push(
+ `"${update.prop}" is not translatable on ${String(block._type)} block "${update.blockId}"` +
+ (props.length ? ` (translatable: ${props.join(", ")})` : ""),
+ );
+ continue;
+ }
+ if (!Object.prototype.hasOwnProperty.call(block, update.prop)) {
+ errors.push(
+ `Block "${update.blockId}" has no fallback-language "${update.prop}", so a translation would never render. Set its content with edit_block first.`,
+ );
+ continue;
+ }
+ if (isRemoval(update.value)) continue;
+ const source = block[update.prop];
+ const sourceKind = valueKind(source);
+ const updateKind = valueKind(update.value);
+ if (!isBlankValue(source) && sourceKind !== updateKind) {
+ errors.push(
+ `Translation for "${update.prop}" on block "${update.blockId}" must have the same shape as the source (${sourceKind}, got ${updateKind})`,
+ );
+ continue;
+ }
+ const sourceBindings = extractBindings(serializeForBindings(source));
+ if (!bindingsMatch(sourceBindings, serializeForBindings(update.value))) {
+ errors.push(
+ `Translation for "${update.prop}" on block "${update.blockId}" must keep the source's {{bindings}} exactly: ${JSON.stringify(sourceBindings)}`,
+ );
+ }
+ }
+ if (errors.length > 0) return { error: errors.join("; ") };
+
+ const updatesById = new Map();
+ for (const update of updates) {
+ const list = updatesById.get(update.blockId) ?? [];
+ list.push(update);
+ updatesById.set(update.blockId, list);
+ }
+
+ return {
+ blocks: blocks.map((block) => {
+ const list = updatesById.get(block._id);
+ if (!list) return block;
+ const record = { ...(block as unknown as AnyBlock) };
+ for (const { prop, value } of list) {
+ const key = translatedKey(prop, lang);
+ if (isRemoval(value)) delete record[key];
+ else record[key] = sanitizeAiPropValue(value);
+ }
+ return record as unknown as ChaiBlock;
+ }),
+ };
+};
+
+export type ChangedSourceProp = {
+ blockId: string;
+ blockType: string;
+ prop: string;
+ /** New fallback-language value; blank when the edit cleared it. */
+ source: unknown;
+ /** Translations stored per language before the edit (null when missing). */
+ previousTranslations: Record;
+};
+
+/**
+ * Fallback-language copy an edit changed or added, for the languages given.
+ * These are the translations that are now stale or missing.
+ */
+export const findChangedSourceProps = (
+ before: ChaiBlock[],
+ after: ChaiBlock[],
+ langs: string[],
+ i18nPropsOf: I18nPropsOf = registryI18nProps,
+): ChangedSourceProp[] => {
+ if (langs.length === 0) return [];
+ const beforeById = new Map(before.map((block) => [block._id, block as unknown as AnyBlock]));
+ const changes: ChangedSourceProp[] = [];
+ for (const block of after) {
+ const record = block as unknown as AnyBlock;
+ const previous = beforeById.get(block._id);
+ for (const prop of translatableProps(record, i18nPropsOf)) {
+ if (translationKind(prop) === "asset") continue;
+ const source = record[prop];
+ const samePrevious = previous && previous._type === record._type;
+ if (samePrevious && isEqual(previous[prop], source)) continue;
+ const previousTranslations: Record = {};
+ for (const lang of langs) {
+ const value = record[translatedKey(prop, lang)];
+ previousTranslations[lang] = isBlankValue(value) ? null : value;
+ }
+ if (
+ isBlankValue(source) &&
+ (!samePrevious || isBlankValue(previous[prop])) &&
+ Object.values(previousTranslations).every((value) => value === null)
+ ) {
+ continue;
+ }
+ changes.push({
+ blockId: block._id,
+ blockType: String(record._type),
+ prop,
+ source,
+ previousTranslations,
+ });
+ }
+ }
+ return changes;
+};
+
+const MAX_SYNC_ENTRIES = 60;
+
+/** Instructions telling the model which translations an edit left stale. @internal */
+export const describeTranslationSync = (changes: ChangedSourceProp[], langs: string[]): string => {
+ if (changes.length === 0 || langs.length === 0) return "";
+ const listed = changes.slice(0, MAX_SYNC_ENTRIES).map((change) => ({
+ blockId: change.blockId,
+ blockType: change.blockType,
+ prop: change.prop,
+ source: change.source,
+ previousTranslations: change.previousTranslations,
+ }));
+ const rest = changes.slice(MAX_SYNC_ENTRIES);
+ const restNote = rest.length
+ ? `\n${rest.length} more changed values are not listed; read them with get_block_translations for blockIds ${JSON.stringify([...new Set(rest.map((c) => c.blockId))])}.`
+ : "";
+ return `\n- 🌐 Translations to sync: this page has language variants (${langs.map(langLabel).join(", ")}), and this edit changed ${changes.length} translatable value(s) in the fallback language. Those languages now show outdated or fallback copy. Before reporting back, call update_block_translations once per language with each source below translated into that language, keeping {{bindings}}, URLs and HTML markup intact. Where a source is empty (the copy was cleared), send value null to remove that language's translation:\n\`\`\`json\n${JSON.stringify(listed, null, 2)}\n\`\`\`${restNote}`;
+};
+
+/** Note explaining that new copy on a language variant was also seeded as fallback-language copy. */
+export const describeSeededFallbackCopy = (
+ seededFallbackBlockIds: string[],
+ lang: string,
+ fallbackLang: string,
+): string => {
+ if (seededFallbackBlockIds.length === 0) return "";
+ return `New copy on blocks ${seededFallbackBlockIds.join(", ")} had no ${langLabel(fallbackLang)} text, so the same ${langLabel(lang)} text was also stored as their fallback-language copy. Tell the user the primary-language page shows it untranslated until it is edited there.`;
+};
diff --git a/src/utils/page-type-helpers.ts b/src/utils/page-type-helpers.ts
new file mode 100644
index 000000000..7a53f3d84
--- /dev/null
+++ b/src/utils/page-type-helpers.ts
@@ -0,0 +1,64 @@
+/**
+ * Page-type resolution helpers shared by Builder AI and MCP tools.
+ */
+
+/** The one partial type agents create: the builder's built-in global block. */
+export const GLOBAL_PARTIAL_PAGE_TYPE = "global";
+
+const PARTIAL_ALIASES = new Set([
+ "partial",
+ "partials",
+ "partial-block",
+ "partial_block",
+ "partialblock",
+ "global-block",
+ "global_block",
+ "globalblock",
+ "global block",
+ "partial block",
+]);
+
+export type PageTypeCandidate = {
+ key: string;
+ hasSlug?: boolean;
+ partial?: boolean;
+};
+
+export type PageTypeResolution = { ok: true; key: string; isPartial: boolean } | { ok: false; message: string };
+
+const isPartialType = (type: PageTypeCandidate) => type.partial === true || type.hasSlug === false;
+
+/** Whether a stored page's type is a partial (global block, layout, form…). */
+export function isPartialPageTypeKey(key: string | null | undefined, pageTypes: PageTypeCandidate[]): boolean {
+ if (!key) return false;
+ if (key === GLOBAL_PARTIAL_PAGE_TYPE) return true;
+ const match = pageTypes.find((type) => type.key === key);
+ return match ? isPartialType(match) : false;
+}
+
+export function resolveCreatePageType(
+ requested: string | undefined,
+ pageTypes: PageTypeCandidate[],
+): PageTypeResolution {
+ const raw = requested?.trim() ?? "";
+ if (!raw) return { ok: true, key: "page", isPartial: false };
+
+ const normalized = raw.toLowerCase();
+ const key = PARTIAL_ALIASES.has(normalized) ? GLOBAL_PARTIAL_PAGE_TYPE : normalized;
+
+ const creatable = pageTypes.filter((type) => !isPartialType(type) || type.key === GLOBAL_PARTIAL_PAGE_TYPE);
+ const match = creatable.find((type) => type.key.toLowerCase() === key);
+ if (match) {
+ return { ok: true, key: match.key, isPartial: isPartialType(match) };
+ }
+
+ const valid = creatable.map((type) => `"${type.key}"`).join(", ");
+ const isOtherPartial = pageTypes.some((type) => type.key.toLowerCase() === key && isPartialType(type));
+ const hint = isOtherPartial
+ ? ` Partials (header, footer, navigation and other reusable sections) are always created as pageType "${GLOBAL_PARTIAL_PAGE_TYPE}".`
+ : ` For a partial (header, footer, navigation or another reusable section) use pageType "${GLOBAL_PARTIAL_PAGE_TYPE}".`;
+ return {
+ ok: false,
+ message: `Error: pageType "${raw}" cannot be created. Valid page types: ${valid}.${hint}`,
+ };
+}
diff --git a/src/web-blocks/helper.test.ts b/src/web-blocks/helper.test.ts
index cfd99b999..1b2ac7d7a 100644
--- a/src/web-blocks/helper.test.ts
+++ b/src/web-blocks/helper.test.ts
@@ -1,4 +1,4 @@
-import { getAriaLabel } from "./helper";
+import { addForcedClasses, getAriaLabel, mergeChaiStyles } from "./helper";
describe("getAriaLabel", () => {
it("returns the trimmed author-set label", () => {
@@ -22,3 +22,103 @@ describe("getAriaLabel", () => {
expect(getAriaLabel({ "aria-label": {} })).toBeUndefined();
});
});
+
+describe("addForcedClasses", () => {
+ it("preserves custom HTML attributes while merging classes", () => {
+ const result = addForcedClasses(
+ {
+ id: "hero-input",
+ "data-track": "search-input",
+ "aria-label": "Search homes",
+ className: "px-4 text-sm",
+ },
+ "focus-visible:outline-none",
+ );
+
+ expect(result).toEqual({
+ id: "hero-input",
+ "data-track": "search-input",
+ "aria-label": "Search homes",
+ className: "px-4 text-sm focus-visible:outline-none",
+ });
+ });
+
+ it("handles undefined styles safely", () => {
+ expect(addForcedClasses(undefined, "flex", "items-center")).toEqual({
+ className: "flex items-center",
+ });
+ expect(addForcedClasses(undefined)).toEqual({});
+ });
+
+ it("accepts conditional ClassValue inputs and resolves Tailwind conflicts", () => {
+ const isActive = true;
+ const isHidden = false;
+ const result = addForcedClasses(
+ { className: "px-2 text-muted-foreground", "data-slot": "tab" },
+ isActive && "px-4 text-foreground",
+ isHidden && "hidden",
+ undefined,
+ null,
+ );
+
+ expect(result).toEqual({
+ "data-slot": "tab",
+ className: "px-4 text-foreground",
+ });
+ });
+
+ it("omits className when the merged class string is empty", () => {
+ const result = addForcedClasses({ className: "", "data-id": "empty" }, "", false, undefined);
+ expect(result).toEqual({ "data-id": "empty" });
+ expect("className" in result).toBe(false);
+ });
+
+ it("does not mutate the input styles object", () => {
+ const original = { className: "p-2", "data-k": "v" };
+ const result = addForcedClasses(original, "p-4");
+ expect(original).toEqual({ className: "p-2", "data-k": "v" });
+ expect(result).toEqual({ className: "p-4", "data-k": "v" });
+ });
+});
+
+describe("mergeChaiStyles", () => {
+ it("merges custom HTML attributes with the first style winning, and Tailwind classes with later precedence", () => {
+ const base = {
+ id: "tab-1",
+ "data-role": "tab",
+ "data-state": "inactive",
+ className: "px-3 text-muted-foreground",
+ };
+ const active = {
+ "data-state": "active",
+ "aria-current": "page",
+ className: "text-foreground font-semibold",
+ };
+
+ expect(mergeChaiStyles(base, active)).toEqual({
+ id: "tab-1",
+ "data-role": "tab",
+ "data-state": "inactive",
+ "aria-current": "page",
+ className: "px-3 text-foreground font-semibold",
+ });
+ });
+
+ it("skips false, null, and undefined entries", () => {
+ const base = { "data-tab": "buy", className: "px-3" };
+ expect(mergeChaiStyles(base, false, null, undefined)).toEqual({
+ "data-tab": "buy",
+ className: "px-3",
+ });
+ });
+
+ it("omits className when all merged entries have no classes", () => {
+ const result = mergeChaiStyles({ id: "a", className: "" }, { "data-x": "1" });
+ expect(result).toEqual({ id: "a", "data-x": "1" });
+ expect("className" in result).toBe(false);
+ });
+
+ it("returns an empty object when called with no truthy styles", () => {
+ expect(mergeChaiStyles(undefined, false, null)).toEqual({});
+ });
+});
diff --git a/src/web-blocks/helper.ts b/src/web-blocks/helper.ts
index 4df96b2b2..674b184c3 100644
--- a/src/web-blocks/helper.ts
+++ b/src/web-blocks/helper.ts
@@ -1,3 +1,4 @@
+import { type ClassValue } from "cnfast";
import { cn } from "~/builder/core/functions/common-functions";
import { ChaiStyles } from "~/types/blocks";
@@ -17,10 +18,36 @@ export const getAriaLabel = (attrs: Record | undefined | null):
return trimmed || undefined;
};
-export const addForcedClasses = (styles: ChaiStyles, ...classes: string[]) => {
- // get all the classes from the blockStateClasses if the value is true
- return {
- ...styles,
- className: cn(styles.className, ...classes),
- };
+export const addForcedClasses = (
+ styles: ChaiStyles | undefined,
+ ...classes: ClassValue[]
+): ChaiStyles => {
+ const className = cn(styles?.className, ...classes);
+ const next: ChaiStyles = { ...styles };
+ if (className) {
+ next.className = className;
+ } else {
+ delete next.className;
+ }
+ return next;
+};
+
+// Classes combine in order; for any other attribute the first style that sets it wins, so the editor still selects the main style.
+export const mergeChaiStyles = (
+ ...stylesList: Array
+): ChaiStyles => {
+ let merged: ChaiStyles = {};
+ const classes: ClassValue[] = [];
+ for (const item of stylesList) {
+ if (!item) continue;
+ merged = { ...item, ...merged };
+ classes.push(item.className);
+ }
+ const className = cn(...classes);
+ if (className) {
+ merged.className = className;
+ } else {
+ delete merged.className;
+ }
+ return merged;
};