@perkyzz/emvb 0.5.0 → 0.7.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 (212) hide show
  1. package/README.md +4 -0
  2. package/THIRD_PARTY_NOTICES.md +23 -1
  3. package/licenses/exif-js.LICENSE +21 -0
  4. package/licenses/fflate.LICENSE +21 -0
  5. package/licenses/glfx.js.LICENSE +19 -0
  6. package/licenses/mini-photo-editor.LICENSE +21 -0
  7. package/licenses/photocn.LICENSE +21 -0
  8. package/package.json +2 -1
  9. package/src/admin/access/RequireEditor.tsx +7 -7
  10. package/src/admin/access/role.ts +5 -2
  11. package/src/admin/content-api.ts +10 -3
  12. package/src/admin/content-item.ts +1 -1
  13. package/src/admin/editor/A11yCopilot.tsx +104 -56
  14. package/src/admin/editor/CommandPalette.tsx +29 -13
  15. package/src/admin/editor/Editor.tsx +88 -20
  16. package/src/admin/editor/EditorToasts.tsx +26 -0
  17. package/src/admin/editor/PerfMeter.tsx +97 -72
  18. package/src/admin/editor/ShareLink.tsx +107 -72
  19. package/src/admin/editor/ShortcutsDialog.tsx +27 -16
  20. package/src/admin/editor/Timeline.tsx +255 -160
  21. package/src/admin/editor/TopBar.tsx +71 -14
  22. package/src/admin/editor/canvas/CanvasFrame.tsx +10 -1
  23. package/src/admin/editor/canvas/CanvasTextEdit.tsx +8 -2
  24. package/src/admin/editor/canvas/drop-line.ts +11 -3
  25. package/src/admin/editor/canvas/frame-focus-ring.ts +37 -0
  26. package/src/admin/editor/canvas/use-canvas-dnd.ts +32 -3
  27. package/src/admin/editor/canvas/vnode-react.tsx +7 -0
  28. package/src/admin/editor/collection-previews.ts +16 -1
  29. package/src/admin/editor/dialogs.tsx +38 -14
  30. package/src/admin/editor/dnd/drop-target.ts +26 -1
  31. package/src/admin/editor/edited-noun.ts +15 -0
  32. package/src/admin/editor/editor-chrome.tsx +108 -7
  33. package/src/admin/editor/editor-commands.ts +15 -1
  34. package/src/admin/editor/editor-css.ts +75 -22
  35. package/src/admin/editor/element-chrome.ts +21 -11
  36. package/src/admin/editor/feature-css.ts +45 -13
  37. package/src/admin/editor/icons/IconLibraryDialog.tsx +52 -11
  38. package/src/admin/editor/icons/library.ts +1 -1
  39. package/src/admin/editor/icons/use-icon-library.ts +5 -2
  40. package/src/admin/editor/ime.ts +29 -0
  41. package/src/admin/editor/palette-items.ts +10 -3
  42. package/src/admin/editor/panels/AddPanel.tsx +35 -10
  43. package/src/admin/editor/panels/ClassesSection.tsx +18 -7
  44. package/src/admin/editor/panels/ColorControl.tsx +135 -27
  45. package/src/admin/editor/panels/ConditionsEditor.tsx +52 -26
  46. package/src/admin/editor/panels/ElementPanel.tsx +134 -24
  47. package/src/admin/editor/panels/LayersPanel.tsx +68 -22
  48. package/src/admin/editor/panels/PageSettings.tsx +66 -35
  49. package/src/admin/editor/panels/SiteStylesDrawer.tsx +170 -32
  50. package/src/admin/editor/panels/TokenScales.tsx +76 -36
  51. package/src/admin/editor/panels/TriggerSettings.tsx +50 -12
  52. package/src/admin/editor/panels/TriggersEditor.tsx +2 -1
  53. package/src/admin/editor/panels/VariableSection.tsx +53 -21
  54. package/src/admin/editor/panels/color-space.ts +9 -3
  55. package/src/admin/editor/panels/settings/AdvancedFields.tsx +12 -2
  56. package/src/admin/editor/panels/settings/AudienceEditor.tsx +51 -35
  57. package/src/admin/editor/panels/settings/BackgroundControls.tsx +55 -11
  58. package/src/admin/editor/panels/settings/BackgroundFill.tsx +3 -2
  59. package/src/admin/editor/panels/settings/BindingsEditor.tsx +15 -18
  60. package/src/admin/editor/panels/settings/BoxControl.tsx +2 -1
  61. package/src/admin/editor/panels/settings/ClassChip.tsx +21 -9
  62. package/src/admin/editor/panels/settings/ClassChipInput.tsx +24 -16
  63. package/src/admin/editor/panels/settings/DraftTextField.tsx +41 -3
  64. package/src/admin/editor/panels/settings/EffectsControls.tsx +38 -14
  65. package/src/admin/editor/panels/settings/FieldBindControl.tsx +46 -28
  66. package/src/admin/editor/panels/settings/FieldControl.tsx +38 -15
  67. package/src/admin/editor/panels/settings/FormBindControl.tsx +2 -2
  68. package/src/admin/editor/panels/settings/HintedSwitch.tsx +33 -0
  69. package/src/admin/editor/panels/settings/IconControls.tsx +12 -8
  70. package/src/admin/editor/panels/settings/IconPicker.tsx +2 -0
  71. package/src/admin/editor/panels/settings/ImageSourcesField.tsx +3 -1
  72. package/src/admin/editor/panels/settings/ItemList.tsx +15 -2
  73. package/src/admin/editor/panels/settings/LengthRow.tsx +8 -6
  74. package/src/admin/editor/panels/settings/MediaPicker.tsx +274 -20
  75. package/src/admin/editor/panels/settings/MotionControl.tsx +28 -15
  76. package/src/admin/editor/panels/settings/NumberRow.tsx +9 -3
  77. package/src/admin/editor/panels/settings/PanelSelect.tsx +50 -0
  78. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +25 -18
  79. package/src/admin/editor/panels/settings/RequiredFieldsNotice.tsx +141 -0
  80. package/src/admin/editor/panels/settings/StyleRow.tsx +10 -3
  81. package/src/admin/editor/panels/settings/StyleSources.tsx +4 -1
  82. package/src/admin/editor/panels/settings/VariantEditor.tsx +10 -1
  83. package/src/admin/editor/panels/settings/box-link-name.ts +6 -2
  84. package/src/admin/editor/panels/settings/class-suggest.ts +7 -7
  85. package/src/admin/editor/panels/settings/query-style.ts +38 -9
  86. package/src/admin/editor/panels/settings/svg-images.ts +13 -0
  87. package/src/admin/editor/panels/site-list.tsx +20 -6
  88. package/src/admin/editor/panels/variable-values.ts +25 -4
  89. package/src/admin/editor/restore-deleted.ts +21 -2
  90. package/src/admin/editor/section-templates.ts +81 -12
  91. package/src/admin/editor/shortcuts.ts +17 -2
  92. package/src/admin/editor/store.ts +14 -3
  93. package/src/admin/editor/useEditorCommands.ts +61 -15
  94. package/src/admin/editor/useEditorData.ts +4 -2
  95. package/src/admin/editor/useEditorShortcuts.ts +17 -7
  96. package/src/admin/editor/useNodeActions.ts +61 -6
  97. package/src/admin/editor/useSave.ts +22 -7
  98. package/src/admin/forms-api.ts +2 -0
  99. package/src/admin/image-editor/BlurFocus.tsx +112 -0
  100. package/src/admin/image-editor/Canvas.tsx +261 -0
  101. package/src/admin/image-editor/CropOverlay.tsx +390 -0
  102. package/src/admin/image-editor/CurvesPanel.tsx +395 -0
  103. package/src/admin/image-editor/ExportDialog.tsx +384 -0
  104. package/src/admin/image-editor/ImageEditButton.tsx +83 -0
  105. package/src/admin/image-editor/ImageEditorDialog.tsx +828 -0
  106. package/src/admin/image-editor/MetadataPanel.tsx +194 -0
  107. package/src/admin/image-editor/announce.tsx +65 -0
  108. package/src/admin/image-editor/crop-geometry.ts +162 -0
  109. package/src/admin/image-editor/curve-math.ts +177 -0
  110. package/src/admin/image-editor/data-url-fetch.ts +59 -0
  111. package/src/admin/image-editor/engine.ts +55 -0
  112. package/src/admin/image-editor/exif.ts +82 -0
  113. package/src/admin/image-editor/flatten.ts +54 -0
  114. package/src/admin/image-editor/gpu-fit.ts +81 -0
  115. package/src/admin/image-editor/image-editor-css.ts +400 -0
  116. package/src/admin/image-editor/load.ts +116 -0
  117. package/src/admin/image-editor/panels.tsx +287 -0
  118. package/src/admin/image-editor/parts.tsx +614 -0
  119. package/src/admin/image-editor/save.ts +141 -0
  120. package/src/admin/image-editor/tone-panels.tsx +338 -0
  121. package/src/admin/image-editor/tools.ts +59 -0
  122. package/src/admin/image-editor/worker.ts +111 -0
  123. package/src/admin/media-api.ts +114 -3
  124. package/src/admin/pages/AgentsPage.tsx +138 -27
  125. package/src/admin/pages/CreateDialog.tsx +97 -30
  126. package/src/admin/pages/NewPageDialog.tsx +21 -3
  127. package/src/admin/pages/NewThemePartDialog.tsx +11 -3
  128. package/src/admin/pages/PageList.tsx +14 -6
  129. package/src/admin/pages/SetupShell.tsx +28 -12
  130. package/src/admin/pages/ThemePartList.tsx +27 -7
  131. package/src/admin/pages/list-kit.tsx +106 -24
  132. package/src/admin/search.ts +15 -0
  133. package/src/admin/setup/useSetupStatus.ts +1 -1
  134. package/src/admin/theme-api.ts +13 -3
  135. package/src/admin/ui.ts +78 -22
  136. package/src/astro/EmVBPage.astro +11 -2
  137. package/src/astro/floats/runtime.ts +21 -0
  138. package/src/astro/menu/runtime.ts +34 -1
  139. package/src/astro/popups/runtime.ts +33 -3
  140. package/src/astro/render.ts +6 -0
  141. package/src/astro/resolve-theme.ts +67 -14
  142. package/src/astro/resolve.ts +9 -1
  143. package/src/astro/tabs/runtime.ts +12 -0
  144. package/src/astro/theme-posts.ts +2 -2
  145. package/src/astro/visitor.ts +6 -3
  146. package/src/constants.ts +1 -1
  147. package/src/core/a11y/audit.ts +171 -24
  148. package/src/core/arrange.ts +29 -6
  149. package/src/core/audience/rules.ts +5 -1
  150. package/src/core/audience/variants.ts +29 -3
  151. package/src/core/clipboard.ts +7 -0
  152. package/src/core/css/generate.ts +31 -6
  153. package/src/core/data/bindings.ts +19 -6
  154. package/src/core/design/classes.ts +20 -9
  155. package/src/core/design/diff.ts +9 -1
  156. package/src/core/design/merge.ts +93 -3
  157. package/src/core/design/tokens.ts +16 -2
  158. package/src/core/design/transfer.ts +46 -8
  159. package/src/core/design/variables.ts +32 -10
  160. package/src/core/elements/dynamic-elements.ts +53 -6
  161. package/src/core/elements/form-elements.ts +68 -30
  162. package/src/core/elements/index.ts +83 -38
  163. package/src/core/elements/menu.ts +37 -19
  164. package/src/core/elements/plain-text.ts +2 -2
  165. package/src/core/elements/select-prompt.ts +3 -0
  166. package/src/core/elements/svg-ids.ts +39 -0
  167. package/src/core/forms/binding.ts +190 -2
  168. package/src/core/forms/definition.ts +72 -0
  169. package/src/core/history/diff.ts +49 -4
  170. package/src/core/icons/catalog.ts +3 -2
  171. package/src/core/image-edit/schema.ts +155 -0
  172. package/src/core/image-edit/summary.ts +61 -0
  173. package/src/core/index.ts +29 -1
  174. package/src/core/limits.ts +21 -0
  175. package/src/core/migrate/index.ts +3 -1
  176. package/src/core/perf/meter.ts +51 -8
  177. package/src/core/recipes/index.ts +5 -4
  178. package/src/core/render/context.ts +8 -0
  179. package/src/core/render/dynamic-post.ts +71 -13
  180. package/src/core/render/extras.ts +77 -4
  181. package/src/core/render/form.ts +164 -12
  182. package/src/core/render/index.ts +179 -22
  183. package/src/core/render/loop.ts +43 -7
  184. package/src/core/render/pagination.ts +18 -4
  185. package/src/core/render/section.ts +27 -0
  186. package/src/core/render/tabs.ts +12 -3
  187. package/src/core/render/vnode.ts +1 -1
  188. package/src/core/sanitize/css.ts +15 -2
  189. package/src/core/sanitize/embed-url.ts +42 -5
  190. package/src/core/sanitize/url.ts +2 -1
  191. package/src/core/schema/layout.ts +26 -7
  192. package/src/core/share/link.ts +5 -2
  193. package/src/core/stable-json.ts +15 -0
  194. package/src/core/stats.ts +2 -1
  195. package/src/core/theme/conditions.ts +3 -1
  196. package/src/core/theme/dynamic.ts +57 -23
  197. package/src/core/theme/float.ts +9 -2
  198. package/src/core/theme/pagination.ts +57 -10
  199. package/src/core/theme/popup-markup.ts +23 -5
  200. package/src/core/theme/popup-rules.ts +11 -5
  201. package/src/core/theme/triggers.ts +3 -2
  202. package/src/core/tree-ops.ts +27 -0
  203. package/src/mcp/ports.ts +8 -1
  204. package/src/mcp/rate-limit.ts +2 -1
  205. package/src/mcp/read.ts +82 -3
  206. package/src/mcp/refs.ts +18 -0
  207. package/src/mcp/tools.ts +1 -1
  208. package/src/mcp/write.ts +271 -25
  209. package/src/server/agent-settings.ts +29 -4
  210. package/src/server/hooks.ts +5 -3
  211. package/src/server/icon-routes.ts +33 -9
  212. package/src/server/mcp-routes.ts +74 -11
package/src/mcp/write.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  defaultElement,
5
5
  findNode,
6
6
  MAX_LAYOUT_BYTES,
7
+ nameKey,
7
8
  nestingIssues,
8
9
  recipeNode,
9
10
  SECTION_RECIPES,
@@ -15,13 +16,19 @@ import {
15
16
  type Layout,
16
17
  type LayoutNode,
17
18
  } from "../core/index.ts";
19
+ import { stableJson } from "../core/stable-json.ts";
18
20
  import { addNode, moveNode, withFreshIds } from "../core/arrange.ts";
19
21
  import { ELEMENT_DESCRIPTORS } from "../core/elements/index.ts";
20
- import { removeNode, slugify, starterLayout, updateNode } from "../core/tree-ops.ts";
22
+ import { nodeChildren, pageSlug, removeNode, starterLayout, updateNode } from "../core/tree-ops.ts";
23
+ import { isSafeFontStack } from "../core/sanitize/css.ts";
24
+ import { sanitizeMediaUrl } from "../core/sanitize/media-url.ts";
25
+ import { sanitizeHref } from "../core/sanitize/href.ts";
26
+ import { isSafeSvgMarkup } from "../core/sanitize/svg.ts";
27
+ import { clipText, MAX_DEPTH } from "../core/limits.ts";
21
28
  import { McpToolError } from "./errors.ts";
22
29
  import type { EmvbPorts } from "./ports.ts";
23
30
  import { queued } from "./queue.ts";
24
- import { resolveDesignRefs } from "./refs.ts";
31
+ import { nestsDeeperThan, resolveDesignRefs } from "./refs.ts";
25
32
  import {
26
33
  findVariableUsages,
27
34
  findVariableUsagesInDesign,
@@ -109,7 +116,15 @@ async function mutatePage(
109
116
  );
110
117
  }
111
118
  const next = apply(current.layout);
119
+ refuseUnsafeImageSources(current.layout, next.layout);
120
+ refuseUnsafeLinks(current.layout, next.layout);
121
+ refuseUnsafeSvg(current.layout, next.layout);
112
122
  const layout = checkLayout(next.layout);
123
+ // W-562: a write that changes nothing (an empty set, the same value, a move to its own
124
+ // spot) saved a new version and rev anyway, cluttering the timeline and the agent log.
125
+ if (stableJson(layout) === stableJson(current.layout)) {
126
+ return { pageId, rev: page.rev, changed: [], summary: `Nothing changed (${tool})` };
127
+ }
113
128
  try {
114
129
  const saved = await ports.savePage(pageId, { layout }, page.rev);
115
130
  await ports.log({
@@ -133,6 +148,117 @@ const refused = (reason: string): never => {
133
148
  throw new McpToolError("REFUSED", reason);
134
149
  };
135
150
 
151
+ /**
152
+ * W-755: these checks run before the layout is validated, so a write that set `props` to null (or
153
+ * a list) reached them as is and failed as an internal error instead of an invalid layout.
154
+ */
155
+ const isRecord = (v: unknown): v is Record<string, unknown> =>
156
+ typeof v === "object" && v !== null && !Array.isArray(v);
157
+
158
+ const propsOf = (node: LayoutNode): Record<string, unknown> =>
159
+ isRecord(node.props) ? node.props : {};
160
+
161
+ /** Link props (the element's `href` fields) on each node, keyed by node and prop. */
162
+ function linkValues(root: LayoutNode): Map<string, string> {
163
+ const found = new Map<string, string>();
164
+ const walk = (node: LayoutNode) => {
165
+ const fields = ELEMENT_DESCRIPTORS.find((d) => d.type === node.type)?.fields ?? [];
166
+ const props = propsOf(node);
167
+ for (const field of fields) {
168
+ const value = props[field.key];
169
+ if (field.kind === "href" && typeof value === "string")
170
+ found.set(`${node.id}.${field.key}`, value);
171
+ }
172
+ for (const child of nodeChildren(node)) walk(child);
173
+ };
174
+ walk(root);
175
+ return found;
176
+ }
177
+
178
+ /**
179
+ * W-563: as W-499 for images, a `javascript:` (or other unsafe) link passed validation and the
180
+ * page published the element without it, with nothing telling the agent. Links the write adds
181
+ * or changes must pass the page's link check; ones already stored are left alone.
182
+ */
183
+ function refuseUnsafeLinks(before: Layout, after: Layout) {
184
+ const old = linkValues(before.root);
185
+ for (const [key, href] of linkValues(after.root)) {
186
+ if (href.trim() === "" || old.get(key) === href || sanitizeHref(href) !== undefined) continue;
187
+ const [id, prop] = key.split(".");
188
+ refused(
189
+ `Element ${id} has the ${prop} ${JSON.stringify(clipText(href, 80))}, which pages can't link to. Use an https:// URL, a path on this site such as /pricing, #section, mailto: or tel:.`,
190
+ );
191
+ }
192
+ }
193
+
194
+ /** SVG markup props (an SVG element's `markup`, an icon's `iconSvg`), keyed by node and prop. */
195
+ function svgValues(root: LayoutNode): Map<string, string> {
196
+ const found = new Map<string, string>();
197
+ const walk = (node: LayoutNode) => {
198
+ const props = propsOf(node);
199
+ if (node.type === "svg" && typeof props["markup"] === "string")
200
+ found.set(`${node.id}.markup`, props["markup"]);
201
+ if (typeof props["iconSvg"] === "string") found.set(`${node.id}.iconSvg`, props["iconSvg"]);
202
+ for (const child of nodeChildren(node)) walk(child);
203
+ };
204
+ walk(root);
205
+ return found;
206
+ }
207
+
208
+ /**
209
+ * W-566: SVG with an `onload` handler (or a script, foreignObject, style…) was stored as given and
210
+ * the page then rendered nothing for it, with nothing telling the agent. Markup the write adds or
211
+ * changes must pass the same check the renderer uses; ones already stored are left alone.
212
+ */
213
+ function refuseUnsafeSvg(before: Layout, after: Layout) {
214
+ const old = svgValues(before.root);
215
+ for (const [key, markup] of svgValues(after.root)) {
216
+ if (markup.trim() === "" || old.get(key) === markup || isSafeSvgMarkup(markup)) continue;
217
+ const [id, prop] = key.split(".");
218
+ refused(
219
+ `Element ${id} has ${prop} the page can't show. Use plain SVG: no scripts, event handlers such as onload, foreignObject, style blocks, links or external images.`,
220
+ );
221
+ }
222
+ }
223
+
224
+ /** Image sources (src and srcset widths) on a node, keyed for comparison. */
225
+ function imageSources(root: LayoutNode): Map<string, string[]> {
226
+ const found = new Map<string, string[]>();
227
+ const walk = (node: LayoutNode) => {
228
+ if (node.type === "image") {
229
+ const props = propsOf(node) as { src?: unknown; sources?: unknown };
230
+ const list = typeof props.src === "string" ? [props.src] : [];
231
+ if (Array.isArray(props.sources)) {
232
+ for (const source of props.sources as { src?: unknown }[]) {
233
+ if (typeof source?.src === "string") list.push(source.src);
234
+ }
235
+ }
236
+ found.set(node.id, list);
237
+ }
238
+ for (const child of nodeChildren(node)) walk(child);
239
+ };
240
+ walk(root);
241
+ return found;
242
+ }
243
+
244
+ /**
245
+ * W-499: a `javascript:` or `data:` image source passed validation and published as a blank
246
+ * placeholder (the renderer drops it), with nothing telling the agent why. Sources the write
247
+ * adds or changes must be http(s) or a same-site path; ones already stored are left alone.
248
+ */
249
+ function refuseUnsafeImageSources(before: Layout, after: Layout) {
250
+ const old = imageSources(before.root);
251
+ for (const [id, list] of imageSources(after.root)) {
252
+ const kept = new Set(old.get(id) ?? []);
253
+ for (const src of list) {
254
+ if (src.trim() === "" || kept.has(src) || sanitizeMediaUrl(src)) continue;
255
+ refused(
256
+ `Image ${id} has the source ${JSON.stringify(src.slice(0, 80))}, which pages can't show. Use an https:// URL or a path on this site such as /_emdash/api/media/file/photo.jpg (upload in the EmDash media library first).`,
257
+ );
258
+ }
259
+ }
260
+ }
261
+
136
262
  const KNOWN_TYPES = new Set(ELEMENT_DESCRIPTORS.map((d) => d.type));
137
263
 
138
264
  /** An element from the agent: its type's defaults, the given props and fields, fresh ids. */
@@ -145,6 +271,23 @@ const ElementSpec: z.ZodType<ElementSpecT> = z.lazy(() =>
145
271
  );
146
272
  type ElementSpecT = { type: string; props?: Record<string, unknown>; children?: ElementSpecT[] };
147
273
 
274
+ /**
275
+ * W-652: the recursive spec is checked by recursion, so an element nested a few thousand levels
276
+ * overflowed the stack while the input was validated and the call failed as an internal error.
277
+ * Pages allow 24 levels of elements; anything past a generous bound is refused up front.
278
+ */
279
+ const BoundedElementSpec = z.preprocess((value, ctx) => {
280
+ if (nestsDeeperThan(value, MAX_DEPTH * 8)) {
281
+ ctx.addIssue({
282
+ code: "custom",
283
+ message: `Elements can be nested at most ${MAX_DEPTH} levels deep.`,
284
+ input: value,
285
+ });
286
+ return z.NEVER;
287
+ }
288
+ return value;
289
+ }, ElementSpec);
290
+
148
291
  function buildNode(spec: ElementSpecT): LayoutNode {
149
292
  if (!KNOWN_TYPES.has(spec.type)) {
150
293
  refused(`Unknown element type ${spec.type}. Call list_element_types.`);
@@ -197,9 +340,22 @@ function promoteHeroHeading(layout: Layout, title: string): Layout {
197
340
  );
198
341
  }
199
342
 
343
+ /** Whether any page already has this slug, paging past the first 50 (W-537, at most 1000). */
344
+ async function slugTaken(ports: EmvbPorts, slug: string): Promise<boolean> {
345
+ let cursor: string | undefined;
346
+ for (let i = 0; i < 20; i++) {
347
+ // oxlint-disable-next-line no-await-in-loop -- cursor paging is sequential
348
+ const batch = await ports.listPages({ limit: 50, ...(cursor ? { cursor } : {}) });
349
+ if (batch.pages.some((page) => page.slug === slug)) return true;
350
+ if (!batch.nextCursor) return false;
351
+ cursor = batch.nextCursor;
352
+ }
353
+ return false;
354
+ }
355
+
200
356
  export async function createPage(ports: EmvbPorts, input: z.infer<typeof CreatePageInput>) {
201
357
  // EmDash derives the slug from the title; refuse a title whose slug is already taken.
202
- const slug = slugify(input.title);
358
+ const slug = pageSlug(input.title);
203
359
  if (!slug) refused("Give the page a title with letters or digits.");
204
360
  const { design } = await ports.getDesign();
205
361
  let layout = starterLayout(input.title);
@@ -225,8 +381,7 @@ export async function createPage(ports: EmvbPorts, input: z.infer<typeof CreateP
225
381
  }
226
382
  if (recipes[0] === "hero") layout = promoteHeroHeading(layout, input.title);
227
383
  const checked = checkLayout(layout);
228
- const taken = await ports.listPages({ limit: 50 });
229
- if (taken.pages.some((page) => page.slug === slug)) {
384
+ if (await slugTaken(ports, slug)) {
230
385
  throw new McpToolError("REFUSED", `The slug "${slug}" is taken. Choose another title.`);
231
386
  }
232
387
  const created = await ports.createPage({ title: input.title, layout: checked });
@@ -246,7 +401,7 @@ export const AddElementInput = z.strictObject({
246
401
  pageId: PageId,
247
402
  parentId: NodeIdInput,
248
403
  index: z.number().int().min(0).optional(),
249
- element: ElementSpec,
404
+ element: BoundedElementSpec,
250
405
  expectedRev: Rev.optional(),
251
406
  });
252
407
 
@@ -320,8 +475,28 @@ export const UpdateElementInput = z.strictObject({
320
475
  expectedRev: Rev.optional(),
321
476
  });
322
477
 
323
- const isRecord = (v: unknown): v is Record<string, unknown> =>
324
- typeof v === "object" && v !== null && !Array.isArray(v);
478
+ /**
479
+ * W-510: a new `src` merged into an image's props kept the old picture's extra sizes (the
480
+ * browser went on showing the old picture from srcset), its image-editor record and its media
481
+ * id and size. As the editor's picker does (W-422, W-425, W-482), they go unless the same
482
+ * write sets them.
483
+ */
484
+ function dropOldPictureProps(
485
+ before: Record<string, unknown>,
486
+ setProps: Record<string, unknown>,
487
+ copy: Record<string, unknown>,
488
+ ) {
489
+ if (typeof setProps.src !== "string" || setProps.src === before.src) return;
490
+ const props = copy.props;
491
+ if (!isRecord(props)) return;
492
+ for (const key of ["sources", "edit", "mediaId"]) {
493
+ if (!(key in setProps)) delete props[key];
494
+ }
495
+ if (before.mediaId !== undefined && !("mediaId" in setProps)) {
496
+ if (!("width" in setProps)) delete props.width;
497
+ if (!("height" in setProps)) delete props.height;
498
+ }
499
+ }
325
500
 
326
501
  export async function updateElement(ports: EmvbPorts, input: z.infer<typeof UpdateElementInput>) {
327
502
  const set = resolveDesignRefs(input.set ?? {}, (await ports.getDesign()).design);
@@ -335,6 +510,9 @@ export async function updateElement(ports: EmvbPorts, input: z.infer<typeof Upda
335
510
  // Objects merge one level deep, like the editor's panels; anything else replaces.
336
511
  copy[key] = isRecord(value) && isRecord(copy[key]) ? { ...copy[key], ...value } : value;
337
512
  }
513
+ if (node.type === "image" && isRecord(set.props)) {
514
+ dropOldPictureProps(node.props as Record<string, unknown>, set.props, copy);
515
+ }
338
516
  for (const path of input.unset ?? []) {
339
517
  const [top, sub] = path.split(".") as [string, string | undefined];
340
518
  if (top === "id" || top === "type" || top === "children") continue;
@@ -447,7 +625,7 @@ export const UpdateSiteStylesInput = z.strictObject({
447
625
  removeClasses: z.array(z.string().min(1).max(64)).max(100).optional(),
448
626
  defaults: z.record(z.string(), z.unknown()).optional(),
449
627
  direction: z.enum(["ltr", "rtl", "auto"]).optional(),
450
- /** Remove variables even when pages or classes still use them (their references fall back). */
628
+ /** Remove variables or classes even when pages or classes still use them (references fall back). */
451
629
  force: z.boolean().optional(),
452
630
  expectedRevision: z.string().max(256).nullable().optional(),
453
631
  });
@@ -460,14 +638,8 @@ const KIND_OF: Record<(typeof VARIABLE_KINDS)[number], VariableKind> = {
460
638
  spacings: "spacing",
461
639
  };
462
640
 
463
- /** Where a variable is still used: class ids and page titles (W-458 in-use guard). */
464
- async function variableUses(
465
- ports: EmvbPorts,
466
- design: DesignSystem,
467
- id: string,
468
- kind: VariableKind,
469
- ): Promise<string[]> {
470
- const where = findVariableUsagesInDesign(design, id, kind).map((u) => `class ${u.classId}`);
641
+ /** Every EmVB page's title and layout, for the in-use guards (at most 1000 pages). */
642
+ async function allLayouts(ports: EmvbPorts): Promise<{ title: string; layout: Layout }[]> {
471
643
  const pages: { id: string; title: string }[] = [];
472
644
  let cursor: string | undefined;
473
645
  for (let i = 0; i < 20; i++) {
@@ -478,15 +650,35 @@ async function variableUses(
478
650
  cursor = batch.nextCursor;
479
651
  }
480
652
  const records = await Promise.all(pages.map((page) => ports.getPage(page.id)));
653
+ const out: { title: string; layout: Layout }[] = [];
481
654
  records.forEach((record, i) => {
482
655
  const layout = record ? validateLayout(record.layout) : null;
483
- if (layout?.ok && findVariableUsages(layout.layout, id, kind).length > 0) {
484
- where.push(`page "${pages[i]?.title ?? ""}"`);
485
- }
656
+ if (layout?.ok) out.push({ title: pages[i]?.title ?? "", layout: layout.layout });
486
657
  });
658
+ return out;
659
+ }
660
+
661
+ /** Where a variable is still used: class ids and page titles (W-458 in-use guard). */
662
+ function variableUses(
663
+ layouts: { title: string; layout: Layout }[],
664
+ design: DesignSystem,
665
+ id: string,
666
+ kind: VariableKind,
667
+ ): string[] {
668
+ const where = findVariableUsagesInDesign(design, id, kind).map((u) => `class ${u.classId}`);
669
+ for (const { title, layout } of layouts) {
670
+ if (findVariableUsages(layout, id, kind).length > 0) where.push(`page "${title}"`);
671
+ }
487
672
  return where;
488
673
  }
489
674
 
675
+ /** W-504: pages whose elements still carry a class (removing it silently unstyled them). */
676
+ function classUses(layouts: { title: string; layout: Layout }[], id: string): string[] {
677
+ const uses = (node: LayoutNode): boolean =>
678
+ (node.classes ?? []).includes(id) || nodeChildren(node).some(uses);
679
+ return layouts.filter(({ layout }) => uses(layout.root)).map(({ title }) => `page "${title}"`);
680
+ }
681
+
490
682
  const upsert = (list: Item[] | undefined, items: Item[]): Item[] => {
491
683
  const next = [...(list ?? [])];
492
684
  for (const item of items) {
@@ -516,6 +708,15 @@ export async function updateSiteStyles(
516
708
  defaults?: Record<string, unknown>;
517
709
  };
518
710
  const changes: string[] = [];
711
+ // W-547: a font stack the site CSS can't carry was saved, then dropped from the page.
712
+ for (const font of (input.variables?.fonts ?? []) as { id?: unknown; value?: unknown }[]) {
713
+ if (typeof font.value === "string" && !isSafeFontStack(font.value)) {
714
+ throw new McpToolError(
715
+ "INVALID_INPUT",
716
+ `Font ${String(font.id)}: "${font.value.slice(0, 60)}" can't be used in the site CSS. Use names of letters, digits, spaces, - and _, quoted or not, separated by commas.`,
717
+ );
718
+ }
719
+ }
519
720
  for (const kind of VARIABLE_KINDS) {
520
721
  const items = input.variables?.[kind] as Item[] | undefined;
521
722
  if (items?.length) {
@@ -523,13 +724,30 @@ export async function updateSiteStyles(
523
724
  changes.push(`${items.length} ${kind}`);
524
725
  }
525
726
  }
526
- if (!input.force) {
527
- const inUse = await Promise.all(
528
- (input.removeVariables ?? []).map(async ({ kind, id }) => ({
727
+ // W-564: removing an id the styles don't have "succeeded" with a removed summary.
728
+ const unknown = [
729
+ ...(input.removeVariables ?? [])
730
+ .filter(({ kind, id }) => !(draft.variables[kind] ?? []).some((v) => v.id === id))
731
+ .map(({ kind, id }) => `${kind} ${id}`),
732
+ ...(input.removeClasses ?? [])
733
+ .filter((id) => !(draft.classes ?? []).some((c) => c.id === id))
734
+ .map((id) => `class ${id}`),
735
+ ];
736
+ if (unknown.length > 0) {
737
+ throw new McpToolError(
738
+ "NOT_FOUND",
739
+ `Nothing to remove for ${unknown.join(", ")}. Call get_site_styles for the ids.`,
740
+ );
741
+ }
742
+ if (!input.force && (input.removeVariables?.length || input.removeClasses?.length)) {
743
+ const layouts = await allLayouts(ports);
744
+ const inUse = [
745
+ ...(input.removeVariables ?? []).map(({ kind, id }) => ({
529
746
  id,
530
- where: await variableUses(ports, state.design, id, KIND_OF[kind]),
747
+ where: variableUses(layouts, state.design, id, KIND_OF[kind]),
531
748
  })),
532
- );
749
+ ...(input.removeClasses ?? []).map((id) => ({ id, where: classUses(layouts, id) })),
750
+ ];
533
751
  const blocked = inUse.filter((u) => u.where.length > 0);
534
752
  if (blocked.length > 0) {
535
753
  throw new McpToolError(
@@ -566,6 +784,30 @@ export async function updateSiteStyles(
566
784
  draft["direction"] = input.direction;
567
785
  changes.push(`direction ${input.direction}`);
568
786
  }
787
+ // W-573: the editor keeps class names, and variable names within a kind, unique (W-277,
788
+ // W-278); an agent's new or renamed one can't take another's name either.
789
+ const clash = (list: Item[] | undefined, touched: unknown[] | undefined, what: string) => {
790
+ const ids = new Set((touched ?? []).map((item) => (item as { id?: unknown }).id));
791
+ const seen = new Map<string, Item>();
792
+ for (const item of list ?? []) {
793
+ const name = (item as { name?: unknown }).name;
794
+ if (typeof name !== "string") continue;
795
+ const key = nameKey(name);
796
+ const other = seen.get(key);
797
+ if (other && (ids.has(item.id) || ids.has(other.id))) {
798
+ const taken = String((other as { name?: unknown }).name);
799
+ throw new McpToolError(
800
+ "INVALID_INPUT",
801
+ `${what} ${item.id} and ${other.id} would both be named "${taken}". Pick another name.`,
802
+ );
803
+ }
804
+ if (!other) seen.set(key, item);
805
+ }
806
+ };
807
+ clash(draft.classes, input.classes, "Classes");
808
+ for (const kind of VARIABLE_KINDS) {
809
+ clash(draft.variables[kind], input.variables?.[kind], `Variables (${kind})`);
810
+ }
569
811
  if (changes.length === 0) refused("Nothing to change.");
570
812
  const result = validateDesign(draft);
571
813
  if (!result.ok) {
@@ -574,6 +816,10 @@ export async function updateSiteStyles(
574
816
  `The site styles would be invalid. ${summarizeIssues(result.issues)}`,
575
817
  );
576
818
  }
819
+ // W-564: the same values again save no new draft revision.
820
+ if (stableJson(result.design) === stableJson(state.design) && state.revision) {
821
+ return { revision: state.revision, summary: "Nothing changed in the site styles draft" };
822
+ }
577
823
  const saved = await ports.saveDesign(result.design as DesignSystem, state.revision);
578
824
  const summary = `Site styles draft: ${changes.join(", ")}`;
579
825
  await ports.log({ target: "styles", tool: "update_site_styles", summary });
@@ -34,7 +34,34 @@ type LogQuery = {
34
34
  items: { id: string; data: unknown }[];
35
35
  }>;
36
36
  put(id: string, data: unknown): Promise<void>;
37
+ deleteMany?(ids: string[]): Promise<number>;
37
38
  };
39
+
40
+ /** Agent activity is kept this many days (W-522). */
41
+ const AGENT_LOG_DAYS = 90;
42
+
43
+ /**
44
+ * Adds one agent activity entry and drops up to 100 entries older than AGENT_LOG_DAYS. The log
45
+ * had no limit, so a busy agent token (60 changes a minute) grew it without end (W-522).
46
+ */
47
+ export async function appendAgentLog(
48
+ store: LogQuery,
49
+ entry: Record<string, unknown>,
50
+ now: Date = new Date(),
51
+ ): Promise<void> {
52
+ const at = now.toISOString();
53
+ await store.put(`${at}-${crypto.randomUUID().slice(0, 8)}`, { ...entry, at });
54
+ if (!store.deleteMany) return;
55
+ const cutoff = new Date(now.getTime() - AGENT_LOG_DAYS * 86_400_000).toISOString();
56
+ const old = await store.query({
57
+ where: { at: { lt: cutoff } },
58
+ orderBy: { at: "asc" },
59
+ limit: 100,
60
+ });
61
+ const ids = old.items.map((item) => item.id);
62
+ if (ids.length > 0) await store.deleteMany(ids);
63
+ }
64
+
38
65
  const agentLog = (ctx: PluginContext) => ctx.storage["agentlog"] as unknown as LogQuery;
39
66
 
40
67
  /** Agents tab: the settings, the MCP endpoint and the last 50 agent changes. Admins only. */
@@ -95,12 +122,10 @@ export const agentsSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
95
122
  ctx.input.settings,
96
123
  );
97
124
  if (!write.applied) {
98
- throw PluginRouteError.conflict("The agent settings changed somewhere else. Reload them.");
125
+ throw PluginRouteError.conflict("The agent settings changed somewhere else.");
99
126
  }
100
- const at = new Date().toISOString();
101
127
  const s = ctx.input.settings;
102
- await agentLog(ctx).put(`${at}-${crypto.randomUUID().slice(0, 8)}`, {
103
- at,
128
+ await appendAgentLog(agentLog(ctx), {
104
129
  target: "settings",
105
130
  tool: "settings",
106
131
  userId: ctx.user?.id ?? null,
@@ -25,7 +25,7 @@ type FieldValidation =
25
25
  | { ok: false; issues: { code: string; message: string }[] };
26
26
 
27
27
  /** Theme-part fields validated on save, besides the layout (R-061). */
28
- const THEME_PART_FIELDS: [string, (raw: unknown) => FieldValidation][] = [
28
+ const THEME_PART_FIELDS: [string, (raw: unknown) => FieldValidation, string?][] = [
29
29
  [
30
30
  "conditions",
31
31
  (raw) => {
@@ -46,6 +46,8 @@ const THEME_PART_FIELDS: [string, (raw: unknown) => FieldValidation][] = [
46
46
  const result = validateFloatSettings(raw);
47
47
  return result.ok ? { ok: true, value: result.settings } : result;
48
48
  },
49
+ // W-678: the message read "The theme part float are invalid."
50
+ "float settings",
49
51
  ],
50
52
  ];
51
53
 
@@ -95,7 +97,7 @@ export async function beforeSave(
95
97
  }
96
98
 
97
99
  if (event.collection === THEME_PARTS_COLLECTION) {
98
- for (const [field, validate] of THEME_PART_FIELDS) {
100
+ for (const [field, validate, label = field] of THEME_PART_FIELDS) {
99
101
  if (event.content[field] === undefined) continue;
100
102
  const result = validate(parseJsonField(event.content[field]));
101
103
  if (!result.ok) {
@@ -104,7 +106,7 @@ export async function beforeSave(
104
106
  code: result.issues[0]?.code ?? `invalid_${field}`,
105
107
  });
106
108
  throw new ContentSaveRejectedError(
107
- `The theme part ${field} are invalid. ${result.issues
109
+ `The theme part ${label} are invalid. ${result.issues
108
110
  .slice(0, 3)
109
111
  .map((i) => i.message)
110
112
  .join("; ")}`,
@@ -1,3 +1,4 @@
1
+ import { clipText } from "../core/limits.ts";
1
2
  import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
3
  import { z } from "zod";
3
4
  import {
@@ -28,16 +29,31 @@ type IconStore = {
28
29
 
29
30
  const store = (ctx: RouteContext<unknown>) => ctx.storage["icons"] as unknown as IconStore;
30
31
 
31
- /** The most recent uploads the picker lists. */
32
- const UPLOAD_LIST_LIMIT = 100;
32
+ /**
33
+ * The uploads the picker lists, and the most My uploads holds (W-535): past it the oldest
34
+ * uploads dropped off the list and could no longer be seen or deleted.
35
+ */
36
+ export const UPLOAD_LIST_LIMIT = 100;
37
+
38
+ /** An icon's label as typed: trimmed and capped (W-655: a rename may hold a slash, as in "AC/DC"). */
39
+ // W-656: control characters become spaces and invisible or direction-changing marks go, so a
40
+ // name like "evil\u202Egvs.exe" can't show reversed in the picker.
41
+ const iconLabel = (name: string) =>
42
+ clipText(
43
+ Array.from(name.normalize("NFC"), (ch) => {
44
+ const code = ch.charCodeAt(0);
45
+ return code < 32 || (code >= 127 && code <= 159) ? " " : ch;
46
+ })
47
+ .join("")
48
+ .replace(/[\u200B\u2060\uFEFF\u200E\u200F\u202A-\u202E\u2066-\u2069]/g, "")
49
+ .replace(/ {2,}/g, " ")
50
+ .trim(),
51
+ 80,
52
+ ).trim() || "Uploaded icon";
33
53
 
34
54
  /** A file name without its folder or extension, as the icon's label. */
35
55
  export const uploadName = (name: string) =>
36
- name
37
- .replace(/^.*[\\/]/, "")
38
- .replace(/\.svg$/i, "")
39
- .trim()
40
- .slice(0, 80) || "Uploaded icon";
56
+ iconLabel(name.replace(/^.*[\\/]/, "").replace(/\.svg$/i, ""));
41
57
 
42
58
  /**
43
59
  * One stored upload safe to send to the editor. Markup that no longer passes the SVG allowlist
@@ -49,7 +65,7 @@ export function publicUploadedIcon(id: string, data: UploadedIcon): UploadedIcon
49
65
  if (!tree) return undefined;
50
66
  return {
51
67
  id,
52
- name: uploadName(typeof data.name === "string" ? data.name : ""),
68
+ name: iconLabel(typeof data.name === "string" ? data.name : ""),
53
69
  svg: serialize(tree),
54
70
  uploadedAt: typeof data.uploadedAt === "string" ? data.uploadedAt : "",
55
71
  };
@@ -84,6 +100,14 @@ export const iconUploadRoute: PluginRoute<z.infer<typeof UploadInput>> = {
84
100
  handler: async (ctx) => {
85
101
  const prepared = prepareUploadedSvg(ctx.input.svg);
86
102
  if (!prepared.ok) throw new PluginRouteError("INVALID_SVG", prepared.message, 422);
103
+ const held = await store(ctx).query({ limit: UPLOAD_LIST_LIMIT });
104
+ if (held.items.length >= UPLOAD_LIST_LIMIT) {
105
+ throw new PluginRouteError(
106
+ "UPLOADS_FULL",
107
+ `My uploads holds up to ${UPLOAD_LIST_LIMIT} icons. Delete one you no longer use, then upload again.`,
108
+ 409,
109
+ );
110
+ }
87
111
  const id = crypto.randomUUID().replaceAll("-", "").slice(0, 16);
88
112
  const item: UploadedIcon = {
89
113
  name: uploadName(ctx.input.name),
@@ -110,7 +134,7 @@ export const iconRenameRoute: PluginRoute<z.infer<typeof RenameInput>> = {
110
134
  handler: async (ctx) => {
111
135
  const current = await store(ctx).get(ctx.input.id);
112
136
  if (!current) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
113
- const name = uploadName(ctx.input.name);
137
+ const name = iconLabel(ctx.input.name.trim().replace(/\.svg$/i, ""));
114
138
  // W-390: answer with the same checked markup the list sends; a row that fails the
115
139
  // allowlist is not renamed or echoed back.
116
140
  const item = publicUploadedIcon(ctx.input.id, { ...current, name });