webcake-storefront-mcp 2.0.0 → 2.2.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.
@@ -5,12 +5,28 @@
5
5
  // - keys mined from 329 published pages (element-keys.generated.json),
6
6
  // - the curated tables in attributes.ts (meanings, enums like "h1|h2|…|p"),
7
7
  // - the factory skeleton (also the source of each key's value TYPE),
8
- // - the generic grid config + shared specials every node may carry.
8
+ // - the generic grid config + shared specials every node may carry,
9
+ // - the published-page renderer (renderer-keys.generated.json, scripts/mine-renderer.mjs):
10
+ // which keys each type's HTML/CSS builder READS, their fallback default, compared values,
11
+ // - the editor panels (editor-keys.generated.json, scripts/mine-editor.mjs): the label the
12
+ // user sees, the control, the options a select offers.
9
13
  // The renderer ignores a specials/config key it doesn't know (a dead key), so an unknown key is
10
14
  // a WARNING with a did-you-mean. Style is different: the renderer emits every style key as CSS
11
15
  // (camelCase → kebab), so style keys are checked as CSS properties, not per type.
12
16
  import { OBSERVED, ELEMENT_ATTRS, SHARED_SPECIALS, SHARED_KEY_DICT, GENERIC_CONFIG } from "./attributes.js";
13
17
  import { buildElement, describeType, isKnownType, ELEMENT_TYPES } from "./catalog.js";
18
+ import { readFileSync } from "node:fs";
19
+ const loadJson = (name) => {
20
+ try {
21
+ return JSON.parse(readFileSync(new URL(name, import.meta.url), "utf8"));
22
+ }
23
+ catch {
24
+ return {};
25
+ }
26
+ };
27
+ const RENDERER = loadJson("./renderer-keys.generated.json");
28
+ const MENTIONED = new Set(RENDERER.mentioned || []);
29
+ const EDITOR = loadJson("./editor-keys.generated.json");
14
30
  /** `[CODE] #id (type) at: message → fix` — stable code first so an agent can act per code. */
15
31
  export function formatFinding(f) {
16
32
  const who = f.id ? ` #${f.id}${f.type ? ` (${f.type})` : ""}` : f.type ? ` (${f.type})` : "";
@@ -49,6 +65,10 @@ for (const a of Object.values(ELEMENT_ATTRS)) {
49
65
  Object.keys(a.specials || {}).forEach((k) => ANY_SPECIALS.add(k));
50
66
  Object.keys(a.config || {}).forEach((k) => ANY_CONFIG.add(k));
51
67
  }
68
+ for (const src of [RENDERER.shared, ...Object.values(RENDERER.types || {}), ...Object.values(EDITOR.types || {})]) {
69
+ Object.keys(src?.specials || {}).forEach((k) => ANY_SPECIALS.add(k));
70
+ Object.keys(src?.config || {}).forEach((k) => ANY_CONFIG.add(k));
71
+ }
52
72
  const KEY_TYPES = new Set(["string", "number", "boolean", "array", "object"]);
53
73
  export function elementSchema(type) {
54
74
  if (!isKnownType(type))
@@ -59,26 +79,53 @@ export function elementSchema(type) {
59
79
  const skeleton = buildElement(type, {});
60
80
  const obs = OBSERVED[type] || { specials: [], config: [], style: [], bindings: [], events: false };
61
81
  const cur = ELEMENT_ATTRS[type] || {};
82
+ const rend = RENDERER.types?.[type];
83
+ const edit = EDITOR.types?.[type];
62
84
  const bucket = (where, keys, defaults, curated, shared) => {
63
85
  const out = {};
64
- for (const k of [...keys].sort()) {
86
+ const r = rend?.[where] || {};
87
+ const rs = RENDERER.shared?.[where] || {};
88
+ const e = edit?.[where] || {};
89
+ for (const k of [...new Set([...keys, ...Object.keys(r), ...Object.keys(e)])].sort()) {
65
90
  const desc = curated?.[k] ?? shared[k] ?? SHARED_KEY_DICT[k];
66
91
  const spec = {};
92
+ const rk = r[k] ?? rs[k];
93
+ const ek = e[k];
67
94
  const types = new Set((obs.types?.[`${where}.${k}`] || []).filter((t) => KEY_TYPES.has(t)));
68
- const t = typeOf(defaults?.[k]);
95
+ const t = typeOf(defaults?.[k]) ?? typeOf(rk?.default);
69
96
  if (t)
70
97
  types.add(t);
71
98
  if (types.size)
72
99
  spec.types = [...types].sort();
73
100
  const seen = obs.values?.[`${where}.${k}`];
74
101
  const curatedEnum = enumOf(curated?.[k]);
102
+ // Numeric editor options next to word values (renderer/real pages) come from another panel.
103
+ const words = [...(rk?.values || []), ...(seen || [])].some((v) => !/^\d+$/.test(v));
104
+ const opts = (ek?.options || []).filter((o) => !(words && /^\d+$/.test(o)));
105
+ const offered = [...new Set([...opts, ...(rk?.values || [])])];
75
106
  // Enforced only when both the editor's list and real pages agree it is closed.
76
107
  if (curatedEnum && seen)
77
108
  spec.enum = [...new Set([...curatedEnum, ...seen])];
109
+ else if (opts.length && seen?.length && seen.every((v) => opts.includes(v)))
110
+ spec.enum = [...new Set([...opts, ...(rk?.values || [])])];
78
111
  else if (seen)
79
112
  spec.seen = seen;
113
+ if (!spec.enum && offered.length)
114
+ spec.values = offered;
80
115
  if (desc)
81
116
  spec.desc = desc;
117
+ if (ek?.label)
118
+ spec.label = ek.label;
119
+ if (rk?.default !== undefined)
120
+ spec.default = rk.default;
121
+ // Grid/position config and shared specials are read by generic plumbing — no per-type flag.
122
+ // false only when nothing on the render side (Elixir or client JS) mentions the key at all.
123
+ if (rend && !(where === "config" ? GENERIC_CONFIG.has(k) : k in SHARED_SPECIALS)) {
124
+ if (rk)
125
+ spec.rendered = true;
126
+ else if (!MENTIONED.has(k))
127
+ spec.rendered = false;
128
+ }
82
129
  out[k] = spec;
83
130
  }
84
131
  return out;
@@ -201,6 +248,8 @@ export function checkElementKeys(node) {
201
248
  const at = `${where}.${k}`;
202
249
  if (k in specs) {
203
250
  checkValue(specs[k], v, { ...base, at }, out);
251
+ if (specs[k].rendered === false && v !== undefined && v !== null && v !== "")
252
+ out.push({ ...base, at, code: "NO_EFFECT", severity: "warning", message: `no render code reads ${where.split(".").pop()}.${k} — stored, changes nothing on the published page`, fix: `drop it; see keys in get_element("${node.type}")` });
204
253
  continue;
205
254
  }
206
255
  const anywhere = where === "specials" ? ANY_SPECIALS : ANY_CONFIG;
@@ -272,6 +321,76 @@ export function valueRules(type) {
272
321
  }
273
322
  return Object.keys(out).length ? out : undefined;
274
323
  }
324
+ /** One line per meaningful key of a type — what get_element shows an agent:
325
+ * `key: meaning · type · one of a|b · default x`. Keys the renderer reads come first; keys no
326
+ * render code mentions go to no_effect (stored, change nothing on the published page). */
327
+ export function keyReference(type) {
328
+ const schema = elementSchema(type);
329
+ if (!schema)
330
+ return undefined;
331
+ const fmt = (v) => (typeof v === "string" ? JSON.stringify(v) : String(v));
332
+ const out = { specials: [], config: [] };
333
+ const dead = [];
334
+ for (const where of ["specials", "config"]) {
335
+ const rows = Object.entries(schema[where]).filter(([k]) => !NOISE.has(k) && !(where === "config" ? GENERIC_CONFIG.has(k) : k in SHARED_SPECIALS));
336
+ rows.sort(([, a], [, b]) => Number(!!b.rendered) - Number(!!a.rendered));
337
+ for (const [k, s] of rows) {
338
+ if (s.rendered === false) {
339
+ dead.push(`${where}.${k}`);
340
+ continue;
341
+ }
342
+ const parts = [];
343
+ const meaning = s.desc ?? (s.label ? `"${s.label}"` : undefined);
344
+ if (meaning)
345
+ parts.push(meaning);
346
+ if (s.types && !(s.types.length === 1 && s.types[0] === "string" && (s.enum || s.values)))
347
+ parts.push(s.types.join("|"));
348
+ if (s.enum)
349
+ parts.push(`one of ${s.enum.join("|")}`);
350
+ else if (s.values || s.seen)
351
+ parts.push(`e.g. ${[...new Set([...(s.values || []), ...(s.seen || [])])].slice(0, 12).join("|")}`);
352
+ if (s.default !== undefined && s.default !== "")
353
+ parts.push(`default ${fmt(s.default)}`);
354
+ out[where].push(parts.length ? `${k}: ${parts.join(" · ")}` : k);
355
+ }
356
+ }
357
+ out.config = groupPlain(out.config);
358
+ if (dead.length)
359
+ out.no_effect = dead;
360
+ return out;
361
+ }
362
+ /** Style config of one part (addToCartColor, addToCartFontSize…) folded into one line per part:
363
+ * `addToCart{Color,FontSize,…}: style of the addToCart part` (defaults kept inline). */
364
+ const STYLE_SUFFIX = /(Background(?:Hover)?|Border(?:Color|Radius|Width|Style)?|BoxShadow|Color(?:Hover)?|Decoration|Font(?:Size|Style|Weight|Theme|Family)?|TextAlign|LetterSpacing|LineHeight|Padding[XY]?|Margin[XY]?|Radius|Width|Height|Size|Gap|Opacity|Shadow)$/;
365
+ function groupPlain(lines) {
366
+ const parse = (l) => {
367
+ const i = l.indexOf(":");
368
+ const k = i < 0 ? l : l.slice(0, i);
369
+ const m = STYLE_SUFFIX.exec(k);
370
+ const enumish = / · (one of|e\.g\.) /.test(l);
371
+ const dflt = / · default (.+)$/.exec(l)?.[1];
372
+ return { k, part: m && m.index > 1 && !enumish ? k.slice(0, m.index) : undefined, suffix: m?.[1], dflt };
373
+ };
374
+ const rows = lines.map((l) => ({ l, ...parse(l) }));
375
+ const count = new Map();
376
+ for (const r of rows)
377
+ if (r.part)
378
+ count.set(r.part, (count.get(r.part) || 0) + 1);
379
+ const done = new Set();
380
+ const out = [];
381
+ for (const r of rows) {
382
+ if (!r.part || count.get(r.part) < 3) {
383
+ out.push(r.l);
384
+ continue;
385
+ }
386
+ if (done.has(r.part))
387
+ continue;
388
+ done.add(r.part);
389
+ const members = rows.filter((x) => x.part === r.part).map((x) => `${x.suffix}${x.dflt ? `=${x.dflt}` : ""}`);
390
+ out.push(`${r.part}{${members.join(",")}}: style of the ${r.part} part`);
391
+ }
392
+ return out;
393
+ }
275
394
  /** Did-you-mean for an unknown element type. */
276
395
  export const suggestType = (type) => didYouMean(type, ELEMENT_TYPES);
277
396
  /** Collapse repeated warnings per code: keep the first `keep`, then one line with the rest. */
@@ -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 } = CODE_BUDGET[kind];
140
+ const { soft: softLimit, hard: hardLimit } = budget[kind];
138
141
  if (now.length > hardLimit)
139
- hard.push(`Site ${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.`);
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(`Site ${kind} would reach ${now.length} chars (budget ${softLimit}).`);
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
+ }