@perkyzz/emvb 0.3.0 → 0.5.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.
Files changed (163) hide show
  1. package/README.md +22 -4
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/package.json +5 -2
  4. package/src/admin/access/role.ts +9 -3
  5. package/src/admin/agents-api.ts +39 -0
  6. package/src/admin/api.ts +17 -7
  7. package/src/admin/content-api.ts +7 -51
  8. package/src/admin/content-item.ts +22 -0
  9. package/src/admin/design-api.ts +30 -0
  10. package/src/admin/editor/A11yCopilot.tsx +1 -1
  11. package/src/admin/editor/CommandPalette.tsx +43 -2
  12. package/src/admin/editor/Editor.tsx +133 -332
  13. package/src/admin/editor/EditorOverlay.tsx +3 -1
  14. package/src/admin/editor/PerfMeter.tsx +1 -1
  15. package/src/admin/editor/ShortcutsDialog.tsx +4 -1
  16. package/src/admin/editor/Timeline.tsx +124 -9
  17. package/src/admin/editor/canvas/CanvasFrame.tsx +51 -368
  18. package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
  19. package/src/admin/editor/canvas/SelectionOverlay.tsx +86 -46
  20. package/src/admin/editor/canvas/canvas-scale.ts +20 -0
  21. package/src/admin/editor/canvas/drop-line.ts +24 -0
  22. package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
  23. package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
  24. package/src/admin/editor/collection-previews.ts +28 -5
  25. package/src/admin/editor/editor-chrome.tsx +346 -0
  26. package/src/admin/editor/editor-commands.ts +360 -0
  27. package/src/admin/editor/editor-css.ts +4 -0
  28. package/src/admin/editor/element-chrome.ts +89 -0
  29. package/src/admin/editor/feature-css.ts +37 -18
  30. package/src/admin/editor/host.ts +33 -0
  31. package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
  32. package/src/admin/editor/icons/library.ts +29 -19
  33. package/src/admin/editor/icons/use-icon-library.ts +315 -0
  34. package/src/admin/editor/palette-items.ts +36 -5
  35. package/src/admin/editor/palette.ts +9 -4
  36. package/src/admin/editor/panels/AddPanel.tsx +2 -67
  37. package/src/admin/editor/panels/ColorControl.tsx +21 -18
  38. package/src/admin/editor/panels/ElementPanel.tsx +40 -99
  39. package/src/admin/editor/panels/LayersPanel.tsx +34 -62
  40. package/src/admin/editor/panels/SettingsPanel.tsx +1 -0
  41. package/src/admin/editor/panels/SiteStylesDrawer.tsx +16 -10
  42. package/src/admin/editor/panels/TokenScales.tsx +4 -2
  43. package/src/admin/editor/panels/VariableSection.tsx +1 -10
  44. package/src/admin/editor/panels/color-space.ts +12 -1
  45. package/src/admin/editor/panels/inline-error.tsx +11 -0
  46. package/src/admin/editor/panels/settings/AdvancedFields.tsx +143 -1
  47. package/src/admin/editor/panels/settings/AudienceEditor.tsx +115 -7
  48. package/src/admin/editor/panels/settings/DraftTextField.tsx +42 -9
  49. package/src/admin/editor/panels/settings/FieldControl.tsx +6 -0
  50. package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
  51. package/src/admin/editor/panels/settings/IconPicker.tsx +21 -1
  52. package/src/admin/editor/panels/settings/ImageSourcesField.tsx +111 -0
  53. package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
  54. package/src/admin/editor/panels/settings/MediaPicker.tsx +2 -3
  55. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +178 -0
  56. package/src/admin/editor/panels/settings/StyleRow.tsx +14 -2
  57. package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
  58. package/src/admin/editor/panels/settings/form-names.ts +7 -11
  59. package/src/admin/editor/panels/settings/length-units.ts +15 -4
  60. package/src/admin/editor/panels/settings/link-rules.ts +19 -0
  61. package/src/admin/editor/panels/settings/number-input.ts +11 -0
  62. package/src/admin/editor/panels/settings/query-style.ts +65 -0
  63. package/src/admin/editor/panels/settings/style-sections.ts +5 -1
  64. package/src/admin/editor/panels/style-target.ts +105 -0
  65. package/src/admin/editor/panels/variable-values.ts +4 -2
  66. package/src/admin/editor/remote-change.ts +67 -0
  67. package/src/admin/editor/section-templates.ts +43 -21
  68. package/src/admin/editor/shortcuts.ts +4 -0
  69. package/src/admin/editor/store.ts +10 -1
  70. package/src/admin/editor/useClipboardActions.ts +1 -1
  71. package/src/admin/editor/useEditorCommands.ts +61 -13
  72. package/src/admin/editor/useEditorData.ts +7 -1
  73. package/src/admin/editor/useEditorShortcuts.ts +23 -15
  74. package/src/admin/editor/useNodeActions.ts +6 -1
  75. package/src/admin/forms-api.ts +17 -6
  76. package/src/admin/icon-uploads-api.ts +18 -0
  77. package/src/admin/index.tsx +3 -1
  78. package/src/admin/media-api.ts +20 -0
  79. package/src/admin/pages/AgentsPage.tsx +274 -0
  80. package/src/admin/theme-api.ts +5 -18
  81. package/src/admin/ui.ts +28 -0
  82. package/src/astro/content-port.ts +24 -0
  83. package/src/astro/floats/runtime.ts +10 -0
  84. package/src/astro/forms/EmVBFormsClient.astro +11 -0
  85. package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
  86. package/src/astro/forms/client.ts +1 -0
  87. package/src/astro/forms-definitions.ts +24 -11
  88. package/src/astro/index.ts +1 -0
  89. package/src/astro/popups/runtime.ts +15 -0
  90. package/src/astro/render-session.ts +85 -0
  91. package/src/astro/request-data.ts +20 -8
  92. package/src/astro/resolve-theme.ts +166 -76
  93. package/src/astro/resolve.ts +57 -16
  94. package/src/astro/tabs/runtime.ts +60 -1
  95. package/src/astro/theme-posts.ts +16 -5
  96. package/src/astro/visitor.ts +67 -5
  97. package/src/constants.ts +1 -1
  98. package/src/core/a11y/audit.ts +202 -26
  99. package/src/core/arrange.ts +71 -38
  100. package/src/core/audience/rules.ts +22 -2
  101. package/src/core/canvas-styles.ts +24 -0
  102. package/src/core/clipboard.ts +11 -32
  103. package/src/core/css/generate.ts +18 -1
  104. package/src/core/css/print.ts +12 -0
  105. package/src/core/css/scope.ts +3 -3
  106. package/src/core/css-keywords.ts +83 -0
  107. package/src/core/data/bindings.ts +4 -6
  108. package/src/core/design/classes.ts +13 -15
  109. package/src/core/design/diff.ts +55 -0
  110. package/src/core/design/merge.ts +127 -0
  111. package/src/core/design/variables.ts +25 -21
  112. package/src/core/elements/dynamic-elements.ts +30 -0
  113. package/src/core/elements/form-elements.ts +20 -3
  114. package/src/core/elements/index.ts +211 -7
  115. package/src/core/forms/binding.ts +4 -13
  116. package/src/core/index.ts +10 -0
  117. package/src/core/local-style.ts +27 -0
  118. package/src/core/migrate/index.ts +9 -4
  119. package/src/core/nesting.ts +4 -23
  120. package/src/core/perf/scripts.ts +9 -6
  121. package/src/core/record.ts +3 -0
  122. package/src/core/render/context.ts +2 -0
  123. package/src/core/render/dynamic-post.ts +22 -7
  124. package/src/core/render/form.ts +145 -15
  125. package/src/core/render/index.ts +195 -14
  126. package/src/core/render/pagination.ts +21 -2
  127. package/src/core/render/vnode.ts +12 -2
  128. package/src/core/sanitize/css.ts +90 -77
  129. package/src/core/sanitize/embed-url.ts +7 -1
  130. package/src/core/sanitize/href.ts +13 -1
  131. package/src/core/sanitize/svg.ts +8 -3
  132. package/src/core/sanitize/url.ts +10 -1
  133. package/src/core/schema/descriptors.ts +4 -1
  134. package/src/core/schema/design.ts +5 -7
  135. package/src/core/schema/layout.ts +160 -181
  136. package/src/core/schema/style.ts +53 -63
  137. package/src/core/share/link.ts +72 -29
  138. package/src/core/tabs/presence.ts +7 -17
  139. package/src/core/theme/dynamic.ts +205 -39
  140. package/src/core/theme/float.ts +1 -1
  141. package/src/core/tree-ops.ts +57 -0
  142. package/src/index.ts +14 -2
  143. package/src/mcp/errors.ts +44 -0
  144. package/src/mcp/index.ts +4 -0
  145. package/src/mcp/ports.ts +78 -0
  146. package/src/mcp/prompts.ts +76 -0
  147. package/src/mcp/publish.ts +60 -0
  148. package/src/mcp/queue.ts +19 -0
  149. package/src/mcp/rate-limit.ts +80 -0
  150. package/src/mcp/read.ts +419 -0
  151. package/src/mcp/refs.ts +84 -0
  152. package/src/mcp/settings.ts +18 -0
  153. package/src/mcp/tools.ts +265 -0
  154. package/src/mcp/write.ts +582 -0
  155. package/src/server/agent-settings.ts +134 -0
  156. package/src/server/design-routes.ts +75 -18
  157. package/src/server/icon-routes.ts +72 -16
  158. package/src/server/mcp-routes.ts +265 -0
  159. package/src/server/plugin.ts +40 -4
  160. package/src/admin/editor/icons/sets/fontawesome.json +0 -1
  161. package/src/admin/editor/icons/sets/lucide.json +0 -1
  162. package/src/admin/editor/icons/sets/remix.json +0 -1
  163. package/src/admin/editor/icons/sets/tabler.json +0 -1
@@ -1,8 +1,13 @@
1
1
  import type { VisitorInfo } from "../audience/rules.ts";
2
2
  import type { ArchivePagination } from "./pagination.ts";
3
3
  import type { Layout, LayoutNode } from "../schema/layout.ts";
4
- import { isParentNode } from "../schema/layout.ts";
4
+ import { LOOP_FILTER, LOOP_PERMALINK } from "../schema/layout.ts";
5
+ import { forEachNode, knownChildren } from "../tree-ops.ts";
6
+ import { isRecord } from "../record.ts";
7
+
8
+ const FIELD_SLUG = /^[a-z][a-z0-9_]{0,63}$/;
5
9
  import type { VNode } from "../render/vnode.ts";
10
+ import { sanitizeHref } from "../sanitize/href.ts";
6
11
 
7
12
  /** Normalized post fields for server-side theme binding (framework-free). */
8
13
  export type ThemePostFields = {
@@ -71,22 +76,94 @@ export const SAMPLE_POST: ThemePostFields = {
71
76
  featuredImageAlt: "Featured image",
72
77
  };
73
78
 
74
- const isRecord = (value: unknown): value is Record<string, unknown> =>
75
- Boolean(value) && typeof value === "object";
79
+ const BLOCK_STYLES = new Set(["normal", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote"]);
80
+ /** Portable Text decorators kept as their HTML element (W-328). */
81
+ const DECORATORS: Record<string, string> = {
82
+ strong: "strong",
83
+ em: "em",
84
+ code: "code",
85
+ underline: "u",
86
+ "strike-through": "s",
87
+ };
88
+ const MAX_LIST_DEPTH = 6;
89
+
90
+ /** The links a block defines (`markDefs`), by key, with hrefs that pass the link check. */
91
+ function linkDefs(block: Record<string, unknown>): Map<string, string> {
92
+ const links = new Map<string, string>();
93
+ const defs = Array.isArray(block["markDefs"]) ? block["markDefs"] : [];
94
+ for (const def of defs) {
95
+ if (!isRecord(def) || def["_type"] !== "link" || typeof def["_key"] !== "string") continue;
96
+ const href = typeof def["href"] === "string" ? sanitizeHref(def["href"]) : undefined;
97
+ if (href) links.set(def["_key"], href);
98
+ }
99
+ return links;
100
+ }
101
+
102
+ /** A span's text wrapped in its marks; unknown marks and unsafe links leave plain text. */
103
+ function spanNode(
104
+ span: Record<string, unknown>,
105
+ links: Map<string, string>,
106
+ ): VNode | string | null {
107
+ const text = typeof span["text"] === "string" ? span["text"] : "";
108
+ if (!text) return null;
109
+ const marks = Array.isArray(span["marks"])
110
+ ? span["marks"].filter((m) => typeof m === "string")
111
+ : [];
112
+ let node: VNode | string = text;
113
+ // W-392: a link can't hold a link, so only the span's first (outermost) link mark is kept.
114
+ const link = marks.find((mark) => !DECORATORS[mark] && links.has(mark));
115
+ for (const mark of new Set(marks.toReversed())) {
116
+ const tag = DECORATORS[mark];
117
+ if (tag) node = { tag, attrs: {}, children: [node] };
118
+ else if (mark === link) {
119
+ node = { tag: "a", attrs: { href: links.get(mark) as string }, children: [node] };
120
+ }
121
+ }
122
+ return node;
123
+ }
124
+
125
+ /** A block's spans, with line breaks kept as `<br>`. */
126
+ function inlineNodes(block: Record<string, unknown>): (VNode | string)[] {
127
+ const links = linkDefs(block);
128
+ const children = Array.isArray(block["children"]) ? block["children"] : [];
129
+ const out: (VNode | string)[] = [];
130
+ for (const child of children) {
131
+ if (!isRecord(child) || (child["_type"] !== undefined && child["_type"] !== "span")) continue;
132
+ const node = spanNode(child, links);
133
+ if (node === null) continue;
134
+ if (typeof node === "string" && node.includes("\n")) {
135
+ node.split("\n").forEach((part, i) => {
136
+ if (i > 0) out.push({ tag: "br", attrs: {}, children: [] });
137
+ if (part) out.push(part);
138
+ });
139
+ } else out.push(node);
140
+ }
141
+ return out;
142
+ }
76
143
 
77
- const spanText = (children: unknown) =>
78
- Array.isArray(children)
79
- ? children
80
- .filter(isRecord)
81
- .map((span) => (typeof span["text"] === "string" ? span["text"] : ""))
82
- .join("")
83
- : "";
144
+ /** Adjacent text joined, and the block's outer whitespace trimmed, as before W-328. */
145
+ function tidy(nodes: (VNode | string)[]): (VNode | string)[] {
146
+ const out: (VNode | string)[] = [];
147
+ for (const node of nodes) {
148
+ const last = out.at(-1);
149
+ if (typeof node === "string" && typeof last === "string") out[out.length - 1] = last + node;
150
+ else out.push(node);
151
+ }
152
+ const first = out[0];
153
+ if (typeof first === "string") out[0] = first.trimStart();
154
+ const end = out.at(-1);
155
+ if (typeof end === "string") out[out.length - 1] = end.trimEnd();
156
+ return out.filter((node) => node !== "");
157
+ }
84
158
 
85
- const HEADING_STYLES = new Set(["h1", "h2", "h3", "h4"]);
159
+ const hasText = (nodes: readonly (VNode | string)[]): boolean =>
160
+ nodes.some((n) => (typeof n === "string" ? n.trim() !== "" : hasText(n.children)));
86
161
 
87
162
  /**
88
- * Convert Portable Text (or a plain string) into safe VNodes.
89
- * Marks are flattened to escaped text; only block structure is preserved.
163
+ * Convert Portable Text (or a plain string) into safe VNodes (W-328). Kept: paragraphs, headings
164
+ * (h1–h6), block quotes, bulleted and numbered lists (nested by level), bold, italic, code,
165
+ * underline, strike-through and links whose href passes the link check. Everything else (custom
166
+ * blocks, images, embeds, raw HTML) is left out; text is always escaped by the serializer.
90
167
  */
91
168
  export function portableTextToVNodes(value: unknown): VNode[] {
92
169
  if (typeof value === "string") {
@@ -94,32 +171,66 @@ export function portableTextToVNodes(value: unknown): VNode[] {
94
171
  return trimmed ? [{ tag: "p", attrs: {}, children: [trimmed] }] : [];
95
172
  }
96
173
  if (!Array.isArray(value)) return [];
97
- return value.flatMap((block): VNode[] => {
98
- if (!isRecord(block) || block["_type"] !== "block") return [];
99
- const text = spanText(block["children"]).trim();
100
- if (!text) return [];
101
- const style = block["style"];
102
- const tag = typeof style === "string" && HEADING_STYLES.has(style) ? style : "p";
103
- return [{ tag, attrs: {}, children: [text] }];
104
- });
174
+ const out: VNode[] = [];
175
+ // The open lists, outermost first, while consecutive list items continue them.
176
+ let lists: VNode[] = [];
177
+ for (const block of value) {
178
+ if (!isRecord(block) || block["_type"] !== "block") {
179
+ lists = [];
180
+ continue;
181
+ }
182
+ const inline = tidy(inlineNodes(block));
183
+ const listItem = block["listItem"];
184
+ if (listItem === "bullet" || listItem === "number") {
185
+ const tag = listItem === "number" ? "ol" : "ul";
186
+ const rawLevel = typeof block["level"] === "number" ? Math.floor(block["level"]) : 1;
187
+ const level = Math.min(Math.max(rawLevel, 1), MAX_LIST_DEPTH);
188
+ lists = lists.slice(0, level);
189
+ if (lists.length === level && lists[level - 1]?.tag !== tag)
190
+ lists = lists.slice(0, level - 1);
191
+ while (lists.length < level) {
192
+ const list: VNode = { tag, attrs: {}, children: [] };
193
+ const parent = lists.at(-1);
194
+ if (parent) {
195
+ const lastItem = parent.children.at(-1);
196
+ if (lastItem && typeof lastItem !== "string") lastItem.children.push(list);
197
+ else parent.children.push({ tag: "li", attrs: {}, children: [list] });
198
+ } else out.push(list);
199
+ lists.push(list);
200
+ }
201
+ if (hasText(inline))
202
+ lists[level - 1]?.children.push({ tag: "li", attrs: {}, children: inline });
203
+ continue;
204
+ }
205
+ lists = [];
206
+ if (!hasText(inline)) continue;
207
+ const style =
208
+ typeof block["style"] === "string" && BLOCK_STYLES.has(block["style"])
209
+ ? block["style"]
210
+ : "normal";
211
+ const tag = style === "normal" ? "p" : style;
212
+ out.push({ tag, attrs: {}, children: inline });
213
+ }
214
+ return out.filter((node) =>
215
+ node.tag !== "ul" && node.tag !== "ol" ? true : node.children.length > 0,
216
+ );
105
217
  }
106
218
 
107
219
  /** Collect `loop.itemPartId` values so hosts can load Loop Item templates. */
108
220
  export function collectLoopItemPartIds(layout: Layout): string[] {
109
221
  const ids = new Set<string>();
110
- const walk = (node: LayoutNode): void => {
111
- if (node.type === "loop") {
222
+ forEachNode(
223
+ layout.root,
224
+ (node) => {
225
+ if (node.type !== "loop") return;
112
226
  const id =
113
227
  typeof (node.props as { itemPartId?: unknown }).itemPartId === "string"
114
228
  ? (node.props as { itemPartId: string }).itemPartId.trim()
115
229
  : "";
116
230
  if (id) ids.add(id);
117
- }
118
- if (isParentNode(node)) {
119
- for (const child of node.children) walk(child);
120
- }
121
- };
122
- walk(layout.root);
231
+ },
232
+ knownChildren,
233
+ );
123
234
  return [...ids];
124
235
  }
125
236
 
@@ -129,28 +240,86 @@ export type CollectionLoop = {
129
240
  collection: string;
130
241
  limit: number;
131
242
  order: "newest" | "oldest" | "title";
243
+ /** W-330: where entries link, the image and excerpt fields, and `field = value` filters. */
244
+ permalink?: string;
245
+ imageField?: string;
246
+ excerptField?: string;
247
+ where?: Record<string, string | string[]>;
132
248
  };
133
249
 
250
+ const MAX_LOOP_FILTERS = 5;
251
+
252
+ /**
253
+ * `category=news; team=design` → `{ category: "news", team: "design" }` (W-330); the same field
254
+ * twice becomes a list (either value). At most 5 pairs; anything malformed is left out.
255
+ */
256
+ export function parseLoopFilter(text: unknown): Record<string, string | string[]> | undefined {
257
+ if (typeof text !== "string" || !LOOP_FILTER.test(text)) return undefined;
258
+ // W-391: a field named like an Object method (`constructor`) starts empty too.
259
+ const where: Record<string, string | string[]> = Object.create(null) as Record<
260
+ string,
261
+ string | string[]
262
+ >;
263
+ let count = 0;
264
+ for (const pair of text.split(";")) {
265
+ const at = pair.indexOf("=");
266
+ if (at < 0) continue;
267
+ const field = pair.slice(0, at).trim();
268
+ const value = pair.slice(at + 1).trim();
269
+ if (!field || !value || count >= MAX_LOOP_FILTERS) continue;
270
+ count += 1;
271
+ const had = Object.hasOwn(where, field) ? where[field] : undefined;
272
+ where[field] = had === undefined ? value : [...(Array.isArray(had) ? had : [had]), value];
273
+ }
274
+ return count > 0 ? Object.fromEntries(Object.entries(where)) : undefined;
275
+ }
276
+
277
+ /** An entry's link from a Loop's pattern (W-330): `{slug}` and `{id}` filled in, URL-encoded. */
278
+ export function loopPermalink(pattern: string, entry: { slug: string; id: string }): string {
279
+ return pattern
280
+ .replaceAll("{slug}", encodeURIComponent(entry.slug))
281
+ .replaceAll("{id}", encodeURIComponent(entry.id));
282
+ }
283
+
134
284
  /** Every collection Loop in a layout, so hosts can fetch their entries (W-308). */
135
285
  export function collectCollectionLoops(layout: Layout): CollectionLoop[] {
136
286
  const loops: CollectionLoop[] = [];
137
287
  const walk = (node: LayoutNode): void => {
138
288
  if (node.type === "loop" && loops.length < 20) {
139
- const props = node.props as { collection?: unknown; limit?: unknown; order?: unknown };
289
+ const props = node.props as {
290
+ collection?: unknown;
291
+ limit?: unknown;
292
+ order?: unknown;
293
+ permalink?: unknown;
294
+ imageField?: unknown;
295
+ excerptField?: unknown;
296
+ filter?: unknown;
297
+ };
140
298
  if (typeof props.collection === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(props.collection)) {
141
299
  const limit =
142
300
  typeof props.limit === "number" && props.limit >= 1 && props.limit <= 50
143
301
  ? Math.floor(props.limit)
144
302
  : 6;
145
303
  const order = props.order === "oldest" || props.order === "title" ? props.order : "newest";
146
- loops.push({ nodeId: node.id, collection: props.collection, limit, order });
304
+ const loop: CollectionLoop = {
305
+ nodeId: node.id,
306
+ collection: props.collection,
307
+ limit,
308
+ order,
309
+ };
310
+ if (typeof props.permalink === "string" && LOOP_PERMALINK.test(props.permalink))
311
+ loop.permalink = props.permalink;
312
+ if (typeof props.imageField === "string" && FIELD_SLUG.test(props.imageField))
313
+ loop.imageField = props.imageField;
314
+ if (typeof props.excerptField === "string" && FIELD_SLUG.test(props.excerptField))
315
+ loop.excerptField = props.excerptField;
316
+ const where = parseLoopFilter(props.filter);
317
+ if (where) loop.where = where;
318
+ loops.push(loop);
147
319
  }
148
320
  }
149
- if (isParentNode(node)) {
150
- for (const child of node.children) walk(child);
151
- }
152
321
  };
153
- walk(layout.root);
322
+ forEachNode(layout.root, walk, knownChildren);
154
323
  return loops;
155
324
  }
156
325
 
@@ -165,11 +334,8 @@ export function collectSectionPartIds(layout: Layout): string[] {
165
334
  : "";
166
335
  if (id) ids.add(id);
167
336
  }
168
- if (isParentNode(node)) {
169
- for (const child of node.children) walk(child);
170
- }
171
337
  };
172
- walk(layout.root);
338
+ forEachNode(layout.root, walk, knownChildren);
173
339
  return [...ids];
174
340
  }
175
341
 
@@ -100,7 +100,7 @@ export function wrapFloatMarkup(
100
100
  ): string {
101
101
  const safeId = escapeAttr(id);
102
102
  const label = escapeAttr(title.trim() || "Notice");
103
- const edge = settings.edge;
103
+ const edge = escapeAttr(settings.edge);
104
104
  const close = settings.dismiss
105
105
  ? `<button type="button" class="emvb-float__close" data-emvb-float-dismiss aria-label="Close"><span aria-hidden="true">×</span></button>`
106
106
  : "";
@@ -14,6 +14,63 @@ export const nodeChildren = (node: LayoutNode): LayoutNode[] => {
14
14
  return [];
15
15
  };
16
16
 
17
+ /** Children of a known parent only. Unknown nodes are not descended into (W-353). */
18
+ export const knownChildren = (node: LayoutNode): readonly LayoutNode[] =>
19
+ isParentNode(node) ? node.children : [];
20
+
21
+ /** Visit `node` and every node under it. Pass `knownChildren` to skip unknown nodes. */
22
+ export function forEachNode(
23
+ node: LayoutNode,
24
+ visit: (node: LayoutNode) => void,
25
+ children: (node: LayoutNode) => readonly LayoutNode[] = nodeChildren,
26
+ ): void {
27
+ visit(node);
28
+ for (const child of children(node)) forEachNode(child, visit, children);
29
+ }
30
+
31
+ /** True when `test` matches `node` or anything under it. Same descent choice as `forEachNode`. */
32
+ export function someNode(
33
+ node: LayoutNode,
34
+ test: (node: LayoutNode) => boolean,
35
+ children: (node: LayoutNode) => readonly LayoutNode[] = nodeChildren,
36
+ ): boolean {
37
+ return test(node) || children(node).some((child) => someNode(child, test, children));
38
+ }
39
+
40
+ export type LayoutIndex = {
41
+ byId: Map<string, LayoutNode>;
42
+ /** Parent id for a node under a container or form. A child of an unknown node has none. */
43
+ parentOf: Map<string, string>;
44
+ };
45
+
46
+ const indexes = new WeakMap<Layout, LayoutIndex>();
47
+
48
+ /**
49
+ * One walk for later id and parent lookups. The same layout object keeps the result, so a render
50
+ * that asks many times walks once. A page stays within 2000 elements and 24 levels.
51
+ */
52
+ export function indexLayout(layout: Layout): LayoutIndex {
53
+ const cached = indexes.get(layout);
54
+ if (cached) return cached;
55
+ const byId = new Map<string, LayoutNode>();
56
+ const parents = new Map<string, string>();
57
+ const seen = new Set<LayoutNode>();
58
+ const walk = (node: LayoutNode, parentId: string | undefined) => {
59
+ if (seen.has(node)) return;
60
+ seen.add(node);
61
+ if (!byId.has(node.id)) {
62
+ byId.set(node.id, node);
63
+ if (parentId) parents.set(node.id, parentId);
64
+ }
65
+ const nextParent = isParentNode(node) ? node.id : undefined;
66
+ for (const child of nodeChildren(node)) walk(child, nextParent);
67
+ };
68
+ walk(layout.root, undefined);
69
+ const index: LayoutIndex = { byId, parentOf: parents };
70
+ indexes.set(layout, index);
71
+ return index;
72
+ }
73
+
17
74
  /** Where a removed node was, so it can be put back exactly (the Restore toast, D-025). */
18
75
  export type Removed = { node: LayoutNode; parentId: string; index: number };
19
76
 
package/src/index.ts CHANGED
@@ -1,16 +1,28 @@
1
1
  import type { PluginDescriptor } from "emdash";
2
2
  import { ADMIN_ENTRY, PACKAGE_NAME, PLUGIN_ID, PLUGIN_VERSION } from "./constants.ts";
3
+ import { canvasStyleUrls } from "./core/canvas-styles.ts";
3
4
  import { createPlugin } from "./server/plugin.ts";
4
5
 
6
+ /** Options a host site passes to `emvb()` in astro.config. */
7
+ export type EmVBOptions = {
8
+ /**
9
+ * Stylesheets the editor canvas loads before EmVB's CSS (W-327): the site's fonts and base
10
+ * styles, so pages look in the editor as on the site. `https:` URLs or site paths
11
+ * (`/styles/site.css`); anything else is ignored.
12
+ */
13
+ canvasStyles?: string[];
14
+ };
15
+
5
16
  /** Descriptor that host sites add to `emdash({ plugins: [...] })` in astro.config. */
6
- export function emvb(): PluginDescriptor {
17
+ export function emvb(options: EmVBOptions = {}): PluginDescriptor {
18
+ const canvasStyles = canvasStyleUrls(options.canvasStyles);
7
19
  return {
8
20
  id: PLUGIN_ID,
9
21
  version: PLUGIN_VERSION,
10
22
  format: "native",
11
23
  entrypoint: PACKAGE_NAME,
12
24
  adminEntry: ADMIN_ENTRY,
13
- options: {},
25
+ options: canvasStyles.length > 0 ? { canvasStyles } : {},
14
26
  };
15
27
  }
16
28
 
@@ -0,0 +1,44 @@
1
+ /** Error codes an MCP tool reports back to the agent (plan § 2 Errors). */
2
+ export type McpErrorCode =
3
+ | "INVALID_INPUT"
4
+ | "INVALID_LAYOUT"
5
+ | "NESTING"
6
+ | "NOT_FOUND"
7
+ | "CONFLICT"
8
+ | "PUBLISH_DISABLED"
9
+ | "FORBIDDEN"
10
+ | "TOO_LARGE"
11
+ | "REFUSED"
12
+ | "NOT_SET_UP"
13
+ | "RATE_LIMITED";
14
+
15
+ const STATUS: Record<McpErrorCode, number> = {
16
+ INVALID_INPUT: 400,
17
+ INVALID_LAYOUT: 422,
18
+ NESTING: 422,
19
+ NOT_FOUND: 404,
20
+ CONFLICT: 409,
21
+ PUBLISH_DISABLED: 403,
22
+ FORBIDDEN: 403,
23
+ TOO_LARGE: 413,
24
+ REFUSED: 422,
25
+ NOT_SET_UP: 409,
26
+ RATE_LIMITED: 429,
27
+ };
28
+
29
+ /**
30
+ * A tool failure the agent can act on. Routes turn it into a `PluginRouteError`, which EmDash's
31
+ * MCP server reports as a tool result with `isError: true`, not a protocol error (SEP-1303).
32
+ */
33
+ export class McpToolError extends Error {
34
+ readonly code: McpErrorCode;
35
+ readonly status: number;
36
+ readonly details?: Record<string, unknown>;
37
+ constructor(code: McpErrorCode, message: string, details?: Record<string, unknown>) {
38
+ super(message);
39
+ this.name = "McpToolError";
40
+ this.code = code;
41
+ this.status = STATUS[code];
42
+ if (details) this.details = details;
43
+ }
44
+ }
@@ -0,0 +1,4 @@
1
+ /** `@perkyzz/emvb/mcp`: the shared MCP tool definitions the stdio bridge lists (D-053). */
2
+ export { TOOLS, visibleTools, type ToolDef } from "./tools.ts";
3
+ export { RATE_LIMITS, type RateClass } from "./rate-limit.ts";
4
+ export { PROMPTS, designJsonSchema, layoutJsonSchema, type PromptDef } from "./prompts.ts";
@@ -0,0 +1,78 @@
1
+ import type { AgentSettings } from "./settings.ts";
2
+ import type { RateClass } from "./rate-limit.ts";
3
+ import type { DesignSystem, Layout } from "../core/index.ts";
4
+
5
+ /** A page as the tool core sees it: the current draft (or published) data and its revision. */
6
+ export type PageRecord = {
7
+ id: string;
8
+ title: string;
9
+ slug: string;
10
+ status: string;
11
+ /** True when a saved draft differs from what is live. */
12
+ hasDraft: boolean;
13
+ layout: unknown;
14
+ /** EmDash `_rev`; writes check it (D-058). */
15
+ rev: string;
16
+ updatedAt: string;
17
+ };
18
+
19
+ export type PageSummary = Omit<PageRecord, "layout" | "rev">;
20
+
21
+ export type RevisionSummary = { id: string; createdAt: string; authorId: string | null };
22
+
23
+ export type DesignState = {
24
+ design: DesignSystem;
25
+ revision: string | null;
26
+ publishedRevision: string | null;
27
+ unpublished: boolean;
28
+ };
29
+
30
+ /** Who is calling. EmDash has already checked the token scope and the editor role (D-056). */
31
+ export type Caller = { userId: string | null; role: number; client?: string };
32
+
33
+ /** One agent change, shown in the Timeline and the Agents tab (D-057). */
34
+ export type AgentLogEntry = {
35
+ target: "page" | "styles";
36
+ tool: string;
37
+ pageId?: string;
38
+ rev?: string;
39
+ revisionId?: string;
40
+ summary: string;
41
+ };
42
+
43
+ /**
44
+ * Everything the tool core reads or writes goes through these ports (D-053). The plugin builds
45
+ * them on `ctx.content` and plugin storage; tests build them in memory.
46
+ */
47
+ export interface EmvbPorts {
48
+ caller: Caller;
49
+ /** Counts the call against the caller's rate limit; throws RATE_LIMITED when full (W-478). */
50
+ rateLimit?(cls: RateClass): Promise<void>;
51
+ listPages(options: { cursor?: string; limit: number }): Promise<{
52
+ pages: PageSummary[];
53
+ nextCursor?: string;
54
+ }>;
55
+ getPage(id: string): Promise<PageRecord | null>;
56
+ listRevisions(id: string, limit: number): Promise<RevisionSummary[]>;
57
+ getDesign(): Promise<DesignState>;
58
+ getRevisionData(pageId: string, revisionId: string): Promise<Record<string, unknown> | null>;
59
+ /** Writes the draft when the stored `_rev` is still `expectedRev`; else McpToolError CONFLICT. */
60
+ savePage(
61
+ id: string,
62
+ patch: { layout?: Layout; title?: string },
63
+ expectedRev: string,
64
+ ): Promise<{ rev: string; revisionId?: string }>;
65
+ createPage(input: {
66
+ title: string;
67
+ layout: Layout;
68
+ }): Promise<{ id: string; slug: string; rev: string }>;
69
+ /** Saves the style draft with compare-and-set; McpToolError CONFLICT when it moved. */
70
+ saveDesign(design: DesignSystem, expectedRevision: string | null): Promise<{ revision: string }>;
71
+ log(entry: AgentLogEntry): Promise<void>;
72
+ /** The admin's agent settings (D-055). Read-only for tools. */
73
+ settings(): Promise<AgentSettings>;
74
+ /** Publishes the page when its `_rev` is still `expectedRev`; else McpToolError CONFLICT. */
75
+ publishPage(id: string, expectedRev: string): Promise<{ rev: string }>;
76
+ /** Publishes the style draft when the published revision is still `expectedPublishedRevision`. */
77
+ publishDesign(expectedPublishedRevision: string | null): Promise<{ revision: string }>;
78
+ }
@@ -0,0 +1,76 @@
1
+ import { z } from "zod";
2
+ import { DesignSystem } from "../core/schema/design.ts";
3
+ import { Layout } from "../core/schema/layout.ts";
4
+
5
+ /** JSON Schema (2020-12) of a stored layout, for `emvb://schema/layout` (W-467). */
6
+ export const layoutJsonSchema = () =>
7
+ z.toJSONSchema(Layout, { io: "input", unrepresentable: "any" });
8
+
9
+ /** JSON Schema of the design system (site styles), for `emvb://schema/design`. */
10
+ export const designJsonSchema = () =>
11
+ z.toJSONSchema(DesignSystem, { io: "input", unrepresentable: "any" });
12
+
13
+ export type PromptDef = {
14
+ name: string;
15
+ title: string;
16
+ description: string;
17
+ args: Record<string, { description: string; required: boolean }>;
18
+ text(args: Record<string, string | undefined>): string;
19
+ };
20
+
21
+ const list = (value: string | undefined) =>
22
+ value ? ` Sections to include: ${JSON.stringify(value)}.` : "";
23
+
24
+ /** Arguments are the person's data: quoted as JSON strings, never spliced in as instructions. */
25
+ const q = (value: string | undefined) => JSON.stringify(value ?? "");
26
+
27
+ /** Workflow prompts (plan § 3 Prompts). They only describe steps; the tools do the work. */
28
+ export const PROMPTS: PromptDef[] = [
29
+ {
30
+ name: "build_landing_page",
31
+ title: "Build a landing page",
32
+ description:
33
+ "Plan and build a new draft landing page from a topic, ready for a person to review.",
34
+ args: {
35
+ topic: { description: "What the page is about", required: true },
36
+ audience: { description: "Who it is for", required: false },
37
+ sections: { description: "Sections to include, comma-separated", required: false },
38
+ },
39
+ text: (a) =>
40
+ `Build a draft EmVB landing page about ${q(a["topic"])}${a["audience"] ? ` for ${q(a["audience"])}` : ""}.${list(a["sections"])}
41
+ 1. Call get_site_styles and list_section_recipes. If the site has no Brand, Ink, Muted and Surface colours or fs-*/space-* sizes, propose them first (see the skill's design reference); recipes and your styles use them.
42
+ 2. Call create_page with a clear title and the recipes that fit, hero first: the hero heading becomes the page's h1.
43
+ 3. Replace placeholder copy with update_element, passing the rev each write returns as the next expectedRev. Real copy, real links, alt text that describes each image.
44
+ 4. Call get_accessibility_findings and fix every error.
45
+ 5. Do not publish. Finish with describe_page and a short summary for the person to review.`,
46
+ },
47
+ {
48
+ name: "fix_accessibility",
49
+ title: "Fix accessibility findings",
50
+ description: "Fix the accessibility findings on one page, then re-check.",
51
+ args: { pageId: { description: "The page id (from list_pages)", required: true } },
52
+ text: (a) =>
53
+ `Fix the accessibility findings on page ${q(a["pageId"])}.
54
+ 1. Call get_layout (format "outline") for the rev, then get_accessibility_findings.
55
+ 2. For each finding, apply its fix with update_element on its nodeId: fix.kind "heading-level" → set.props.level; "text-color" → set.style.color; "decorative" → set.props.decorative true, but only when the image adds nothing; otherwise set.props.alt to words that describe it; "drop-aria-hidden" → set.attributes to its list without the aria-hidden entry. A finding without a fix: follow its message.
56
+ 3. Pass the rev from your last read as expectedRev on the first write, then the rev each write returns on the next one.
57
+ 4. When several contrast findings share one site colour, darken or lighten that colour variable once with update_site_styles instead of overriding each element; keep the design's palette. Keep sibling headings at the same level.
58
+ 5. Call get_accessibility_findings again and report what is left. Do not publish.`,
59
+ },
60
+ {
61
+ name: "restyle_site",
62
+ title: "Restyle the site",
63
+ description: "Propose and apply site style changes to the style draft only.",
64
+ args: { brief: { description: "The look you want", required: true } },
65
+ text: (a) =>
66
+ `Restyle the site to match: ${q(a["brief"])}. Call get_site_styles, propose variable and class changes, then apply them with update_site_styles (draft only). Keep the variable names recipes look for (Brand, Ink, Muted, Surface, On brand; fs-* and space-* ids; Button and Card classes). Check text colours against their backgrounds for 4.5:1 contrast. Never remove a variable that is in use. Do not publish; a person reviews the style draft.`,
67
+ },
68
+ {
69
+ name: "review_page",
70
+ title: "Review a page",
71
+ description: "Write a review of one page without changing it.",
72
+ args: { pageId: { description: "The page id (from list_pages)", required: true } },
73
+ text: (a) =>
74
+ `Review page ${q(a["pageId"])} without editing it: call describe_page (sections, heading outline, images with their alt text) and get_accessibility_findings, and get_layout when you need styles or ids. Then write a short review covering structure, copy, images and alt text, accessibility, and consistency with the site styles, with the element ids for each suggestion.`,
75
+ },
76
+ ];