webcake-landing-mcp 1.4.0 → 1.5.1

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.
@@ -1,4 +1,18 @@
1
1
  [
2
+ {
3
+ "v": "1.5.1",
4
+ "d": "24/08/2026",
5
+ "type": "Added",
6
+ "en": "update_page now detects when the live page was edited outside this session (e.g. in the Webcake editor) since it was last read, and rejects the…",
7
+ "vi": "update_page nay phát hiện khi trang đang sống đã bị chỉnh sửa bên ngoài phiên làm việc này (ví dụ trong editor Webcake) kể từ lần đọc gần nhất, và…"
8
+ },
9
+ {
10
+ "v": "1.5.0",
11
+ "d": "23/07/2026",
12
+ "type": "Added",
13
+ "en": "search_images now returns a sizes map on every photo (the delivered width/height in px for each src variant, accounting for retina dpr) plus a…",
14
+ "vi": "search_images nay trả về một sizes map trên mỗi ảnh (kích thước width/height thực tế theo px của từng biến thể src, có tính đến dpr cho màn hình…"
15
+ },
2
16
  {
3
17
  "v": "1.4.0",
4
18
  "d": "23/07/2026",
@@ -26,19 +40,5 @@
26
40
  "type": "Added",
27
41
  "en": "New layout tool computes exact top/left/width/height coordinates for both breakpoints so the model never hand-calculates left/top (the number-one…",
28
42
  "vi": "Tool mới layout tính toán chính xác tọa độ top/left/width/height cho cả hai breakpoint để model không cần tự tính left/top bằng tay (nguyên nhân…"
29
- },
30
- {
31
- "v": "1.1.0",
32
- "d": "20/06/2026",
33
- "type": "Added",
34
- "en": "create_page, add_section, and validate_page now apply a deterministic layout auto-fix before validating or saving: off-canvas children are pulled…",
35
- "vi": "create_page, add_section và validate_page nay tự động áp dụng một lần auto-fix layout xác định trước khi validate hoặc lưu: các phần tử con nằm…"
36
- },
37
- {
38
- "v": "1.0.84",
39
- "d": "17/06/2026",
40
- "type": "Added",
41
- "en": "create_page now sends a by_ai field in the create request body (default value \"mcp\") so the backend can stamp each MCP-generated page in its by_ai…",
42
- "vi": "create_page nay gửi thêm trường by_ai trong body của request tạo trang (giá trị mặc định \"mcp\") để backend có thể đánh dấu từng trang được tạo qua…"
43
43
  }
44
44
  ]
@@ -113,8 +113,8 @@ SECTION BUILD HINTS (apply to whichever sections the chosen archetype uses)
113
113
 
114
114
  RULES
115
115
  - Visible content goes in "specials" (text-block.specials.text, image-block.specials.src…), NEVER in "styles".
116
- - Colors as rgba(r,g,b,a). fontSize/borderWidth/top/left/width/height are NUMBERS (px). borderRadius is a STRING with CSS units ("8px", "50%", "16px 16px 0 0") — a bare number or unit-less string is auto-coerced to px by the server, but write the unit explicitly to avoid surprises.
117
- - IMAGES: a real landing page has images (hero/product shot, feature icons, about photo). The save AUTO-HOSTS external image URLs: any real http(s) URL you put in specials.src / a url(...) background / gallery item.link / video poster gets downloaded and re-hosted to the Webcake CDN automatically on create_page/update_page/add_section/patch_page (the response's rehost field reports the count) — so reference and web image URLs do NOT need a pre-call to upload_images. SOURCE PRIORITY: (1) images the user supplied or that exist in the reference HTML/URL (ingest AST images/background_images/og_image, canvas src/background) → put the REAL source URL straight into the slot and let the save host it; use those EXACT images, never swap them for stock photos, and carry the URL through un-altered (never drop it, never placeholder a slot that had a real source image). The ONE case you must call upload_images yourself FIRST: LOCAL FILE PATHS from the user's computer (pass the path directly in upload_images 'urls' — the save can't read local files; NEVER relay the user's local file through a third-party host like catbox or imgur), then use the returned URL. (2) only for slots with NO source image → call search_images with a short English subject (e.g. 'fresh coffee cup', 'modern office team') and put a returned URL into image-block specials.src — use src.large for a hero/banner, src.medium for a card/thumb (avg_color helps pick a matching section background); (3) if search_images returns ok:false, is unreachable, or has NO photo that fits the slot → find a real image YOURSELF using whatever web search/fetch capability you have (the brand's own site, the product page, a free-to-use source), then re-host it via upload_images and use the returned URL; (4) a PLACEHOLDER is the LAST resort, ONLY after (2) AND (3) both failed — sized to the box: "https://placehold.co/<width>x<height>". Never jump straight from a failed search to a placeholder without trying (3). NEVER leave src empty — it renders blank on the live page. The server automatically derives styles.background from specials.src on every expand (create/update/validate) using the editor's exact format: 'center center/ cover no-repeat scroll content-box url(<src>) border-box' — you do NOT need to set styles.background manually; if you do hand-write it, it must contain url(...). A SECTION background may layer a gradient overlay over an image: 'linear-gradient(...), center center/ cover no-repeat scroll content-box url(<src>) border-box' — the server canonicalises any url() layer into that exact editor shorthand on expand (other url() formats survive the first save but get mangled to 'undefined/ undefined/ …' the moment the page is edited in the Webcake editor). gallery.media = array of OBJECTS {type:'image', link:'<real-or-placeholder-url>', linkVideo:'', typeVideo:'youtube', imageCompression:true} (NOT plain URL strings — the gallery reads item.link); video.specials.img = a poster image (real photo, else placeholder). Do NOT set a flat (no url()) styles.background on a video element — it suppresses the poster image.
116
+ - Colors as rgba(r,g,b,a). fontSize/borderWidth/top/left/width/height are NUMBERS (px) — always EMIT numbers. (Reading an existing page you may still meet strings: the editor saves fontSize as "59"/"13px", height as "600", opacity as "50%". The server normalizes those back to numbers on both get_page and save, so a hand-edited page is never locked out of the MCP; only a value with a unit the renderer cannot use — e.g. width:"100%" — is reported, as a warning.) borderRadius is a STRING with CSS units ("8px", "50%", "16px 16px 0 0") — a bare number or unit-less string is auto-coerced to px by the server, but write the unit explicitly to avoid surprises.
117
+ - IMAGES: a real landing page has images (hero/product shot, feature icons, about photo). The save AUTO-HOSTS external image URLs: any real http(s) URL you put in specials.src / a url(...) background / gallery item.link / video poster gets downloaded and re-hosted to the Webcake CDN automatically on create_page/update_page/add_section/patch_page (the response's rehost field reports the count) — so reference and web image URLs do NOT need a pre-call to upload_images. SOURCE PRIORITY: (1) images the user supplied or that exist in the reference HTML/URL (ingest AST images/background_images/og_image, canvas src/background) → put the REAL source URL straight into the slot and let the save host it; use those EXACT images, never swap them for stock photos, and carry the URL through un-altered (never drop it, never placeholder a slot that had a real source image). The ONE case you must call upload_images yourself FIRST: LOCAL FILE PATHS from the user's computer (pass the path directly in upload_images 'urls' — the save can't read local files; NEVER relay the user's local file through a third-party host like catbox or imgur), then use the returned URL. (2) only for slots with NO source image → call search_images with a short English subject (e.g. 'fresh coffee cup', 'modern office team') and put a returned URL into image-block specials.src. MATCH THE VARIANT TO THE SLOT SIZE — search_images returns a per-photo \`sizes\` map (delivered WxH per variant) + a \`size_guide\`; pick the variant whose width ≈ the element's RENDERED width (×1–2 for retina), then stop: full-bleed hero/banner (~900–1200px) → src.large (~940px) or src.large2x (~1880px); feature card/thumb (~260–360px) → src.medium (~350px); avatar/logo (~64–120px) → src.tiny (280px). NEVER stretch a small variant across a big slot — it pixelates ('vỡ ảnh'); NEVER put src.original (full-res, often several MB) or an oversized variant in a small card — it makes the page slow/heavy ('nặng trang'). If a photo's NATIVE width (photo.width) is smaller than the slot, pick a higher-res photo instead of upscaling. (avg_color helps pick a matching section background); (3) if search_images returns ok:false, is unreachable, or has NO photo that fits the slot → find a real image YOURSELF using whatever web search/fetch capability you have (the brand's own site, the product page, a free-to-use source), then re-host it via upload_images and use the returned URL; (4) a PLACEHOLDER is the LAST resort, ONLY after (2) AND (3) both failed — sized to the box: "https://placehold.co/<width>x<height>". Never jump straight from a failed search to a placeholder without trying (3). NEVER leave src empty — it renders blank on the live page. The server automatically derives styles.background from specials.src on every expand (create/update/validate) using the editor's exact format: 'center center/ cover no-repeat scroll content-box url(<src>) border-box' — you do NOT need to set styles.background manually; if you do hand-write it, it must contain url(...). A SECTION background may layer a gradient overlay over an image: 'linear-gradient(...), center center/ cover no-repeat scroll content-box url(<src>) border-box' — the server canonicalises any url() layer into that exact editor shorthand on expand (other url() formats survive the first save but get mangled to 'undefined/ undefined/ …' the moment the page is edited in the Webcake editor). gallery.media = array of OBJECTS {type:'image', link:'<real-or-placeholder-url>', linkVideo:'', typeVideo:'youtube', imageCompression:true} (NOT plain URL strings — the gallery reads item.link); video.specials.img = a poster image (real photo, else placeholder). Do NOT set a flat (no url()) styles.background on a video element — it suppresses the poster image.
118
118
  - CONTRAST (check EVERY text element against the band it sits on, especially SATURATED / mid-tone bands like yellow, orange, teal, pink — there "light vs dark text" is not obvious, so decide by the band's luminance): light bands → near-black text (e.g. rgba(20,30,25,1)); dark bands → near-white text; a saturated/mid-tone band → whichever of near-black or near-white actually reads (for a bright yellow/amber band that means DARK text, not white/grey). NEVER use muted-grey, low-alpha (alpha < ~0.85), or near-white text on a colored band — that is exactly what makes labels look faded/sunken. Muted-grey is ONLY for secondary text on a white/very-light band. Icons and their captions follow the SAME rule as the text beside them.
119
119
  - movable:false for section/slide/grid-item/popup; otherwise true. runtime is always {}.
120
120
  - Every form input MUST have a unique specials.field_name.
@@ -226,6 +226,104 @@ function normalizeMisplacedAnimation(node) {
226
226
  normalizeMisplacedAnimation(child);
227
227
  }
228
228
  }
229
+ // ---------------------------------------------------------------------------
230
+ // editor-value normalization: the Webcake EDITOR does not store every numeric
231
+ // style as a number. Confirmed write paths in landing_page_backend/assets/editor:
232
+ // • fontSize → "59" (main/panels/EditTextPanel.vue: updateStyle('fontSize', e.target.value))
233
+ // "13px" / "11px" / "70" (main/pickers/*.vue seed values)
234
+ // • height → "600" (main/traits/SizeAndPosition.vue handleBlur: e.target.value)
235
+ // • borderWidth→ "1" / "0px"
236
+ // • opacity → "50%" (main/traits/Layer.vue: updateStyle('opacity', val + '%'))
237
+ // • top/left → "unset"
238
+ // The published renderer copes (landing_page_build/render/build/exportCss.js
239
+ // parseInt()s the KEY_PREFIX_PIXEL group and string-concatenates '+ "px"' for
240
+ // top/left/width/height), so these pages are perfectly valid — but the MCP
241
+ // schema demanded numbers, so ONE manual tweak in the editor locked the page out
242
+ // of every MCP edit tool. That is the bug this pass removes.
243
+ //
244
+ // Fix: after every expand pass, coerce a unit-less or px-suffixed numeric string
245
+ // back to a number for the keys the renderer treats as bare px numbers, and turn
246
+ // an editor percent opacity into the 0–1 fraction. Values the coercion cannot
247
+ // read (`"unset"`, `"auto"`, `"100%"`) are left alone — the schema accepts them
248
+ // and validate.ts warns where the renderer would choke. Deterministic +
249
+ // idempotent, so the expand(compact(x)) == expand(x) invariant holds.
250
+ // ---------------------------------------------------------------------------
251
+ /** Style keys the renderer emits as bare px numbers (or parseInt()s). */
252
+ const NUMERIC_STYLE_KEYS = new Set(["top", "left", "width", "height", "zIndex", "fontSize", "borderWidth"]);
253
+ /** Per-breakpoint config keys the renderer appends "px" to / uses as numbers. */
254
+ const NUMERIC_CONFIG_KEYS = new Set([
255
+ "virtualHeight", "column", "row", "slideWidth", "iconSize", "iconTop", "linePaddingLeft",
256
+ "topBgImage", "leftBgImage", "widthBgImage", "heightBgImage",
257
+ "stickyTop", "stickyLeft", "stickyRight", "stickyBottom",
258
+ ]);
259
+ /** A number written as a string, with an optional "px" suffix: "59", " 12.5 ", "13px". */
260
+ const NUMERIC_PX_STRING = /^\s*-?\d+(?:\.\d+)?\s*(?:px)?\s*$/i;
261
+ /** "59" | "13px" -> 59 | 13. Anything else (including numbers) passes through. */
262
+ function numFromEditorString(v) {
263
+ if (typeof v !== "string" || !NUMERIC_PX_STRING.test(v))
264
+ return v;
265
+ const n = parseFloat(v);
266
+ return Number.isFinite(n) ? n : v;
267
+ }
268
+ /** "50%" -> 0.5 (the editor's Layer trait writes percent); else numeric-string coercion. */
269
+ function opacityFromEditorString(v) {
270
+ if (typeof v !== "string")
271
+ return v;
272
+ const pct = v.trim().match(/^(-?\d+(?:\.\d+)?)\s*%$/);
273
+ if (pct) {
274
+ const n = parseFloat(pct[1]) / 100;
275
+ return Number.isFinite(n) ? n : v;
276
+ }
277
+ return numFromEditorString(v);
278
+ }
279
+ /** Walk a tree node and coerce editor-written numeric strings in-place (mutates). */
280
+ function normalizeEditorValues(node) {
281
+ if (!node || typeof node !== "object")
282
+ return;
283
+ for (const bp of ["desktop", "mobile"]) {
284
+ const rbp = node.responsive?.[bp];
285
+ if (!rbp || typeof rbp !== "object")
286
+ continue;
287
+ const styles = rbp.styles;
288
+ if (styles && typeof styles === "object") {
289
+ for (const key of NUMERIC_STYLE_KEYS) {
290
+ if (styles[key] !== undefined)
291
+ styles[key] = numFromEditorString(styles[key]);
292
+ }
293
+ if (styles.opacity !== undefined && styles.opacity !== null) {
294
+ styles.opacity = opacityFromEditorString(styles.opacity);
295
+ }
296
+ }
297
+ const config = rbp.config;
298
+ if (config && typeof config === "object") {
299
+ for (const key of NUMERIC_CONFIG_KEYS) {
300
+ if (config[key] !== undefined)
301
+ config[key] = numFromEditorString(config[key]);
302
+ }
303
+ const anim = config.animation;
304
+ if (anim && typeof anim === "object") {
305
+ for (const key of ["delay", "duration"]) {
306
+ if (anim[key] !== undefined && anim[key] !== null)
307
+ anim[key] = numFromEditorString(anim[key]);
308
+ }
309
+ }
310
+ }
311
+ }
312
+ if (Array.isArray(node.children)) {
313
+ for (const child of node.children)
314
+ normalizeEditorValues(child);
315
+ }
316
+ }
317
+ /** settings.width_section carries the canvas width the coords live in — keep it numeric. */
318
+ function normalizeSettings(source) {
319
+ const ws = source?.settings?.width_section;
320
+ if (!ws || typeof ws !== "object")
321
+ return;
322
+ for (const bp of ["desktop", "mobile"]) {
323
+ if (ws[bp] !== undefined)
324
+ ws[bp] = numFromEditorString(ws[bp]);
325
+ }
326
+ }
229
327
  /** Apply all post-expand normalizations to every node in a page source. */
230
328
  function normalizeSource(source) {
231
329
  if (!source || typeof source !== "object")
@@ -233,6 +331,7 @@ function normalizeSource(source) {
233
331
  for (const arr of ["page", "popup", "dynamic_pages"]) {
234
332
  if (Array.isArray(source[arr])) {
235
333
  for (const node of source[arr]) {
334
+ normalizeEditorValues(node);
236
335
  normalizeMisplacedAnimation(node);
237
336
  normalizeImageBlocks(node);
238
337
  normalizeBorderRadius(node);
@@ -240,6 +339,7 @@ function normalizeSource(source) {
240
339
  }
241
340
  }
242
341
  }
342
+ normalizeSettings(source);
243
343
  return source;
244
344
  }
245
345
  export const landingDomain = {
@@ -264,7 +364,18 @@ export const landingDomain = {
264
364
  },
265
365
  compact: (input) => {
266
366
  try {
267
- return compactSource(coercePage(input), createElement);
367
+ // Normalize FIRST (on a clone, so a caller's fetched tree is never mutated):
368
+ // a page hand-tweaked in the editor stores fontSize as "59" and height as
369
+ // "600", and the model should READ the canonical number it is asked to
370
+ // WRITE. Normalizing before compaction also lets a value that merely
371
+ // differs from the seed by its type ("20" vs 20) compact away.
372
+ const normalized = structuredClone(coercePage(input));
373
+ for (const arr of ["page", "popup", "dynamic_pages"]) {
374
+ if (Array.isArray(normalized?.[arr]))
375
+ normalized[arr].forEach(normalizeEditorValues);
376
+ }
377
+ normalizeSettings(normalized);
378
+ return compactSource(normalized, createElement);
268
379
  }
269
380
  catch {
270
381
  return input; // bad JSON — return as-is
@@ -15,7 +15,7 @@ RULES (follow for every request):
15
15
  - BUILD THE SOURCE IN ONE PASS — gather everything you need BEFORE assembling the source, then build the FULL tree once. BATCH the reads: when a section needs several element types (section + text-block + image-block + button + form + input), call get_element({types:[…]}) ONCE instead of one call per type — same for images, call search_images({queries:[…]}) ONCE with one query per image slot (it dedups + parallelizes and returns one best photo per query). Across MULTIPLE pages in one conversation: reusing skeletons you already fetched is correct, but call get_element for any type you have NOT already fetched in this conversation — NEVER author an unfamiliar type from memory; and if the earlier skeletons are no longer in your context (long conversation, compacted history), re-fetch before building. Do NOT interleave get_element calls between create_page previews and rebuild. create_page/update_page take the entire source as input, so each call re-ships the whole page — re-previewing repeatedly wastes the request.
16
16
  - create_page and update_page DEFAULT to dry_run=true (a safety net for ambiguous requests). When the user's intent is clear AND validate_page already passed (no errors, warnings fixed), SKIP the dry-run and call with dry_run=false directly — saves one round-trip. Use dry_run=true only when (a) the request is ambiguous about target/content, (b) the user explicitly asks to "preview" or "xem trước", (c) this is an update_page that overwrites significant existing content, or (d) you genuinely need to inspect the redacted payload. Never loop dry-runs to "check" the source — validate_page is the validator. Do not run dry-run then dry-run again before the real write.
17
17
  - LARGE PAGES (4+ sections) — build INCREMENTALLY to avoid the giant single create_page payload that can drop the connection: create_page with a SMALL skeleton (empty/near-empty page) to get a page_id, then call add_section once per section (each call ships ONLY that section; the backend appends it server-side and rejects duplicate ids — no whole-source get+put). Small pages can still go in one create_page pass.
18
- - EDIT existing pages surgically: find_pages (locate the page by name/domain/id when you don't already have a page_id) → get_page → change ONLY what was asked → keep every other element, its id, and coordinates. For a SMALL edit, PREFER patch_page over update_page: send only the changed elements by id (ops: update/replace/remove/add) instead of re-shipping the whole tree — the MCP fetches the live source, merges, validates and saves server-side. Use update_page only when you're rewriting most of the page. Never regenerate the whole tree for a small change.
18
+ - EDIT existing pages surgically: find_pages (locate the page by name/domain/id when you don't already have a page_id) → get_page → change ONLY what was asked → keep every other element, its id, and coordinates. For a SMALL edit, PREFER patch_page over update_page: send only the changed elements by id (ops: update/replace/remove/add) instead of re-shipping the whole tree — the MCP fetches the live source, merges, validates and saves server-side. Use update_page only when you're rewriting most of the page. Never regenerate the whole tree for a small change. CONCURRENCY — the user may be editing the SAME page in the Webcake editor while you work: update_page replaces the whole stored tree, so a source read a while ago (or a cached draft_id, which can be hours old) would silently revert their changes. The server now checks this for you: get_page returns source_version, and update_page re-reads the page and REJECTS the save with reason:"page_changed_externally" (naming the element ids it would have deleted) when the live tree moved. When you see that, do NOT pass force:true on your own — either redo the edit with patch_page({ page_id, patches }), which merges into the live tree and can never revert anyone, or call get_page again, re-apply the change to the fresh tree, and save. Only use force:true after the user has explicitly said to discard the newer edits.
19
19
  - FIX-AFTER-ERROR / RETRY-AFTER-TIMEOUT (don't rebuild — this is the #1 time-waster): every mutating tool (create_page, update_page, add_section, patch_page) writes the payload to a draft cache BEFORE the network call and returns a draft_id. On validation failure, timeout, or any network error, the draft is kept — retry or fix without re-sending the full JSON:
20
20
  · create_page failed validation OR timed out → its error returns a draft_id (full source cached). Call patch_page({ draft_id, patches:[…], dry_run:false }) to fix ONLY the listed elements, or retry create_page({ draft_id, dry_run:false }) as-is after a timeout.
21
21
  · add_section failed validation, timed out, or returned dry_run=true → response returns a draft_id (section batch cached). Call patch_page({ draft_id, patches:[…], dry_run:false }) to fix elements and append, or retry patch_page({ draft_id, dry_run:false }) (no patches) to commit as-is.
@@ -97,16 +97,16 @@
97
97
  "description": "Per-breakpoint CSS. Positioning is absolute (px numbers). additionalProperties allowed for any camelCase CSS property.",
98
98
  "additionalProperties": true,
99
99
  "properties": {
100
- "top": { "type": "number", "description": "px, absolute within container. Omit on section." },
101
- "left": { "type": "number", "description": "px, absolute within container. Omit on section." },
102
- "width": { "type": "number", "description": "px." },
103
- "height": { "type": "number", "description": "px. Section uses this as canvas height." },
100
+ "top": { "type": ["number", "string", "null"], "description": "px, absolute within container. EMIT A NUMBER. Read-tolerance: the editor can save a numeric string (\"120\") or the keyword \"unset\" — numeric/px strings are normalized back to numbers before validation. Omit on section." },
101
+ "left": { "type": ["number", "string", "null"], "description": "px, absolute within container. EMIT A NUMBER. Read-tolerance: same as top (numeric string or \"unset\"). Omit on section." },
102
+ "width": { "type": ["number", "string", "null"], "description": "px. EMIT A NUMBER — the renderer appends \"px\" verbatim, so a value that already carries a unit would render as \"120pxpx\". Read-tolerance: unit-less/px strings the editor saves are normalized to numbers." },
103
+ "height": { "type": ["number", "string", "null"], "description": "px. Section uses this as canvas height. EMIT A NUMBER (the editor saves the string \"600\" when the height box loses focus — normalized on read)." },
104
104
  "position": { "type": "string", "enum": ["absolute", "relative", "fixed", "static"] },
105
- "zIndex": { "type": "number" },
105
+ "zIndex": { "type": ["number", "string", "null"], "description": "Stacking order. EMIT A NUMBER; numeric strings are normalized." },
106
106
  "background": { "type": "string", "description": "rgba(...) or gradient." },
107
107
  "backgroundImage": { "type": "string", "description": "url(...)." },
108
108
  "color": { "type": "string", "description": "rgba(r,g,b,a)." },
109
- "fontSize": { "type": "number", "description": "px." },
109
+ "fontSize": { "type": ["number", "string"], "description": "px. EMIT A NUMBER. Read-tolerance: the editor saves \"59\" (inline text-resize box) and \"13px\" (element pickers); the renderer parseInt()s it, and the MCP normalizes both back to a number." },
110
110
  "fontFamily": { "type": "string" },
111
111
  "fontWeight": { "type": ["string", "number"] },
112
112
  "fontStyle": { "type": "string" },
@@ -115,12 +115,12 @@
115
115
  "letterSpacing": { "type": ["number", "string"] },
116
116
  "textTransform": { "type": "string" },
117
117
  "textDecoration": { "type": "string" },
118
- "borderStyle": { "type": "string", "enum": ["solid", "dashed", "dotted", "double", "none"] },
119
- "borderWidth": { "type": "number", "description": "px." },
118
+ "borderStyle": { "type": "string", "enum": ["none", "solid", "dashed", "dotted", "double", "groove", "ridge", "inset", "outset", "hidden"], "description": "The full set the editor's border-style dropdown offers (Border.vue)." },
119
+ "borderWidth": { "type": ["number", "string"], "description": "px. EMIT A NUMBER. Read-tolerance: the editor saves \"1\" / \"0px\"; parseInt()ed by the renderer and normalized here." },
120
120
  "borderColor": { "type": "string" },
121
121
  "borderRadius": { "type": ["string", "number"] },
122
122
  "boxShadow": { "type": "string" },
123
- "opacity": { "type": "number", "minimum": 0, "maximum": 1 },
123
+ "opacity": { "type": ["number", "string"], "description": "0–1. EMIT A NUMBER. Read-tolerance: the editor Layer trait saves a percent string (\"50%\") — normalized to the 0–1 fraction (0.5) before validation." },
124
124
  "mixBlendMode": { "type": "string" },
125
125
  "transform": { "type": "string" },
126
126
  "padding": { "type": ["number", "string"] },
@@ -139,26 +139,26 @@
139
139
  "additionalProperties": true,
140
140
  "properties": {
141
141
  "name": { "type": "string", "description": "animate.css name, or \"none\"." },
142
- "delay": { "type": "number" },
143
- "duration": { "type": "number" },
142
+ "delay": { "type": ["number", "string"] },
143
+ "duration": { "type": ["number", "string"] },
144
144
  "repeat": { "type": ["number", "null"] }
145
145
  }
146
146
  },
147
- "virtualHeight": { "type": "number" },
147
+ "virtualHeight": { "type": ["number", "string", "null"] },
148
148
  "overlay": { "type": "string", "description": "Overlay color rgba(...)." },
149
149
  "hiddenEffect": { "type": "object", "additionalProperties": true },
150
150
  "svgMask": { "type": "string" },
151
151
  "lock": { "type": "boolean" },
152
- "column": { "type": "number" },
153
- "row": { "type": "number" },
154
- "slideWidth": { "type": "number" },
155
- "iconSize": { "type": "number" },
156
- "iconTop": { "type": "number" },
157
- "linePaddingLeft": { "type": "number" },
158
- "topBgImage": { "type": "number" },
159
- "leftBgImage": { "type": "number" },
160
- "widthBgImage": { "type": "number" },
161
- "heightBgImage": { "type": "number" }
152
+ "column": { "type": ["number", "string", "null"] },
153
+ "row": { "type": ["number", "string", "null"] },
154
+ "slideWidth": { "type": ["number", "string", "null"] },
155
+ "iconSize": { "type": ["number", "string", "null"] },
156
+ "iconTop": { "type": ["number", "string", "null"] },
157
+ "linePaddingLeft": { "type": ["number", "string", "null"] },
158
+ "topBgImage": { "type": ["number", "string", "null"] },
159
+ "leftBgImage": { "type": ["number", "string", "null"] },
160
+ "widthBgImage": { "type": ["number", "string", "null"] },
161
+ "heightBgImage": { "type": ["number", "string", "null"] }
162
162
  }
163
163
  },
164
164
  "responsive": {
@@ -203,8 +203,8 @@
203
203
  "id": { "type": "string", "description": "Event id (any string; ~8 chars in real data)." },
204
204
  "type": {
205
205
  "type": "string",
206
- "enum": ["click", "hover", "success", "unset"],
207
- "description": "Trigger."
206
+ "enum": ["click", "hover", "success", "error", "delay", "unset"],
207
+ "description": "Trigger. Matches the editor's own dropdown: click/hover on any element, success/error on a form, delay on anything (plus the legacy \"unset\")."
208
208
  },
209
209
  "action": {
210
210
  "type": "string",
@@ -352,6 +352,31 @@ export function validatePage(input) {
352
352
  `Valid examples: fadeInUp, slideInLeft, zoomIn, bounceIn, backInDown, flipInX, lightSpeedInLeft, rotateIn, rollIn, jackInTheBox.`);
353
353
  }
354
354
  }
355
+ // top/left/width/height are the ONE style group the renderer does NOT emit
356
+ // verbatim: exportCss.js strips them from the generic loop (PROPERTY_NOT_SHOW)
357
+ // and re-emits them as `${getStyle(el, mode, key)}px`. A value that already
358
+ // carries a unit therefore renders as "100%px"/"autopx" — invalid CSS the
359
+ // browser drops, so the element collapses or jumps to 0. Plain numbers and
360
+ // numeric strings are fine (expand() normalizes the latter to numbers first).
361
+ for (const bp of ["desktop", "mobile"]) {
362
+ const styles = node.responsive?.[bp]?.styles;
363
+ if (!styles || typeof styles !== "object")
364
+ continue;
365
+ // A sticky element takes exportCss.js handleStyleSticky(), which positions
366
+ // it from config.sticky* and never reads styles.top/left — the editor
367
+ // deliberately parks "unset" there, so those two are not a problem here.
368
+ const isSticky = !!node.responsive?.[bp]?.config?.sticky;
369
+ for (const key of ["top", "left", "width", "height"]) {
370
+ if (isSticky && (key === "top" || key === "left"))
371
+ continue;
372
+ const raw = styles[key];
373
+ if (typeof raw !== "string" || raw.trim() === "")
374
+ continue;
375
+ warnings.push(`${path} (${type ?? "?"}) [${bp}]: styles.${key}="${raw}" is not a plain px number — ` +
376
+ `the renderer emits this property as \`${key}:${raw}px\`, which the browser drops. ` +
377
+ `Set it to a NUMBER: patch_page({op:'update',id:'${node.id ?? "?"}',styles:{${bp}:{${key}:<px>}}}).`);
378
+ }
379
+ }
355
380
  // styles.opacity < 1 renders the element permanently faded (exportCss.js emits opacity:<v>)
356
381
  for (const bp of ["desktop", "mobile"]) {
357
382
  const styles = node.responsive?.[bp]?.styles;
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Optimistic-concurrency guard for whole-source overwrites.
3
+ *
4
+ * THE PROBLEM. `update_page` (and a committed `kind:'update'` draft) REPLACES a
5
+ * page's stored source with a tree the model read earlier — from `get_page`, or
6
+ * from a draft the MCP cached minutes/hours ago. If the user opens the Webcake
7
+ * editor in between and moves an element, retypes a headline or adds a section,
8
+ * that overwrite silently reverts their work: the snapshot wins and the UI edit
9
+ * is gone. The backend cannot help — `/api/v1/ai/update_page_source` is a blind
10
+ * `update_source(record, %{source: …})` with no version column and no ETag
11
+ * (LandingPageWeb.V1.AiController.update_page_source), so last-write-wins is the
12
+ * only semantics it offers.
13
+ *
14
+ * THE FIX. Fingerprint the STORED source and remember it per page:
15
+ * - every READ we do (`get_page`, the live read inside `patch_page`) records a
16
+ * TRUSTED baseline — the exact bytes the backend just handed us;
17
+ * - every WRITE records an UNTRUSTED baseline — our prediction of what the page
18
+ * now holds. It should match a later read, but the backend re-encodes the JSON
19
+ * on the way in and out, so a mismatch here must never be read as "someone
20
+ * else edited the page";
21
+ * - a server-side append (`add_section`) FORGETS it — the backend rewrote the
22
+ * tree behind our back, so nothing we hold is a baseline any more.
23
+ * Before a blind overwrite we re-read the page and compare (see decideOverwrite).
24
+ *
25
+ * The fingerprint is content-based (canonical key-sorted JSON → sha256), so it
26
+ * survives the backend's decode→re-encode round-trip and needs no schema change.
27
+ *
28
+ * The store is per-process and bounded. Losing it (restart, a second `serve`
29
+ * instance) is safe: with no baseline the caller falls back to the element-id
30
+ * loss check, which still catches the destructive case.
31
+ */
32
+ import { createHash } from "node:crypto";
33
+ /** Canonical JSON: object keys sorted recursively so two equal trees hash equal. */
34
+ function canonical(v) {
35
+ if (Array.isArray(v))
36
+ return v.map(canonical);
37
+ if (v && typeof v === "object") {
38
+ const out = {};
39
+ for (const k of Object.keys(v).sort())
40
+ out[k] = canonical(v[k]);
41
+ return out;
42
+ }
43
+ return v;
44
+ }
45
+ /** Short content fingerprint of a page source (object or JSON string). */
46
+ export function sourceFingerprint(source) {
47
+ let v = source;
48
+ if (typeof v === "string") {
49
+ try {
50
+ v = JSON.parse(v);
51
+ }
52
+ catch {
53
+ /* not JSON — hash the raw string */
54
+ }
55
+ }
56
+ return createHash("sha256").update(JSON.stringify(canonical(v) ?? null)).digest("hex").slice(0, 16);
57
+ }
58
+ /** Every element id in a source tree (page + popup + dynamic_pages, recursively). */
59
+ export function collectElementIds(source) {
60
+ const ids = new Set();
61
+ const walk = (node) => {
62
+ if (!node || typeof node !== "object")
63
+ return;
64
+ if (typeof node.id === "string" && typeof node.type === "string")
65
+ ids.add(node.id);
66
+ if (Array.isArray(node.children))
67
+ for (const c of node.children)
68
+ walk(c);
69
+ };
70
+ let v = source;
71
+ if (typeof v === "string") {
72
+ try {
73
+ v = JSON.parse(v);
74
+ }
75
+ catch {
76
+ return ids;
77
+ }
78
+ }
79
+ for (const arr of ["page", "popup", "dynamic_pages"]) {
80
+ if (Array.isArray(v?.[arr]))
81
+ for (const n of v[arr])
82
+ walk(n);
83
+ }
84
+ return ids;
85
+ }
86
+ const MAX_PAGES = 100;
87
+ const versions = new Map();
88
+ /** Record what the page holds now, and whether we KNOW it (read) or predict it (write). */
89
+ export function rememberPageVersion(pageId, fp, origin) {
90
+ if (!pageId)
91
+ return;
92
+ versions.delete(pageId); // re-insert so Map iteration order = LRU
93
+ versions.set(pageId, { fp, origin, at: Date.now() });
94
+ while (versions.size > MAX_PAGES) {
95
+ const oldest = versions.keys().next().value;
96
+ if (oldest === undefined)
97
+ break;
98
+ versions.delete(oldest);
99
+ }
100
+ }
101
+ /** Drop the baseline — the stored tree changed in a way we cannot predict. */
102
+ export function forgetPageVersion(pageId) {
103
+ if (pageId)
104
+ versions.delete(pageId);
105
+ }
106
+ /** The baseline we hold for this page, or undefined if we hold none. */
107
+ export function lastKnownPageVersion(pageId) {
108
+ if (!pageId)
109
+ return undefined;
110
+ const v = versions.get(pageId);
111
+ return v ? { fp: v.fp, origin: v.origin } : undefined;
112
+ }
113
+ /** Test hook — clears the baseline store. */
114
+ export function resetPageVersions() {
115
+ versions.clear();
116
+ }
117
+ /**
118
+ * Pure verdict for "may this whole-source overwrite proceed?" — the network read
119
+ * lives in the caller so this stays testable.
120
+ *
121
+ * trusted baseline matches live → allow (any deletions are deliberate)
122
+ * trusted baseline differs → refuse: edited outside this session
123
+ * no/untrusted baseline, live ids dropped → refuse: provable destruction
124
+ * no/untrusted baseline, nothing dropped → allow, flagged unverified
125
+ */
126
+ export function decideOverwrite(liveSource, incoming, baseline) {
127
+ const liveVersion = sourceFingerprint(liveSource);
128
+ if (baseline && baseline.fp === liveVersion)
129
+ return { allow: true, liveVersion };
130
+ const liveIds = collectElementIds(liveSource);
131
+ const incomingIds = collectElementIds(incoming);
132
+ const dropped = [...liveIds].filter((id) => !incomingIds.has(id));
133
+ // A stale READ baseline is proof the page moved under us — refuse even when the
134
+ // overwrite drops nothing, because it would still revert the edits it does touch.
135
+ if (baseline?.origin === "read") {
136
+ return { allow: false, reason: "page_changed_externally", liveVersion, baseVersion: baseline.fp, dropped };
137
+ }
138
+ // No baseline, or one we only PREDICTED after a write: a mismatch proves nothing,
139
+ // so fall back to the check that is always sound — does this save destroy content?
140
+ if (dropped.length === 0)
141
+ return { allow: true, liveVersion, unverified: true };
142
+ return { allow: false, reason: "unverified_overwrite", liveVersion, baseVersion: baseline?.fp, dropped };
143
+ }
144
+ // ---- version-keyed source cache -------------------------------------------
145
+ //
146
+ // The concurrency check must never be served from a cache — a cached answer
147
+ // cannot see an edit made after it was written, which is the whole bug. What IS
148
+ // cacheable is the SOURCE, validated by the backend's own version token: ask
149
+ // `GET /api/v1/ai/page_version` for `updated_at` (a few hundred bytes), and only
150
+ // re-download the tree when it moved. Unchanged page ⇒ no download at all; the
151
+ // freshness guarantee is identical because the token comes from the server.
152
+ //
153
+ // Entries are keyed by credentials as well as page id, so a hosted `serve`
154
+ // instance can never hand one caller a tree fetched with another caller's JWT.
155
+ // Bounded to a handful of pages — a source can be megabytes.
156
+ const MAX_CACHED_SOURCES = 6;
157
+ const sources = new Map();
158
+ /** Cache key: the page plus a short digest of the credentials it was fetched with. */
159
+ export function sourceCacheKey(pageId, jwt) {
160
+ const who = createHash("sha256").update(jwt ?? "").digest("hex").slice(0, 12);
161
+ return `${who}:${pageId}`;
162
+ }
163
+ /** Store a full getPageSource outcome under the backend version it was read at. */
164
+ export function cachePageSource(key, version, result) {
165
+ if (!version)
166
+ return; // no server token ⇒ nothing to validate a hit against
167
+ sources.delete(key);
168
+ sources.set(key, { version, result, at: Date.now() });
169
+ while (sources.size > MAX_CACHED_SOURCES) {
170
+ const oldest = sources.keys().next().value;
171
+ if (oldest === undefined)
172
+ break;
173
+ sources.delete(oldest);
174
+ }
175
+ }
176
+ /** The version a cached entry was read at, or undefined when nothing is cached. */
177
+ export function cachedPageSourceVersion(key) {
178
+ return sources.get(key)?.version;
179
+ }
180
+ /** The cached outcome IF it was read at exactly this version, else undefined. */
181
+ export function cachedPageSource(key, version) {
182
+ if (!version)
183
+ return undefined;
184
+ const hit = sources.get(key);
185
+ if (!hit || hit.version !== version)
186
+ return undefined;
187
+ sources.delete(key); // refresh LRU position
188
+ sources.set(key, { ...hit, at: Date.now() });
189
+ return hit.result;
190
+ }
191
+ /** Drop a page's cached source (e.g. after our own write changed it). */
192
+ export function dropCachedPageSource(key) {
193
+ sources.delete(key);
194
+ }
195
+ /** Test hook — clears the source cache. */
196
+ export function resetPageSourceCache() {
197
+ sources.clear();
198
+ }
@@ -57,6 +57,54 @@ export function normalizePhoto(p) {
57
57
  src: p?.src && typeof p.src === "object" ? p.src : {},
58
58
  };
59
59
  }
60
+ /**
61
+ * Delivered pixel size of ONE Pexels src-variant URL. Pexels encodes the size in
62
+ * the query string (`w`, `h`, and `dpr` for retina): `large`/`large2x` carry
63
+ * `w`+`h` (large2x adds `dpr=2` → the file is twice as many pixels), `medium`/
64
+ * `small` carry only `h` (width follows the native aspect ratio), and `original`
65
+ * has NO query params → it is the full native resolution. `dpr` multiplies both
66
+ * sides because the served file really is that many pixels. Pure + defensive:
67
+ * an unparseable URL or a variant with no size hint falls back to native w/h.
68
+ */
69
+ export function variantPixels(url, nativeW, nativeH) {
70
+ const aspect = nativeW > 0 && nativeH > 0 ? nativeW / nativeH : 1;
71
+ let q;
72
+ try {
73
+ q = new URL(url).searchParams;
74
+ }
75
+ catch {
76
+ return { w: nativeW || 0, h: nativeH || 0 };
77
+ }
78
+ const dprRaw = parseInt(q.get("dpr") ?? "1", 10);
79
+ const dpr = Number.isFinite(dprRaw) && dprRaw > 0 ? dprRaw : 1;
80
+ const wRaw = parseInt(q.get("w") ?? "", 10);
81
+ const hRaw = parseInt(q.get("h") ?? "", 10);
82
+ const hasW = Number.isFinite(wRaw) && wRaw > 0;
83
+ const hasH = Number.isFinite(hRaw) && hRaw > 0;
84
+ if (!hasW && !hasH)
85
+ return { w: nativeW || 0, h: nativeH || 0 }; // original / no size hint
86
+ const baseW = hasW ? wRaw : Math.round(hRaw * aspect);
87
+ const baseH = hasH ? hRaw : Math.round(wRaw / aspect);
88
+ return { w: baseW * dpr, h: baseH * dpr };
89
+ }
90
+ /** Map every src variant of a photo to its delivered {w,h} in px (see variantPixels). */
91
+ export function annotateVariantSizes(photo) {
92
+ const out = {};
93
+ for (const [variant, url] of Object.entries(photo.src ?? {})) {
94
+ if (typeof url === "string" && url)
95
+ out[variant] = variantPixels(url, photo.width, photo.height);
96
+ }
97
+ return out;
98
+ }
99
+ /**
100
+ * How to pick the RIGHT variant: match the delivered width to the slot's rendered
101
+ * width — too small pixelates ("vỡ ảnh"), too big bloats the page ("nặng trang").
102
+ * Returned in search_images responses so the model chooses by size, not just topic.
103
+ */
104
+ export const IMAGE_SIZE_GUIDE = "Match the src variant's delivered WIDTH (see each photo's `sizes` map) to the slot's RENDERED width — aim for ~1–2× it (extra headroom = crisp on retina), then STOP. " +
105
+ "Rules of thumb on the 960/1200 canvas: full-bleed hero/banner (~900–1200px wide) → src.large (940px) or src.large2x (1880px, retina); half-hero / product shot (~450–650px) → src.large or src.medium; feature card / thumbnail (~260–360px) → src.medium (~350px); avatar / logo / small icon (~64–120px) → src.tiny (280px). " +
106
+ "NEVER stretch a small variant across a big slot — upscaling looks broken/pixelated ('vỡ ảnh'). NEVER drop src.original (full-res, often several MB) or an oversized variant into a small card — it makes the page slow and heavy ('nặng trang'). " +
107
+ "Also check the photo's NATIVE width/height: if a photo's native width is smaller than the slot, it cannot fill it crisply — choose a higher-resolution photo (or a smaller slot) rather than upscaling.";
60
108
  /** Build the shared query string for both the direct Pexels call and the proxy. */
61
109
  export function buildSearchQuery(params) {
62
110
  const q = new URLSearchParams();