@perkyzz/emvb 0.4.0 → 0.6.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 (127) hide show
  1. package/README.md +23 -3
  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 +5 -3
  9. package/src/admin/agents-api.ts +39 -0
  10. package/src/admin/editor/CommandPalette.tsx +43 -2
  11. package/src/admin/editor/Editor.tsx +33 -0
  12. package/src/admin/editor/Timeline.tsx +108 -6
  13. package/src/admin/editor/collection-previews.ts +6 -1
  14. package/src/admin/editor/editor-chrome.tsx +49 -0
  15. package/src/admin/editor/editor-commands.ts +13 -0
  16. package/src/admin/editor/editor-css.ts +7 -0
  17. package/src/admin/editor/feature-css.ts +22 -3
  18. package/src/admin/editor/palette.ts +6 -2
  19. package/src/admin/editor/panels/ColorControl.tsx +24 -12
  20. package/src/admin/editor/panels/ElementPanel.tsx +1 -1
  21. package/src/admin/editor/panels/LayersPanel.tsx +13 -3
  22. package/src/admin/editor/panels/TokenScales.tsx +4 -2
  23. package/src/admin/editor/panels/VariableSection.tsx +5 -3
  24. package/src/admin/editor/panels/color-space.ts +12 -1
  25. package/src/admin/editor/panels/settings/AdvancedFields.tsx +84 -28
  26. package/src/admin/editor/panels/settings/AudienceEditor.tsx +42 -4
  27. package/src/admin/editor/panels/settings/DraftTextField.tsx +38 -9
  28. package/src/admin/editor/panels/settings/FieldControl.tsx +24 -7
  29. package/src/admin/editor/panels/settings/IconPicker.tsx +21 -1
  30. package/src/admin/editor/panels/settings/ImageSourcesField.tsx +111 -0
  31. package/src/admin/editor/panels/settings/MediaPicker.tsx +156 -7
  32. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +178 -0
  33. package/src/admin/editor/panels/settings/RequiredFieldsNotice.tsx +76 -0
  34. package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
  35. package/src/admin/editor/panels/settings/link-rules.ts +19 -0
  36. package/src/admin/editor/panels/settings/number-input.ts +11 -0
  37. package/src/admin/editor/panels/settings/query-style.ts +65 -0
  38. package/src/admin/editor/panels/variable-values.ts +18 -2
  39. package/src/admin/editor/remote-change.ts +67 -0
  40. package/src/admin/editor/store.ts +7 -3
  41. package/src/admin/image-editor/BlurFocus.tsx +112 -0
  42. package/src/admin/image-editor/Canvas.tsx +261 -0
  43. package/src/admin/image-editor/CropOverlay.tsx +390 -0
  44. package/src/admin/image-editor/CurvesPanel.tsx +394 -0
  45. package/src/admin/image-editor/ExportDialog.tsx +354 -0
  46. package/src/admin/image-editor/ImageEditButton.tsx +83 -0
  47. package/src/admin/image-editor/ImageEditorDialog.tsx +786 -0
  48. package/src/admin/image-editor/MetadataPanel.tsx +183 -0
  49. package/src/admin/image-editor/announce.tsx +65 -0
  50. package/src/admin/image-editor/crop-geometry.ts +161 -0
  51. package/src/admin/image-editor/curve-math.ts +177 -0
  52. package/src/admin/image-editor/data-url-fetch.ts +59 -0
  53. package/src/admin/image-editor/engine.ts +55 -0
  54. package/src/admin/image-editor/exif.ts +82 -0
  55. package/src/admin/image-editor/flatten.ts +54 -0
  56. package/src/admin/image-editor/gpu-fit.ts +81 -0
  57. package/src/admin/image-editor/image-editor-css.ts +398 -0
  58. package/src/admin/image-editor/load.ts +109 -0
  59. package/src/admin/image-editor/panels.tsx +287 -0
  60. package/src/admin/image-editor/parts.tsx +565 -0
  61. package/src/admin/image-editor/save.ts +125 -0
  62. package/src/admin/image-editor/tone-panels.tsx +338 -0
  63. package/src/admin/image-editor/tools.ts +59 -0
  64. package/src/admin/image-editor/worker.ts +111 -0
  65. package/src/admin/index.tsx +3 -1
  66. package/src/admin/media-api.ts +132 -2
  67. package/src/admin/pages/AgentsPage.tsx +274 -0
  68. package/src/admin/ui.ts +33 -0
  69. package/src/astro/EmVBPage.astro +11 -2
  70. package/src/astro/floats/runtime.ts +10 -0
  71. package/src/astro/popups/runtime.ts +15 -0
  72. package/src/astro/render.ts +3 -0
  73. package/src/astro/resolve-theme.ts +15 -4
  74. package/src/astro/tabs/runtime.ts +60 -1
  75. package/src/astro/visitor.ts +4 -3
  76. package/src/constants.ts +1 -1
  77. package/src/core/a11y/audit.ts +202 -26
  78. package/src/core/arrange.ts +13 -3
  79. package/src/core/css/generate.ts +9 -1
  80. package/src/core/data/bindings.ts +12 -6
  81. package/src/core/design/classes.ts +5 -3
  82. package/src/core/design/diff.ts +3 -1
  83. package/src/core/design/merge.ts +3 -1
  84. package/src/core/design/transfer.ts +13 -2
  85. package/src/core/design/variables.ts +2 -1
  86. package/src/core/elements/dynamic-elements.ts +9 -1
  87. package/src/core/elements/form-elements.ts +18 -3
  88. package/src/core/elements/index.ts +39 -11
  89. package/src/core/elements/plain-text.ts +2 -2
  90. package/src/core/forms/binding.ts +148 -1
  91. package/src/core/history/diff.ts +32 -4
  92. package/src/core/image-edit/schema.ts +145 -0
  93. package/src/core/image-edit/summary.ts +58 -0
  94. package/src/core/index.ts +14 -0
  95. package/src/core/limits.ts +10 -0
  96. package/src/core/migrate/index.ts +3 -1
  97. package/src/core/perf/meter.ts +9 -1
  98. package/src/core/render/dynamic-post.ts +23 -6
  99. package/src/core/render/form.ts +36 -11
  100. package/src/core/render/index.ts +75 -15
  101. package/src/core/render/pagination.ts +21 -2
  102. package/src/core/sanitize/embed-url.ts +7 -1
  103. package/src/core/sanitize/href.ts +13 -1
  104. package/src/core/schema/descriptors.ts +4 -1
  105. package/src/core/schema/layout.ts +21 -4
  106. package/src/core/share/link.ts +9 -3
  107. package/src/core/stable-json.ts +15 -0
  108. package/src/core/theme/dynamic.ts +32 -24
  109. package/src/core/theme/pagination.ts +30 -3
  110. package/src/core/theme/popup-rules.ts +10 -5
  111. package/src/mcp/errors.ts +44 -0
  112. package/src/mcp/index.ts +4 -0
  113. package/src/mcp/ports.ts +85 -0
  114. package/src/mcp/prompts.ts +76 -0
  115. package/src/mcp/publish.ts +60 -0
  116. package/src/mcp/queue.ts +19 -0
  117. package/src/mcp/rate-limit.ts +80 -0
  118. package/src/mcp/read.ts +486 -0
  119. package/src/mcp/refs.ts +84 -0
  120. package/src/mcp/settings.ts +18 -0
  121. package/src/mcp/tools.ts +265 -0
  122. package/src/mcp/write.ts +664 -0
  123. package/src/server/agent-settings.ts +159 -0
  124. package/src/server/design-routes.ts +71 -17
  125. package/src/server/icon-routes.ts +13 -6
  126. package/src/server/mcp-routes.ts +323 -0
  127. package/src/server/plugin.ts +32 -2
@@ -88,12 +88,23 @@ export function loopPerPage(layout: Layout): number {
88
88
  return found ?? DEFAULT_PER_PAGE;
89
89
  }
90
90
 
91
+ /** The paged archive title wording when the host passes none (W-229). */
92
+ const PAGED_TITLE = "{title} – page {page}";
93
+
91
94
  /**
92
95
  * A paged archive's title for `<title>` and headings: "Posts – page 2"; page 1 is the bare
93
- * title (W-229).
96
+ * title (W-229). W-529: `template` sets the wording in the site's language, with `{title}` and
97
+ * `{page}` filled in like the Pagination element's "Page {page} of {total}"; one without
98
+ * `{page}` would give every page the same title, so it falls back to the default.
94
99
  */
95
- export function archivePageTitle(title: string, page: number | undefined): string {
96
- return page !== undefined && page > 1 ? `${title} – page ${page}` : title;
100
+ export function archivePageTitle(
101
+ title: string,
102
+ page: number | undefined,
103
+ template?: string,
104
+ ): string {
105
+ if (page === undefined || page <= 1) return title;
106
+ const wording = template?.trim().includes("{page}") ? template.trim() : PAGED_TITLE;
107
+ return wording.replaceAll("{title}", title).replaceAll("{page}", String(page));
97
108
  }
98
109
 
99
110
  /** One entry of a Pagination bar: a page link, the current page, or a gap (W-222). */
@@ -151,3 +162,19 @@ function totalItems(p: ArchivePagination, total: number): PaginationItem[] {
151
162
  if (p.page < total) items.push({ kind: "next", href: archivePagePath(p.basePath, p.page + 1) });
152
163
  return items;
153
164
  }
165
+
166
+ /** The first Pagination element's "Page title text" in an archive layout, if set (W-529). */
167
+ export function paginationTitleText(layout: Layout): string | undefined {
168
+ let found: string | undefined;
169
+ const walk = (node: LayoutNode): void => {
170
+ if (found !== undefined) return;
171
+ if (node.type === "pagination") {
172
+ const text = (node.props as { titleText?: unknown }).titleText;
173
+ found = typeof text === "string" && text.trim() ? text.trim() : "";
174
+ return;
175
+ }
176
+ if (isParentNode(node)) for (const child of node.children) walk(child);
177
+ };
178
+ walk(layout.root);
179
+ return found || undefined;
180
+ }
@@ -18,13 +18,18 @@ export type PopupDevice = (typeof POPUP_DEVICES)[number];
18
18
  */
19
19
  export const DEVICE_PREVIEW_PX = { desktop: 1280, tablet: 768, mobile: 390 } as const;
20
20
 
21
- /** Public CSS queries. Bounds match `deviceForWidth`: 767 mobile, 1024 tablet, 1025 desktop. */
21
+ /**
22
+ * Public CSS queries. Bounds match `deviceForWidth`: below 768 mobile, below 1025 tablet.
23
+ * W-506: zoom and display scaling give fractional viewport widths; with whole-pixel bounds a
24
+ * width such as 1024.5 matched neither the tablet nor the desktop "hide" query, so an element
25
+ * hidden on both showed. The max bounds sit just under the next device's min (as Bootstrap does).
26
+ */
22
27
  export const DEVICE_MEDIA = {
23
- tablet: "(max-width: 1024px)",
24
- mobile: "(max-width: 767px)",
28
+ tablet: "(max-width: 1024.98px)",
29
+ mobile: "(max-width: 767.98px)",
25
30
  hideDesktop: "(min-width: 1025px)",
26
- hideTablet: "(min-width: 768px) and (max-width: 1024px)",
27
- hideMobile: "(max-width: 767px)",
31
+ hideTablet: "(min-width: 768px) and (max-width: 1024.98px)",
32
+ hideMobile: "(max-width: 767.98px)",
28
33
  } as const;
29
34
 
30
35
  /** A scroll percent as a number from 0 to 100; anything unreadable is 0. */
@@ -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,85 @@
1
+ import type { AgentSettings } from "./settings.ts";
2
+ import type { RateClass } from "./rate-limit.ts";
3
+ import type { DesignSystem, Layout, RequiredFieldInfo } 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
+ /**
79
+ * W-511: each form's fields as the forms plugin defines them, for describe_page's required-field
80
+ * warnings. Forms it can't read are left out; without this port there are no such warnings.
81
+ */
82
+ formFields?(
83
+ formIds: readonly string[],
84
+ ): Promise<ReadonlyMap<string, readonly RequiredFieldInfo[]>>;
85
+ }
@@ -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
+ ];
@@ -0,0 +1,60 @@
1
+ import { z } from "zod";
2
+ import { McpToolError } from "./errors.ts";
3
+ import type { EmvbPorts } from "./ports.ts";
4
+ import { queued } from "./queue.ts";
5
+
6
+ const off = (what: string) =>
7
+ new McpToolError(
8
+ "PUBLISH_DISABLED",
9
+ `Agents may not publish ${what} on this site. Leave the draft for a person to review, or ask an admin to allow it in Pages VisualBuilder → AI agents.`,
10
+ );
11
+
12
+ export const PublishPageInput = z.strictObject({
13
+ pageId: z.string().min(1).max(128),
14
+ /** Required: an agent can't publish a draft it hasn't read (plan § 3). */
15
+ expectedRev: z.string().min(1).max(256),
16
+ confirm: z.literal(true),
17
+ });
18
+ export const PublishPageOutput = z.object({
19
+ pageId: z.string(),
20
+ rev: z.string(),
21
+ summary: z.string(),
22
+ });
23
+
24
+ /** D-055: publishes one page only when the admin allowed agent publishing. */
25
+ export async function publishPage(ports: EmvbPorts, input: z.infer<typeof PublishPageInput>) {
26
+ if (!(await ports.settings()).publishPages) throw off("pages");
27
+ return queued(`page:${input.pageId}`, async () => {
28
+ const published = await ports.publishPage(input.pageId, input.expectedRev);
29
+ const summary = `Published page ${input.pageId}`;
30
+ await ports.log({
31
+ target: "page",
32
+ tool: "publish_page",
33
+ pageId: input.pageId,
34
+ rev: published.rev,
35
+ summary,
36
+ });
37
+ return { pageId: input.pageId, rev: published.rev, summary };
38
+ });
39
+ }
40
+
41
+ export const PublishSiteStylesInput = z.strictObject({
42
+ /** The `publishedRevision` from get_site_styles (null when nothing was ever published). */
43
+ expectedPublishedRevision: z.string().max(256).nullable(),
44
+ confirm: z.literal(true),
45
+ });
46
+ export const PublishSiteStylesOutput = z.object({ revision: z.string(), summary: z.string() });
47
+
48
+ /** D-055: publishes the style draft only when the admin allowed it. Pages are not republished. */
49
+ export async function publishSiteStyles(
50
+ ports: EmvbPorts,
51
+ input: z.infer<typeof PublishSiteStylesInput>,
52
+ ) {
53
+ if (!(await ports.settings()).publishStyles) throw off("site styles");
54
+ return queued("styles", async () => {
55
+ const published = await ports.publishDesign(input.expectedPublishedRevision);
56
+ const summary = "Published the site styles";
57
+ await ports.log({ target: "styles", tool: "publish_site_styles", summary });
58
+ return { revision: published.revision, summary };
59
+ });
60
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * One write at a time per key in this isolate (D-058), like the editor's save queue: a write
3
+ * reads the latest `_rev` only after the previous write to the same page has finished.
4
+ */
5
+ const tails = new Map<string, Promise<unknown>>();
6
+
7
+ export function queued<T>(key: string, work: () => Promise<T>): Promise<T> {
8
+ const previous = tails.get(key) ?? Promise.resolve();
9
+ const next = previous.then(work, work);
10
+ const settled = next.then(
11
+ () => undefined,
12
+ () => undefined,
13
+ );
14
+ tails.set(key, settled);
15
+ void settled.then(() => {
16
+ if (tails.get(key) === settled) tails.delete(key);
17
+ });
18
+ return next;
19
+ }
@@ -0,0 +1,80 @@
1
+ import { McpToolError } from "./errors.ts";
2
+
3
+ /** What a tool call counts against: reads, draft writes or publishes (W-478). */
4
+ export type RateClass = "read" | "write" | "publish";
5
+
6
+ /** Per token: 300 reads and 60 writes a minute, 10 publishes an hour. */
7
+ export const RATE_LIMITS: Record<RateClass, { limit: number; windowMs: number; per: string }> = {
8
+ read: { limit: 300, windowMs: 60_000, per: "a minute" },
9
+ write: { limit: 60, windowMs: 60_000, per: "a minute" },
10
+ publish: { limit: 10, windowMs: 3_600_000, per: "an hour" },
11
+ };
12
+
13
+ export const rateClassOf = (def: { readOnly: boolean; publish?: string }): RateClass =>
14
+ def.publish ? "publish" : def.readOnly ? "read" : "write";
15
+
16
+ /** The part of EmDash's plugin KV the limiter needs. It lives in the site database, so it holds
17
+ * across Node processes and Cloudflare isolates alike. */
18
+ export interface RateStore {
19
+ getVersioned<T>(key: string): Promise<{ value: T; revision: string } | null>;
20
+ compareAndSet(
21
+ key: string,
22
+ expectedRevision: string | null,
23
+ value: unknown,
24
+ ): Promise<{ applied: boolean }>;
25
+ }
26
+
27
+ type Window = { w: number; n: number };
28
+
29
+ const NOUNS: Record<RateClass, string> = { read: "reads", write: "changes", publish: "publishes" };
30
+
31
+ /**
32
+ * Counts one call for `who` in a fixed window and refuses it with RATE_LIMITED once the window is
33
+ * full. Compare-and-set keeps parallel calls from slipping through on a stale count.
34
+ */
35
+ export async function hitRateLimit(
36
+ store: RateStore,
37
+ who: string,
38
+ cls: RateClass,
39
+ now: () => number = Date.now,
40
+ ): Promise<void> {
41
+ const { limit, windowMs, per } = RATE_LIMITS[cls];
42
+ const key = `ratelimit:${cls}:${who}`;
43
+ for (let attempt = 0; attempt < 100; attempt++) {
44
+ const at = now();
45
+ const w = Math.floor(at / windowMs) * windowMs;
46
+ // oxlint-disable-next-line no-await-in-loop -- compare-and-set retries in turn
47
+ const stored = await store.getVersioned<Window>(key);
48
+ const current = stored && stored.value?.w === w ? stored.value.n : 0;
49
+ if (current >= limit) {
50
+ const retryAfterSeconds = Math.max(1, Math.ceil((w + windowMs - at) / 1000));
51
+ throw new McpToolError(
52
+ "RATE_LIMITED",
53
+ `Too many ${NOUNS[cls]}: this token may make ${limit} ${per}. Try again in ${retryAfterSeconds} seconds.`,
54
+ { retryAfterSeconds, limit, per },
55
+ );
56
+ }
57
+ // oxlint-disable-next-line no-await-in-loop -- compare-and-set retries in turn
58
+ const write = await store.compareAndSet(key, stored?.revision ?? null, { w, n: current + 1 });
59
+ if (write.applied) return;
60
+ }
61
+ throw new McpToolError(
62
+ "RATE_LIMITED",
63
+ "Too many calls at once from this token. Try again in 1 second.",
64
+ { retryAfterSeconds: 1 },
65
+ );
66
+ }
67
+
68
+ /** A short, non-reversible id for the caller's token, so no token is ever stored (W-478). */
69
+ export async function callerKey(request: Request | undefined, userId: string | null) {
70
+ const auth = request?.headers.get("authorization") ?? "";
71
+ const token = /^Bearer\s+(.+)$/i.exec(auth)?.[1]?.trim();
72
+ if (token) {
73
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
74
+ return `t:${[...new Uint8Array(digest)]
75
+ .slice(0, 12)
76
+ .map((b) => b.toString(16).padStart(2, "0"))
77
+ .join("")}`;
78
+ }
79
+ return userId ? `u:${userId}` : "anonymous";
80
+ }