webcake-storefront-mcp 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builder/native-first.js +7 -4
- package/dist/builder/page-code.js +150 -0
- package/dist/changelog.json +7 -7
- package/dist/tools/builder.js +20 -2
- package/dist/tools/families.js +2 -2
- package/dist/tools/page-code.js +114 -0
- package/dist/tools/pages.js +14 -8
- package/dist/tools/registry.js +2 -0
- package/package.json +1 -1
|
@@ -52,6 +52,9 @@ page. Go down this list and stop at the FIRST step that works:
|
|
|
52
52
|
api.get_SizeAdvice({ height }).then((r) => {
|
|
53
53
|
document.querySelector(".size-result p").textContent = r.size;
|
|
54
54
|
});
|
|
55
|
+
Code only ONE page needs (a landing page's calculator, a one-off effect) goes in that page's
|
|
56
|
+
code — update_page_custom_code (CSS / JS / head / body for that page only); site-wide code is
|
|
57
|
+
update_site_custom_code. get_page_custom_code lists the #ids and classes the code can target.
|
|
55
58
|
5. Third-party snippets (tracking, chat, a widget): the smallest code_before_head / embed that works.
|
|
56
59
|
A visual detail no style property can do: a few lines of CSS on a custom_class.
|
|
57
60
|
|
|
@@ -122,7 +125,7 @@ export function codeUsage(values) {
|
|
|
122
125
|
/** Judge a write by what it ADDS: shrinking or swapping code on an already-large site always passes,
|
|
123
126
|
* so a site can move off custom code step by step. Past the ceiling nothing may grow: small fixes
|
|
124
127
|
* used to be allowed and ratcheted a site to 90k chars of CSS, which then failed to publish. */
|
|
125
|
-
export function checkSiteCode(before, changes) {
|
|
128
|
+
export function checkSiteCode(before, changes, { label = "Site", budget = CODE_BUDGET } = {}) {
|
|
126
129
|
const after = { ...before, ...changes };
|
|
127
130
|
const hard = [];
|
|
128
131
|
const soft = [];
|
|
@@ -134,11 +137,11 @@ export function checkSiteCode(before, changes) {
|
|
|
134
137
|
const { old, now } = texts(kind);
|
|
135
138
|
if (now.length <= old.length)
|
|
136
139
|
continue;
|
|
137
|
-
const { soft: softLimit, hard: hardLimit } =
|
|
140
|
+
const { soft: softLimit, hard: hardLimit } = budget[kind];
|
|
138
141
|
if (now.length > hardLimit)
|
|
139
|
-
hard.push(
|
|
142
|
+
hard.push(`${label} ${kind} would reach ${now.length} chars (ceiling ${hardLimit}). That is an app, not a snippet: move UI to native elements, data to a collection, logic to an HTTP function.`);
|
|
140
143
|
else if (now.length > softLimit)
|
|
141
|
-
soft.push(
|
|
144
|
+
soft.push(`${label} ${kind} would reach ${now.length} chars (budget ${softLimit}).`);
|
|
142
145
|
}
|
|
143
146
|
for (const [field, value] of Object.entries(changes)) {
|
|
144
147
|
if (PASTED_DOCUMENT.test(String(value || "")) && !PASTED_DOCUMENT.test(String(before[field] || "")))
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Custom code of ONE page — page.settings.custom_code, the same four slots as the site's code.
|
|
2
|
+
// builderx_api (PageUtils.get_page_custom_code) renders it after the site's code on that page
|
|
3
|
+
// only: CSS/head code in <head>, body code after <body>, JS in its own <script> at the end, so a
|
|
4
|
+
// broken page script can't take the site script down with it. Settings are copied to the
|
|
5
|
+
// published page on publish_site; the preview reads them straight away.
|
|
6
|
+
import { Script } from "node:vm";
|
|
7
|
+
import { SITE_CODE_FIELDS } from "./native-first.js";
|
|
8
|
+
export const PAGE_CODE_FIELDS = SITE_CODE_FIELDS;
|
|
9
|
+
/** Per page, in chars. Above `soft` a write must name its native gap; past `hard` it is refused. */
|
|
10
|
+
export const PAGE_CODE_BUDGET = {
|
|
11
|
+
script: { soft: 15_000, hard: 50_000 },
|
|
12
|
+
css: { soft: 10_000, hard: 30_000 },
|
|
13
|
+
};
|
|
14
|
+
export const PAGE_CODE_GUIDE = `## Per-page custom code (last resort — NATIVE FIRST still applies)
|
|
15
|
+
Use it when the element schema can't express what the user asked for ON THIS PAGE ONLY (a landing
|
|
16
|
+
page's one-off animation, a calculator that writes into native elements, a tracking event for this
|
|
17
|
+
page). Anything every page needs belongs in the site code (update_site_custom_code); anything an
|
|
18
|
+
element setting can do belongs in that setting.
|
|
19
|
+
Slots (rendered on this page only, after the site's code):
|
|
20
|
+
- code_custom_css — CSS, wrapped in <style> for you. Target #ELEMENT-ID (ids from targets) or a
|
|
21
|
+
specials.custom_class you set on a native element. Media queries: match the site breakpoints.
|
|
22
|
+
- code_custom_javascript — plain JS, NO <script> tag (it gets its own). Runs at the end of <body>,
|
|
23
|
+
after the page's HTML exists; content loaded later (product grids, carts) needs a
|
|
24
|
+
MutationObserver or a retry. Wrap in an IIFE; never document.write.
|
|
25
|
+
- code_before_head — <script src>/<link>/<meta> for this page (e.g. a library only this page uses).
|
|
26
|
+
- code_before_body — markup after the page's content, before its scripts (same spot as the
|
|
27
|
+
site's code_before_body): a noscript pixel, a mount point for a widget.
|
|
28
|
+
Rules: write into native elements (textContent, classList) instead of building UI in JS; data comes
|
|
29
|
+
from a collection / HTTP function (webcake-fn), never hard-coded lists. Syntax is checked before
|
|
30
|
+
saving; #ids that aren't on the page are flagged. Preview right away; publish_site to go live.`;
|
|
31
|
+
/** The page's custom code from its settings (object or JSON string), only known slots, only strings. */
|
|
32
|
+
export function readPageCode(settings) {
|
|
33
|
+
let s = settings;
|
|
34
|
+
if (typeof s === "string") {
|
|
35
|
+
try {
|
|
36
|
+
s = JSON.parse(s);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
s = null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const code = s && typeof s === "object" ? s.custom_code : null;
|
|
43
|
+
const out = {};
|
|
44
|
+
if (code && typeof code === "object")
|
|
45
|
+
for (const f of PAGE_CODE_FIELDS)
|
|
46
|
+
if (typeof code[f] === "string" && code[f].trim())
|
|
47
|
+
out[f] = code[f];
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
/** Merge an edit into the current code. `append` adds after what is there; "" clears a slot.
|
|
51
|
+
* A <script> wrapper around code_custom_javascript is removed (the renderer adds its own). */
|
|
52
|
+
export function mergePageCode(before, input, mode = "replace") {
|
|
53
|
+
const after = { ...before };
|
|
54
|
+
const notes = [];
|
|
55
|
+
for (const f of PAGE_CODE_FIELDS) {
|
|
56
|
+
let v = input[f];
|
|
57
|
+
if (v === undefined)
|
|
58
|
+
continue;
|
|
59
|
+
if (f === "code_custom_javascript") {
|
|
60
|
+
const m = /^\s*<script\b[^>]*>([\s\S]*)<\/script>\s*$/i.exec(v);
|
|
61
|
+
if (m && !/<script\b/i.test(m[1])) {
|
|
62
|
+
v = m[1].trim();
|
|
63
|
+
notes.push("code_custom_javascript: removed the <script> wrapper — the page renders its own tag.");
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const next = mode === "append" && before[f] && v ? `${before[f]}\n${v}` : v;
|
|
67
|
+
if (next.trim())
|
|
68
|
+
after[f] = next;
|
|
69
|
+
else
|
|
70
|
+
delete after[f];
|
|
71
|
+
}
|
|
72
|
+
return { after, notes };
|
|
73
|
+
}
|
|
74
|
+
const ELEMENT_ID = /^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*-[A-Za-z0-9]{6,}$/;
|
|
75
|
+
/** Syntax and target checks. errors block the save (a syntax error kills the page's script);
|
|
76
|
+
* warnings point at selectors that match nothing on the page. */
|
|
77
|
+
export function lintPageCode(code, pageIds) {
|
|
78
|
+
const errors = [];
|
|
79
|
+
const warnings = [];
|
|
80
|
+
const compile = (src, where) => {
|
|
81
|
+
try {
|
|
82
|
+
new Script(src, { filename: where });
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
const line = /:(\d+)/.exec(String(e?.stack || ""))?.[1];
|
|
86
|
+
errors.push(`${where}: ${e?.name || "SyntaxError"}: ${e?.message}${line ? ` (line ${line})` : ""} — the whole script would fail to run.`);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
if (code.code_custom_javascript)
|
|
90
|
+
compile(code.code_custom_javascript, "code_custom_javascript");
|
|
91
|
+
for (const f of ["code_before_head", "code_before_body"]) {
|
|
92
|
+
const html = code[f];
|
|
93
|
+
if (!html)
|
|
94
|
+
continue;
|
|
95
|
+
let i = 0;
|
|
96
|
+
for (const m of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
|
|
97
|
+
i++;
|
|
98
|
+
if (/\bsrc\s*=/.test(m[1]) || /type\s*=\s*["']?(?!text\/javascript|module|application\/javascript)[^"'\s>]+/i.test(m[1]))
|
|
99
|
+
continue;
|
|
100
|
+
if (m[2].trim())
|
|
101
|
+
compile(m[2], `${f} <script> #${i}`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const css = code.code_custom_css;
|
|
105
|
+
if (css) {
|
|
106
|
+
const body = css.replace(/^\s*<style[^>]*>|<\/style>\s*$/gi, "").replace(/\/\*[\s\S]*?\*\//g, "");
|
|
107
|
+
let depth = 0;
|
|
108
|
+
for (const ch of body) {
|
|
109
|
+
if (ch === "{")
|
|
110
|
+
depth++;
|
|
111
|
+
else if (ch === "}" && --depth < 0)
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
if (depth !== 0)
|
|
115
|
+
errors.push(`code_custom_css: unbalanced braces (${depth > 0 ? "missing }" : "extra }"}) — every rule after it would be dropped.`);
|
|
116
|
+
}
|
|
117
|
+
// Element ids used as selectors / getElementById that aren't on this page.
|
|
118
|
+
const used = new Set();
|
|
119
|
+
const all = PAGE_CODE_FIELDS.map((f) => code[f] || "").join("\n");
|
|
120
|
+
for (const m of all.matchAll(/#([A-Za-z][\w-]*)|getElementById\(\s*["'`]([\w-]+)["'`]\s*\)/g)) {
|
|
121
|
+
const id = m[1] || m[2];
|
|
122
|
+
if (ELEMENT_ID.test(id))
|
|
123
|
+
used.add(id);
|
|
124
|
+
}
|
|
125
|
+
const missing = [...used].filter((id) => !pageIds.has(id));
|
|
126
|
+
if (missing.length)
|
|
127
|
+
warnings.push(`No element with id ${missing.slice(0, 8).map((x) => `#${x}`).join(", ")} on this page — the rule/script will match nothing. Pick ids from targets.`);
|
|
128
|
+
return { errors, warnings };
|
|
129
|
+
}
|
|
130
|
+
/** What code can aim at on this page: every node's id, type, custom_class (compact, capped). */
|
|
131
|
+
export function codeTargets(source, limit = 300) {
|
|
132
|
+
const out = [];
|
|
133
|
+
const ids = new Set();
|
|
134
|
+
const walk = (n) => {
|
|
135
|
+
if (!n || typeof n !== "object")
|
|
136
|
+
return;
|
|
137
|
+
if (n.id) {
|
|
138
|
+
ids.add(n.id);
|
|
139
|
+
if (out.length < limit) {
|
|
140
|
+
const cls = n.specials?.custom_class ? ` .${String(n.specials.custom_class).trim().split(/\s+/).join(".")}` : "";
|
|
141
|
+
out.push(`#${n.id} ${n.type || "?"}${cls}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
for (const c of Array.isArray(n.children) ? n.children : [])
|
|
145
|
+
walk(c);
|
|
146
|
+
};
|
|
147
|
+
for (const s of Array.isArray(source?.sections) ? source.sections : [])
|
|
148
|
+
walk(s);
|
|
149
|
+
return { targets: out, ids, total: ids.size, truncated: ids.size > out.length };
|
|
150
|
+
}
|
package/dist/changelog.json
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"v": "2.1.0",
|
|
4
|
+
"d": "19/11/2026",
|
|
5
|
+
"type": "Added",
|
|
6
|
+
"en": "New get_page_custom_code and update_page_custom_code tools (family site_code) read and write custom code for ONE page — code_custom_css,…",
|
|
7
|
+
"vi": "Hai tool mới get_page_custom_code và update_page_custom_code (nhóm site_code) đọc và ghi custom code cho MỘT trang — code_custom_css,…"
|
|
8
|
+
},
|
|
2
9
|
{
|
|
3
10
|
"v": "2.0.0",
|
|
4
11
|
"d": "19/11/2026",
|
|
@@ -33,12 +40,5 @@
|
|
|
33
40
|
"type": "Added",
|
|
34
41
|
"en": "New preview_page tool screenshots the saved (unpublished) draft at desktop and mobile widths through the editor's own preview host, so a page can be…",
|
|
35
42
|
"vi": "Tool mới preview_page chụp ảnh bản nháp đã lưu (chưa publish) ở cả độ rộng máy tính và điện thoại qua host xem trước của chính editor, nhờ đó có thể…"
|
|
36
|
-
},
|
|
37
|
-
{
|
|
38
|
-
"v": "1.38.0",
|
|
39
|
-
"d": "05/11/2026",
|
|
40
|
-
"type": "Changed",
|
|
41
|
-
"en": "The install command no longer asks any questions: it opens the prod browser connect page and configures every AI app it detects on the machine…",
|
|
42
|
-
"vi": "Lệnh install nay không còn hỏi gì: mở thẳng trang kết nối prod trên trình duyệt và ghi cấu hình vào mọi ứng dụng AI phát hiện được trên máy (Claude…"
|
|
43
43
|
}
|
|
44
44
|
]
|
package/dist/tools/builder.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { checkSiteCode, codeGuard } from "../builder/native-first.js";
|
|
3
|
+
import { PAGE_CODE_ARG, writePageCode } from "./page-code.js";
|
|
4
|
+
import { PAGE_CODE_BUDGET, codeTargets, lintPageCode, mergePageCode } from "../builder/page-code.js";
|
|
2
5
|
import { elementSchema, suggestType, valueRules } from "../builder/element-schema.js";
|
|
3
6
|
import { z } from "zod";
|
|
4
7
|
import { BUILD_GUIDE } from "../builder/guide.js";
|
|
@@ -244,10 +247,18 @@ ONE page per site for type main (homepage) / error / maintain, and slugs are uni
|
|
|
244
247
|
})
|
|
245
248
|
.optional()
|
|
246
249
|
.describe("SEO for this page → settings.seo. Without it the page publishes with an EMPTY title/description. For a store page a good default title is '{{name_product}} | {{name_site}}' (product) or '{{name_category}} | {{name_site}}' (category)."),
|
|
250
|
+
custom_code: PAGE_CODE_ARG,
|
|
251
|
+
native_gap: z.string().min(30).optional().describe("Only if custom_code is refused and no native way exists: the need, what you checked, what it lacks."),
|
|
247
252
|
dry_run: z.boolean().default(true).describe("Preview+validate only (true) or create+save (false)"),
|
|
248
|
-
}, ({ name, slug, source, type, is_homepage, seo, dry_run }) => handle(async () => {
|
|
253
|
+
}, ({ name, slug, source, type, is_homepage, seo, custom_code, native_gap, dry_run }) => handle(async () => {
|
|
249
254
|
const parsed = parseSource(source);
|
|
250
255
|
const validation = validatePage(parsed);
|
|
256
|
+
// Per-page code is judged against THIS source before anything is created.
|
|
257
|
+
const pageCode = custom_code ? Object.fromEntries(Object.entries(custom_code).filter(([, v]) => v !== undefined)) : undefined;
|
|
258
|
+
const codeCheck = pageCode ? lintPageCode(mergePageCode({}, pageCode).after, codeTargets(parsed).ids) : undefined;
|
|
259
|
+
const codeBlock = pageCode ? codeGuard(checkSiteCode({}, mergePageCode({}, pageCode).after, { label: "Page", budget: PAGE_CODE_BUDGET }), native_gap) : null;
|
|
260
|
+
if (codeCheck?.errors.length)
|
|
261
|
+
validation.valid = false;
|
|
251
262
|
// Resolve numeric page type + the site data-source flag a special page needs.
|
|
252
263
|
const kind = type || (is_homepage ? "main" : undefined);
|
|
253
264
|
const typeNum = kind ? PAGE_TYPE_NUM[kind] : undefined;
|
|
@@ -263,6 +274,7 @@ ONE page per site for type main (homepage) / error / maintain, and slugs are uni
|
|
|
263
274
|
dry_run: true,
|
|
264
275
|
...(conflict ? { blocked: true, conflict } : {}),
|
|
265
276
|
validation,
|
|
277
|
+
...(pageCode ? { custom_code: { errors: codeCheck.errors, warnings: codeCheck.warnings, ...(codeBlock ? { blocked: codeBlock } : {}) } } : {}),
|
|
266
278
|
request: { name, slug: cleanSlug ?? null, type: kind ?? null, page_type_num: typeNum ?? null, is_homepage, sections: (parsed && parsed.sections || []).length },
|
|
267
279
|
will_enable_feature: requiredFlag ?? null,
|
|
268
280
|
renders_at_breakpoints: ["bp1", "bp2", "bp3", "bp4"],
|
|
@@ -277,8 +289,10 @@ ONE page per site for type main (homepage) / error / maintain, and slugs are uni
|
|
|
277
289
|
return { error: conflict.error, existing_page: conflict.existing_page };
|
|
278
290
|
}
|
|
279
291
|
if (!validation.valid) {
|
|
280
|
-
return { error: "Validation failed — not saving.", validation };
|
|
292
|
+
return { error: "Validation failed — not saving.", validation, ...(codeCheck?.errors.length ? { custom_code_errors: codeCheck.errors } : {}) };
|
|
281
293
|
}
|
|
294
|
+
if (codeBlock)
|
|
295
|
+
return codeBlock;
|
|
282
296
|
// A special page is useless if its site data-source flag is off (bindings
|
|
283
297
|
// return null). Enable it BEFORE creating the page so the page works on first load.
|
|
284
298
|
let feature = null;
|
|
@@ -300,6 +314,9 @@ ONE page per site for type main (homepage) / error / maintain, and slugs are uni
|
|
|
300
314
|
}
|
|
301
315
|
// slug / homepage / SEO are not applied at create — set them via update_page.
|
|
302
316
|
const metaWarning = await applyPageMeta(api, pageId, { slug: cleanSlug, is_homepage, seo }).then(() => undefined, (e) => `Page saved, but slug/homepage/SEO failed: ${e?.message ?? e}`);
|
|
317
|
+
const codeSaved = pageCode
|
|
318
|
+
? await writePageCode(api, pageId, pageCode, { native_gap, dry_run: false }).catch((e) => ({ error: `Page saved, but its custom code failed: ${e?.message ?? e}` }))
|
|
319
|
+
: undefined;
|
|
303
320
|
return {
|
|
304
321
|
success: true,
|
|
305
322
|
page_id: pageId,
|
|
@@ -308,6 +325,7 @@ ONE page per site for type main (homepage) / error / maintain, and slugs are uni
|
|
|
308
325
|
page_type: kind ?? null,
|
|
309
326
|
...(feature ? { data_source: { flag: feature.flag, newly_enabled: feature.changed } } : {}),
|
|
310
327
|
stats: validation.stats,
|
|
328
|
+
...(codeSaved ? { custom_code: codeSaved } : {}),
|
|
311
329
|
...(metaWarning ? { warning: metaWarning } : {}),
|
|
312
330
|
};
|
|
313
331
|
}));
|
package/dist/tools/families.js
CHANGED
|
@@ -30,8 +30,8 @@ export const FAMILIES = {
|
|
|
30
30
|
global_section: ["Global header/footer/custom sections shown on every page", [
|
|
31
31
|
"list_global_sections", "get_global_section", "create_global_section", "delete_global_section", "search_global_section_elements", "get_global_section_element",
|
|
32
32
|
]],
|
|
33
|
-
site_code: ["
|
|
34
|
-
"get_site_custom_code", "update_site_custom_code", "append_site_custom_code",
|
|
33
|
+
site_code: ["Custom code, site-wide or for ONE page (native first: refused when an element can do it)", [
|
|
34
|
+
"get_site_custom_code", "update_site_custom_code", "append_site_custom_code", "get_page_custom_code", "update_page_custom_code",
|
|
35
35
|
]],
|
|
36
36
|
theme: ["Site themes and templates", ["list_themes", "semantic_search_themes", "list_template_themes", "create_site_from_template"]],
|
|
37
37
|
product: ["Products of the store", ["list_products", "get_product", "create_product", "update_product", "delete_product", "set_product_published"]],
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// get_page_custom_code / update_page_custom_code: custom code for ONE page (page.settings.custom_code).
|
|
2
|
+
// writePageCode is the single writer — update_page_source.custom_code and build_page go through it.
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { checkSiteCode, codeGuard } from "../builder/native-first.js";
|
|
5
|
+
import { PAGE_CODE_BUDGET, PAGE_CODE_FIELDS, PAGE_CODE_GUIDE, codeTargets, lintPageCode, mergePageCode, readPageCode, } from "../builder/page-code.js";
|
|
6
|
+
import { getConfirmMode } from "./context.js";
|
|
7
|
+
const parse = (v) => {
|
|
8
|
+
if (typeof v !== "string")
|
|
9
|
+
return v;
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(v);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
/** The page (fresh from the backend), its settings object and parsed source. */
|
|
18
|
+
async function loadPage(api, pageId) {
|
|
19
|
+
const res = await api.listPages();
|
|
20
|
+
const list = res?.data || res?.pages || res;
|
|
21
|
+
const page = (Array.isArray(list) ? list : []).find((p) => p.id === pageId);
|
|
22
|
+
if (!page)
|
|
23
|
+
throw new Error(`Page "${pageId}" not found on this site (list_pages).`);
|
|
24
|
+
const settings = parse(page.settings);
|
|
25
|
+
const source = parse(page.source?.source) || { sections: [] };
|
|
26
|
+
return { page, settings: settings && typeof settings === "object" ? settings : {}, source };
|
|
27
|
+
}
|
|
28
|
+
const sizes = (c) => Object.fromEntries(PAGE_CODE_FIELDS.map((f) => [f, (c[f] || "").length]));
|
|
29
|
+
const usage = (c) => {
|
|
30
|
+
const script = ["code_before_head", "code_before_body", "code_custom_javascript"].reduce((n, f) => n + (c[f] || "").length, 0);
|
|
31
|
+
const css = (c.code_custom_css || "").length;
|
|
32
|
+
return { script: { used: script, budget: PAGE_CODE_BUDGET.script.soft }, css: { used: css, budget: PAGE_CODE_BUDGET.css.soft } };
|
|
33
|
+
};
|
|
34
|
+
/** Validate and save a page's custom code. Returns the result object a tool hands back. */
|
|
35
|
+
export async function writePageCode(api, pageId, input, opts = {}) {
|
|
36
|
+
const { settings, source } = await loadPage(api, pageId);
|
|
37
|
+
const before = readPageCode(settings);
|
|
38
|
+
const { after, notes } = mergePageCode(before, input, opts.mode ?? "replace");
|
|
39
|
+
const { ids } = codeTargets(source);
|
|
40
|
+
const lint = lintPageCode(after, ids);
|
|
41
|
+
if (lint.errors.length)
|
|
42
|
+
return { error: "BLOCKED: the code has errors — not saved.", errors: lint.errors, ...(lint.warnings.length ? { warnings: lint.warnings } : {}) };
|
|
43
|
+
const blocked = codeGuard(checkSiteCode(before, after, { label: "Page", budget: PAGE_CODE_BUDGET }), opts.native_gap);
|
|
44
|
+
if (blocked)
|
|
45
|
+
return blocked;
|
|
46
|
+
if (!opts.allow_shrink)
|
|
47
|
+
for (const f of PAGE_CODE_FIELDS) {
|
|
48
|
+
const was = (before[f] || "").length;
|
|
49
|
+
const now = (after[f] || "").length;
|
|
50
|
+
if (was > 200 && now < was * 0.5)
|
|
51
|
+
return {
|
|
52
|
+
error: `BLOCKED: ${f} would shrink from ${was} to ${now} chars — that looks like lost code. Read it with get_page_custom_code and merge (or mode:"append"); pass allow_shrink:true if the removal is deliberate.`,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
const changed = PAGE_CODE_FIELDS.filter((f) => (before[f] || "") !== (after[f] || ""));
|
|
56
|
+
const report = {
|
|
57
|
+
page_id: pageId,
|
|
58
|
+
changed,
|
|
59
|
+
before: sizes(before),
|
|
60
|
+
after: sizes(after),
|
|
61
|
+
usage: usage(after),
|
|
62
|
+
...(notes.length ? { notes } : {}),
|
|
63
|
+
...(lint.warnings.length ? { warnings: lint.warnings } : {}),
|
|
64
|
+
};
|
|
65
|
+
if (!changed.length)
|
|
66
|
+
return { ...report, saved: false, note: "Nothing changed." };
|
|
67
|
+
if (opts.dry_run)
|
|
68
|
+
return { ...report, dry_run: true, would_save: after, next: "Show the user the code; on their OK call again with dry_run:false." };
|
|
69
|
+
// Top-level settings keys replace: the whole custom_code object goes in, every other key stays.
|
|
70
|
+
const next = { ...settings, custom_code: after };
|
|
71
|
+
if (!Object.keys(after).length)
|
|
72
|
+
delete next.custom_code;
|
|
73
|
+
await api.updatePage(pageId, { settings: next });
|
|
74
|
+
return { ...report, saved: true, next: "Check it with preview_page, then publish_site to take it live (settings are copied on publish)." };
|
|
75
|
+
}
|
|
76
|
+
const codeArgs = {
|
|
77
|
+
code_custom_css: z.string().optional().describe("CSS for this page (no <style> needed). Target #ELEMENT-ID or .custom_class. \"\" clears."),
|
|
78
|
+
code_custom_javascript: z.string().optional().describe("Plain JS for this page, NO <script> tag; runs at the end of <body>. \"\" clears."),
|
|
79
|
+
code_before_head: z.string().optional().describe("HTML for <head> on this page only (<script src>, <link>, <meta>). \"\" clears."),
|
|
80
|
+
code_before_body: z.string().optional().describe("HTML after this page's content, before its scripts (noscript pixel, widget mount point). \"\" clears."),
|
|
81
|
+
};
|
|
82
|
+
export const PAGE_CODE_ARG = z.object(codeArgs).optional()
|
|
83
|
+
.describe("Per-page custom code saved with the page (same slots as update_page_custom_code). Last resort — native first.");
|
|
84
|
+
export function registerPageCodeTools(server, api, handle) {
|
|
85
|
+
server.tool("get_page_custom_code", "Read the custom code of ONE page (CSS / JS / head / body slots in page.settings.custom_code), its budget usage, the element ids and custom classes the code can target on that page, and the rules for per-page code. Read this before update_page_custom_code.", { page_id: z.string().describe("Page ID (list_pages)") }, ({ page_id }) => handle(async () => {
|
|
86
|
+
const { page, settings, source } = await loadPage(api, page_id);
|
|
87
|
+
const code = readPageCode(settings);
|
|
88
|
+
const t = codeTargets(source);
|
|
89
|
+
return {
|
|
90
|
+
page: { id: page.id, name: page.name, slug: page.slug ?? null },
|
|
91
|
+
custom_code: code,
|
|
92
|
+
usage: usage(code),
|
|
93
|
+
targets: t.targets,
|
|
94
|
+
...(t.truncated ? { targets_note: `${t.total} elements; first ${t.targets.length} listed — search_page_elements for the rest.` } : {}),
|
|
95
|
+
guide: PAGE_CODE_GUIDE,
|
|
96
|
+
};
|
|
97
|
+
}));
|
|
98
|
+
server.tool("update_page_custom_code", `Save custom code for ONE page — only when the element schema can't do what the user asked (NATIVE FIRST: element → its settings/events/bindings → an app → code). Slots: code_custom_css, code_custom_javascript (plain JS, own <script>), code_before_head, code_before_body; rendered on that page only, after the site's code. mode "replace" (default) sets the slots you pass, "append" adds to them; "" clears a slot. JS syntax and CSS braces are checked before saving, #ids not on the page are flagged, oversized or UI-building code is refused unless native_gap names the gap, and a large shrink needs allow_shrink. Read get_page_custom_code first; dry_run shows what would be saved.`, {
|
|
99
|
+
page_id: z.string().describe("Page ID (list_pages)"),
|
|
100
|
+
...codeArgs,
|
|
101
|
+
mode: z.enum(["replace", "append"]).optional().describe("replace (default): set the given slots; append: add after the current code"),
|
|
102
|
+
native_gap: z.string().min(30).optional().describe("Only when refused and no native way exists: the need, the elements/apps you checked, what each lacks. Tell the user first."),
|
|
103
|
+
allow_shrink: z.boolean().optional().describe("Allow a slot to lose more than half its code (deliberate removal)"),
|
|
104
|
+
dry_run: z.boolean().optional().describe("Validate and show what would be saved, without saving (default: on in confirm mode)"),
|
|
105
|
+
}, ({ page_id, mode, native_gap, allow_shrink, dry_run, ...code }) => handle(async () => {
|
|
106
|
+
const input = Object.fromEntries(Object.entries(code).filter(([, v]) => v !== undefined));
|
|
107
|
+
if (!Object.keys(input).length)
|
|
108
|
+
throw new Error("Pass at least one slot: code_custom_css, code_custom_javascript, code_before_head or code_before_body.");
|
|
109
|
+
return writePageCode(api, page_id, input, {
|
|
110
|
+
mode, native_gap, allow_shrink,
|
|
111
|
+
dry_run: dry_run !== undefined ? dry_run : getConfirmMode() === "always_confirm",
|
|
112
|
+
});
|
|
113
|
+
}));
|
|
114
|
+
}
|
package/dist/tools/pages.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { writePageCode } from "./page-code.js";
|
|
3
|
+
import { readPageCode } from "../builder/page-code.js";
|
|
2
4
|
import { CUSTOM_CODE_GUIDE } from "../guides.js";
|
|
3
5
|
import { getConfirmMode } from "./context.js";
|
|
4
6
|
import { addedErrors, applyNodeUpdates, computeNodeDiff, checkContentPlaceholders, checkElementPatch, finalizeForRender } from "../builder/page.js";
|
|
@@ -237,7 +239,8 @@ export function registerPageTools(server, api, handle) {
|
|
|
237
239
|
const overview = source ? buildOverview(source) : null;
|
|
238
240
|
return {
|
|
239
241
|
page: { id: page.id, name: page.name, slug: page.slug, type: page.type },
|
|
240
|
-
custom_code: (page.
|
|
242
|
+
custom_code: readPageCode(page.settings),
|
|
243
|
+
...(page.source?.custom_code ? { legacy_devmode_code: "page_source.custom_code is set but the storefront never renders it — move it with update_page_custom_code." } : {}),
|
|
241
244
|
overview,
|
|
242
245
|
hint: "Use search_page_elements to query specific elements by type, class, text, etc. Target via CSS: #ELEMENT-ID or .custom-class. Sections have class 'x-section', elements have 'x-element'.",
|
|
243
246
|
};
|
|
@@ -625,7 +628,7 @@ IMPORTANT: Before calling this tool, you MUST:
|
|
|
625
628
|
Safeguarded: blocks if new source is <50% of existing size.`, {
|
|
626
629
|
page_id: z.string().describe("Page ID"),
|
|
627
630
|
source: z.any().describe("Full page source object (sections tree) or JSON string"),
|
|
628
|
-
custom_code: z.string().optional().describe("
|
|
631
|
+
custom_code: z.string().optional().describe("JS for this page only → page.settings.custom_code.code_custom_javascript (same as update_page_custom_code; use that tool for CSS/head/body slots). Last resort."),
|
|
629
632
|
native_gap: NATIVE_GAP,
|
|
630
633
|
allow_shrink: ALLOW_SHRINK,
|
|
631
634
|
}, ({ page_id, source, custom_code, native_gap, allow_shrink }) => handle(async () => {
|
|
@@ -637,14 +640,16 @@ Safeguarded: blocks if new source is <50% of existing size.`, {
|
|
|
637
640
|
// per-breakpoint keys like every other writer; nodes already in bp shape are untouched.
|
|
638
641
|
finalizeForRender(body.source, await api.getSiteBreakpoints(), await api.getSiteDefaultGrid());
|
|
639
642
|
}
|
|
643
|
+
// page_source.custom_code is stored but never rendered; per-page code lives in
|
|
644
|
+
// page.settings.custom_code (update_page_custom_code). This param writes there.
|
|
645
|
+
let pageCode;
|
|
640
646
|
if (custom_code != null) {
|
|
647
|
+
pageCode = await writePageCode(api, page_id, { code_custom_javascript: custom_code }, { native_gap, dry_run: false });
|
|
641
648
|
invalidatePageCache();
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
return blocked;
|
|
647
|
-
body.custom_code = custom_code;
|
|
649
|
+
if (pageCode.error)
|
|
650
|
+
return pageCode;
|
|
651
|
+
if (body.source == null)
|
|
652
|
+
return { success: true, custom_code: pageCode };
|
|
648
653
|
}
|
|
649
654
|
// Safeguard: force fresh read and block if new source is suspiciously smaller
|
|
650
655
|
if (body.source) {
|
|
@@ -676,6 +681,7 @@ Safeguarded: blocks if new source is <50% of existing size.`, {
|
|
|
676
681
|
page_source_id: saved.id,
|
|
677
682
|
page_id: saved.page_id,
|
|
678
683
|
source_length: (saved.source || "").length,
|
|
684
|
+
...(pageCode ? { custom_code: pageCode } : {}),
|
|
679
685
|
};
|
|
680
686
|
}));
|
|
681
687
|
}
|
package/dist/tools/registry.js
CHANGED
|
@@ -30,6 +30,7 @@ import { registerBuilderExtraTools } from "./builder-extras.js";
|
|
|
30
30
|
import { registerPageDraftTools } from "./page-draft.js";
|
|
31
31
|
import { registerSitePlanTools } from "./site-plans.js";
|
|
32
32
|
import { registerApiGatewayTools } from "./api-gateway.js";
|
|
33
|
+
import { registerPageCodeTools } from "./page-code.js";
|
|
33
34
|
import { readFileSync } from "node:fs";
|
|
34
35
|
import { FAMILIES, familyTool } from "./families.js";
|
|
35
36
|
/** Tool names folded into api_get / api_call → their route (invoke_tool points callers there). */
|
|
@@ -88,6 +89,7 @@ const MODULES = [
|
|
|
88
89
|
["web", registerPageDraftTools],
|
|
89
90
|
["site_config", registerSitePlanTools],
|
|
90
91
|
["session", registerApiGatewayTools],
|
|
92
|
+
["web", registerPageCodeTools],
|
|
91
93
|
];
|
|
92
94
|
/** Every collected tool of a server, by name — members of a family included (tests, gateway). */
|
|
93
95
|
const ENTRIES = new WeakMap();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "webcake-storefront-mcp",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "MCP server for the WebCake/StoreCake storefront builder — page CRUD, page authoring, products, orders, and more",
|
|
5
5
|
"mcpName": "io.github.vuluu2k/webcake-storefront-mcp",
|
|
6
6
|
"license": "MIT",
|