@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.
- package/README.md +23 -3
- package/THIRD_PARTY_NOTICES.md +23 -1
- package/licenses/exif-js.LICENSE +21 -0
- package/licenses/fflate.LICENSE +21 -0
- package/licenses/glfx.js.LICENSE +19 -0
- package/licenses/mini-photo-editor.LICENSE +21 -0
- package/licenses/photocn.LICENSE +21 -0
- package/package.json +5 -3
- package/src/admin/agents-api.ts +39 -0
- package/src/admin/editor/CommandPalette.tsx +43 -2
- package/src/admin/editor/Editor.tsx +33 -0
- package/src/admin/editor/Timeline.tsx +108 -6
- package/src/admin/editor/collection-previews.ts +6 -1
- package/src/admin/editor/editor-chrome.tsx +49 -0
- package/src/admin/editor/editor-commands.ts +13 -0
- package/src/admin/editor/editor-css.ts +7 -0
- package/src/admin/editor/feature-css.ts +22 -3
- package/src/admin/editor/palette.ts +6 -2
- package/src/admin/editor/panels/ColorControl.tsx +24 -12
- package/src/admin/editor/panels/ElementPanel.tsx +1 -1
- package/src/admin/editor/panels/LayersPanel.tsx +13 -3
- package/src/admin/editor/panels/TokenScales.tsx +4 -2
- package/src/admin/editor/panels/VariableSection.tsx +5 -3
- package/src/admin/editor/panels/color-space.ts +12 -1
- package/src/admin/editor/panels/settings/AdvancedFields.tsx +84 -28
- package/src/admin/editor/panels/settings/AudienceEditor.tsx +42 -4
- package/src/admin/editor/panels/settings/DraftTextField.tsx +38 -9
- package/src/admin/editor/panels/settings/FieldControl.tsx +24 -7
- package/src/admin/editor/panels/settings/IconPicker.tsx +21 -1
- package/src/admin/editor/panels/settings/ImageSourcesField.tsx +111 -0
- package/src/admin/editor/panels/settings/MediaPicker.tsx +156 -7
- package/src/admin/editor/panels/settings/QueryStyleRows.tsx +178 -0
- package/src/admin/editor/panels/settings/RequiredFieldsNotice.tsx +76 -0
- package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
- package/src/admin/editor/panels/settings/link-rules.ts +19 -0
- package/src/admin/editor/panels/settings/number-input.ts +11 -0
- package/src/admin/editor/panels/settings/query-style.ts +65 -0
- package/src/admin/editor/panels/variable-values.ts +18 -2
- package/src/admin/editor/remote-change.ts +67 -0
- package/src/admin/editor/store.ts +7 -3
- package/src/admin/image-editor/BlurFocus.tsx +112 -0
- package/src/admin/image-editor/Canvas.tsx +261 -0
- package/src/admin/image-editor/CropOverlay.tsx +390 -0
- package/src/admin/image-editor/CurvesPanel.tsx +394 -0
- package/src/admin/image-editor/ExportDialog.tsx +354 -0
- package/src/admin/image-editor/ImageEditButton.tsx +83 -0
- package/src/admin/image-editor/ImageEditorDialog.tsx +786 -0
- package/src/admin/image-editor/MetadataPanel.tsx +183 -0
- package/src/admin/image-editor/announce.tsx +65 -0
- package/src/admin/image-editor/crop-geometry.ts +161 -0
- package/src/admin/image-editor/curve-math.ts +177 -0
- package/src/admin/image-editor/data-url-fetch.ts +59 -0
- package/src/admin/image-editor/engine.ts +55 -0
- package/src/admin/image-editor/exif.ts +82 -0
- package/src/admin/image-editor/flatten.ts +54 -0
- package/src/admin/image-editor/gpu-fit.ts +81 -0
- package/src/admin/image-editor/image-editor-css.ts +398 -0
- package/src/admin/image-editor/load.ts +109 -0
- package/src/admin/image-editor/panels.tsx +287 -0
- package/src/admin/image-editor/parts.tsx +565 -0
- package/src/admin/image-editor/save.ts +125 -0
- package/src/admin/image-editor/tone-panels.tsx +338 -0
- package/src/admin/image-editor/tools.ts +59 -0
- package/src/admin/image-editor/worker.ts +111 -0
- package/src/admin/index.tsx +3 -1
- package/src/admin/media-api.ts +132 -2
- package/src/admin/pages/AgentsPage.tsx +274 -0
- package/src/admin/ui.ts +33 -0
- package/src/astro/EmVBPage.astro +11 -2
- package/src/astro/floats/runtime.ts +10 -0
- package/src/astro/popups/runtime.ts +15 -0
- package/src/astro/render.ts +3 -0
- package/src/astro/resolve-theme.ts +15 -4
- package/src/astro/tabs/runtime.ts +60 -1
- package/src/astro/visitor.ts +4 -3
- package/src/constants.ts +1 -1
- package/src/core/a11y/audit.ts +202 -26
- package/src/core/arrange.ts +13 -3
- package/src/core/css/generate.ts +9 -1
- package/src/core/data/bindings.ts +12 -6
- package/src/core/design/classes.ts +5 -3
- package/src/core/design/diff.ts +3 -1
- package/src/core/design/merge.ts +3 -1
- package/src/core/design/transfer.ts +13 -2
- package/src/core/design/variables.ts +2 -1
- package/src/core/elements/dynamic-elements.ts +9 -1
- package/src/core/elements/form-elements.ts +18 -3
- package/src/core/elements/index.ts +39 -11
- package/src/core/elements/plain-text.ts +2 -2
- package/src/core/forms/binding.ts +148 -1
- package/src/core/history/diff.ts +32 -4
- package/src/core/image-edit/schema.ts +145 -0
- package/src/core/image-edit/summary.ts +58 -0
- package/src/core/index.ts +14 -0
- package/src/core/limits.ts +10 -0
- package/src/core/migrate/index.ts +3 -1
- package/src/core/perf/meter.ts +9 -1
- package/src/core/render/dynamic-post.ts +23 -6
- package/src/core/render/form.ts +36 -11
- package/src/core/render/index.ts +75 -15
- package/src/core/render/pagination.ts +21 -2
- package/src/core/sanitize/embed-url.ts +7 -1
- package/src/core/sanitize/href.ts +13 -1
- package/src/core/schema/descriptors.ts +4 -1
- package/src/core/schema/layout.ts +21 -4
- package/src/core/share/link.ts +9 -3
- package/src/core/stable-json.ts +15 -0
- package/src/core/theme/dynamic.ts +32 -24
- package/src/core/theme/pagination.ts +30 -3
- package/src/core/theme/popup-rules.ts +10 -5
- package/src/mcp/errors.ts +44 -0
- package/src/mcp/index.ts +4 -0
- package/src/mcp/ports.ts +85 -0
- package/src/mcp/prompts.ts +76 -0
- package/src/mcp/publish.ts +60 -0
- package/src/mcp/queue.ts +19 -0
- package/src/mcp/rate-limit.ts +80 -0
- package/src/mcp/read.ts +486 -0
- package/src/mcp/refs.ts +84 -0
- package/src/mcp/settings.ts +18 -0
- package/src/mcp/tools.ts +265 -0
- package/src/mcp/write.ts +664 -0
- package/src/server/agent-settings.ts +159 -0
- package/src/server/design-routes.ts +71 -17
- package/src/server/icon-routes.ts +13 -6
- package/src/server/mcp-routes.ts +323 -0
- package/src/server/plugin.ts +32 -2
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import {
|
|
2
|
+
PluginRouteError,
|
|
3
|
+
type ContentPolicyDecision,
|
|
4
|
+
type ContentPolicyEvent,
|
|
5
|
+
type PluginContext,
|
|
6
|
+
type PluginRoute,
|
|
7
|
+
} from "emdash";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { PAGES_COLLECTION, THEME_PARTS_COLLECTION } from "../constants.ts";
|
|
10
|
+
import { AgentSettings, DEFAULT_AGENT_SETTINGS } from "../mcp/settings.ts";
|
|
11
|
+
|
|
12
|
+
/** Plugin KV key of the agent settings (plan § 4, D-055). */
|
|
13
|
+
const AGENT_SETTINGS_KEY = "agent-settings";
|
|
14
|
+
|
|
15
|
+
/** The agent settings and their revision. Missing or damaged settings read as the safe defaults. */
|
|
16
|
+
export async function readAgentSettings(
|
|
17
|
+
ctx: Pick<PluginContext, "kv">,
|
|
18
|
+
): Promise<{ settings: AgentSettings; revision: string | null }> {
|
|
19
|
+
const stored = await ctx.kv.getVersioned<unknown>(AGENT_SETTINGS_KEY);
|
|
20
|
+
if (!stored) return { settings: DEFAULT_AGENT_SETTINGS, revision: null };
|
|
21
|
+
const parsed = AgentSettings.safeParse(stored.value);
|
|
22
|
+
return {
|
|
23
|
+
settings: parsed.success ? parsed.data : DEFAULT_AGENT_SETTINGS,
|
|
24
|
+
revision: stored.revision,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type LogQuery = {
|
|
29
|
+
query(o: {
|
|
30
|
+
where?: Record<string, unknown>;
|
|
31
|
+
orderBy: Record<string, "asc" | "desc">;
|
|
32
|
+
limit: number;
|
|
33
|
+
}): Promise<{
|
|
34
|
+
items: { id: string; data: unknown }[];
|
|
35
|
+
}>;
|
|
36
|
+
put(id: string, data: unknown): Promise<void>;
|
|
37
|
+
deleteMany?(ids: string[]): Promise<number>;
|
|
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
|
+
|
|
65
|
+
const agentLog = (ctx: PluginContext) => ctx.storage["agentlog"] as unknown as LogQuery;
|
|
66
|
+
|
|
67
|
+
/** Agents tab: the settings, the MCP endpoint and the last 50 agent changes. Admins only. */
|
|
68
|
+
export const agentsRoute: PluginRoute = {
|
|
69
|
+
permission: "plugins:manage",
|
|
70
|
+
handler: async (ctx) => {
|
|
71
|
+
const { settings, revision } = await readAgentSettings(ctx);
|
|
72
|
+
const log = await agentLog(ctx).query({ orderBy: { at: "desc" }, limit: 50 });
|
|
73
|
+
return {
|
|
74
|
+
settings,
|
|
75
|
+
revision,
|
|
76
|
+
endpoint: new URL("/_emdash/api/mcp", ctx.request.url).toString(),
|
|
77
|
+
activity: log.items.map((item) => Object.assign({ id: item.id }, item.data as object)),
|
|
78
|
+
};
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const PageAgentsInput = z.object({ pageId: z.string().min(1).max(128) });
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* W-460: the page's versions an agent saved, for the Timeline's Agent badge and filter. Editors
|
|
86
|
+
* can read this (it carries no settings); the full activity list stays admin-only.
|
|
87
|
+
*/
|
|
88
|
+
export const pageAgentVersionsRoute: PluginRoute<z.infer<typeof PageAgentsInput>> = {
|
|
89
|
+
permission: "content:edit_any",
|
|
90
|
+
input: PageAgentsInput,
|
|
91
|
+
handler: async (ctx) => {
|
|
92
|
+
const log = await agentLog(ctx).query({
|
|
93
|
+
where: { pageId: ctx.input.pageId },
|
|
94
|
+
orderBy: { at: "desc" },
|
|
95
|
+
limit: 100,
|
|
96
|
+
});
|
|
97
|
+
const versions = log.items
|
|
98
|
+
.map(
|
|
99
|
+
(item) => item.data as { revisionId?: string; tool: string; summary: string; at: string },
|
|
100
|
+
)
|
|
101
|
+
.filter((entry) => entry.revisionId)
|
|
102
|
+
.map((entry) => ({
|
|
103
|
+
revisionId: entry.revisionId as string,
|
|
104
|
+
tool: entry.tool,
|
|
105
|
+
summary: entry.summary,
|
|
106
|
+
at: entry.at,
|
|
107
|
+
}));
|
|
108
|
+
return { versions };
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const SaveInput = z.object({ settings: AgentSettings, revision: z.string().nullable() });
|
|
113
|
+
|
|
114
|
+
/** Saves the agent settings (compare-and-set). Admins only; no MCP tool can reach this. */
|
|
115
|
+
export const agentsSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
|
|
116
|
+
permission: "plugins:manage",
|
|
117
|
+
input: SaveInput,
|
|
118
|
+
handler: async (ctx) => {
|
|
119
|
+
const write = await ctx.kv.compareAndSet(
|
|
120
|
+
AGENT_SETTINGS_KEY,
|
|
121
|
+
ctx.input.revision,
|
|
122
|
+
ctx.input.settings,
|
|
123
|
+
);
|
|
124
|
+
if (!write.applied) {
|
|
125
|
+
throw PluginRouteError.conflict("The agent settings changed somewhere else. Reload them.");
|
|
126
|
+
}
|
|
127
|
+
const s = ctx.input.settings;
|
|
128
|
+
await appendAgentLog(agentLog(ctx), {
|
|
129
|
+
target: "settings",
|
|
130
|
+
tool: "settings",
|
|
131
|
+
userId: ctx.user?.id ?? null,
|
|
132
|
+
summary: `Agent settings: access ${s.mcpEnabled ? "on" : "off"}, publish pages ${s.publishPages ? "on" : "off"}, publish styles ${s.publishStyles ? "on" : "off"}`,
|
|
133
|
+
});
|
|
134
|
+
return { revision: write.revision };
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const OWNED = new Set([PAGES_COLLECTION, THEME_PARTS_COLLECTION]);
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* D-055: refuse publishing EmVB content through EmDash's own MCP tools (e.g. `content_publish`)
|
|
142
|
+
* unless the admin let agents publish pages. Our `publish_page` tool publishes with a plugin
|
|
143
|
+
* origin after its own settings check.
|
|
144
|
+
*/
|
|
145
|
+
export async function beforePublish(
|
|
146
|
+
event: ContentPolicyEvent,
|
|
147
|
+
ctx: PluginContext,
|
|
148
|
+
): Promise<ContentPolicyDecision> {
|
|
149
|
+
if (!OWNED.has(event.collection)) return undefined;
|
|
150
|
+
const source = event.origin.source === "mcp" || event.actor?.source === "mcp";
|
|
151
|
+
if (!source) return undefined;
|
|
152
|
+
const { settings } = await readAgentSettings(ctx);
|
|
153
|
+
if (settings.mcpEnabled && settings.publishPages) return undefined;
|
|
154
|
+
return {
|
|
155
|
+
cancel: true,
|
|
156
|
+
reason:
|
|
157
|
+
"Agents may not publish EmVB pages on this site. An admin can allow it in Pages VisualBuilder → AI agents.",
|
|
158
|
+
};
|
|
159
|
+
}
|
|
@@ -27,7 +27,10 @@ type DesignResponse = {
|
|
|
27
27
|
status: "ok" | "empty" | "unreadable";
|
|
28
28
|
};
|
|
29
29
|
|
|
30
|
-
const readDesign = async (
|
|
30
|
+
export const readDesign = async (
|
|
31
|
+
ctx: RouteContext<unknown>,
|
|
32
|
+
key: string,
|
|
33
|
+
): Promise<DesignResponse> => {
|
|
31
34
|
const current = await store(ctx).getVersioned(key);
|
|
32
35
|
if (!current) return { design: emptyDesign(), revision: null, status: "empty" };
|
|
33
36
|
const result = validateDesign(current.value);
|
|
@@ -88,20 +91,62 @@ export const designSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
|
|
|
88
91
|
const summary = summarizeIssues(result.issues);
|
|
89
92
|
throw new PluginRouteError("INVALID_DESIGN", `The design system is invalid. ${summary}`, 422);
|
|
90
93
|
}
|
|
91
|
-
const write = await
|
|
92
|
-
|
|
93
|
-
ctx.input.revision,
|
|
94
|
-
result.design,
|
|
95
|
-
);
|
|
96
|
-
if (!write.applied) {
|
|
94
|
+
const write = await writeDesignDraft(ctx, result.design, ctx.input.revision, "editor");
|
|
95
|
+
if (!write) {
|
|
97
96
|
throw PluginRouteError.conflict(
|
|
98
97
|
"The design system was changed somewhere else. Reload it and try again.",
|
|
99
98
|
);
|
|
100
99
|
}
|
|
101
|
-
return { revision: write
|
|
100
|
+
return { revision: write };
|
|
102
101
|
},
|
|
103
102
|
};
|
|
104
103
|
|
|
104
|
+
/** Keep the last 50 style drafts and publishes (D-057), newest first by key. */
|
|
105
|
+
const DESIGN_HISTORY_LIMIT = 50;
|
|
106
|
+
|
|
107
|
+
type HistoryStore = {
|
|
108
|
+
put(id: string, data: unknown): Promise<void>;
|
|
109
|
+
query(o: { orderBy: Record<string, "asc" | "desc">; limit: number; cursor?: string }): Promise<{
|
|
110
|
+
items: { id: string; data: unknown }[];
|
|
111
|
+
}>;
|
|
112
|
+
deleteMany(ids: string[]): Promise<number>;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/** Records a style draft or publish in the design history, then trims it to the limit. */
|
|
116
|
+
async function recordDesign(
|
|
117
|
+
ctx: RouteContext<unknown>,
|
|
118
|
+
design: DesignSystem,
|
|
119
|
+
kind: "draft" | "publish",
|
|
120
|
+
by: "editor" | "agent",
|
|
121
|
+
) {
|
|
122
|
+
const history = ctx.storage["designhistory"] as unknown as HistoryStore | undefined;
|
|
123
|
+
if (!history) return;
|
|
124
|
+
const at = new Date().toISOString();
|
|
125
|
+
await history.put(`${at}-${crypto.randomUUID().slice(0, 8)}`, {
|
|
126
|
+
at,
|
|
127
|
+
kind,
|
|
128
|
+
by,
|
|
129
|
+
userId: ctx.user?.id ?? null,
|
|
130
|
+
design,
|
|
131
|
+
});
|
|
132
|
+
const old = await history.query({ orderBy: { at: "desc" }, limit: 100 });
|
|
133
|
+
const extra = old.items.slice(DESIGN_HISTORY_LIMIT).map((item) => item.id);
|
|
134
|
+
if (extra.length > 0) await history.deleteMany(extra);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Compare-and-set of the style draft, recorded in the history. The new revision, or null on conflict. */
|
|
138
|
+
export async function writeDesignDraft(
|
|
139
|
+
ctx: RouteContext<unknown>,
|
|
140
|
+
design: DesignSystem,
|
|
141
|
+
expectedRevision: string | null,
|
|
142
|
+
by: "editor" | "agent",
|
|
143
|
+
): Promise<string | null> {
|
|
144
|
+
const write = await store(ctx).compareAndSet(DESIGN_DRAFT_KEY, expectedRevision, design);
|
|
145
|
+
if (!write.applied) return null;
|
|
146
|
+
await recordDesign(ctx, design, "draft", by);
|
|
147
|
+
return write.revision;
|
|
148
|
+
}
|
|
149
|
+
|
|
105
150
|
const PublishInput = z.object({ publishedRevision: z.string().nullable() });
|
|
106
151
|
|
|
107
152
|
/** Copies the style draft onto the published design. Pages are not republished (W-100). */
|
|
@@ -109,20 +154,29 @@ export const designPublishRoute: PluginRoute<z.infer<typeof PublishInput>> = {
|
|
|
109
154
|
permission: "content:edit_any",
|
|
110
155
|
input: PublishInput,
|
|
111
156
|
handler: async (ctx) => {
|
|
112
|
-
const
|
|
113
|
-
if (
|
|
157
|
+
const result = await publishDesignDraft(ctx, ctx.input.publishedRevision, "editor");
|
|
158
|
+
if (result === "no-draft") {
|
|
114
159
|
throw new PluginRouteError("NO_STYLE_DRAFT", "There are no style changes to publish.", 409);
|
|
115
160
|
}
|
|
116
|
-
|
|
117
|
-
DESIGN_KEY,
|
|
118
|
-
ctx.input.publishedRevision,
|
|
119
|
-
draft.design,
|
|
120
|
-
);
|
|
121
|
-
if (!write.applied) {
|
|
161
|
+
if (result === "conflict") {
|
|
122
162
|
throw PluginRouteError.conflict(
|
|
123
163
|
"Site styles were published somewhere else. Reload the editor and try again.",
|
|
124
164
|
);
|
|
125
165
|
}
|
|
126
|
-
return { revision:
|
|
166
|
+
return { revision: result.revision };
|
|
127
167
|
},
|
|
128
168
|
};
|
|
169
|
+
|
|
170
|
+
/** Copies the style draft onto the published design (compare-and-set) and records it. */
|
|
171
|
+
export async function publishDesignDraft(
|
|
172
|
+
ctx: RouteContext<unknown>,
|
|
173
|
+
expectedPublishedRevision: string | null,
|
|
174
|
+
by: "editor" | "agent",
|
|
175
|
+
): Promise<"no-draft" | "conflict" | { revision: string }> {
|
|
176
|
+
const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
|
|
177
|
+
if (draft.status !== "ok") return "no-draft";
|
|
178
|
+
const write = await store(ctx).compareAndSet(DESIGN_KEY, expectedPublishedRevision, draft.design);
|
|
179
|
+
if (!write.applied) return "conflict";
|
|
180
|
+
await recordDesign(ctx, draft.design, "publish", by);
|
|
181
|
+
return { revision: write.revision };
|
|
182
|
+
}
|
|
@@ -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 {
|
|
@@ -33,11 +34,13 @@ const UPLOAD_LIST_LIMIT = 100;
|
|
|
33
34
|
|
|
34
35
|
/** A file name without its folder or extension, as the icon's label. */
|
|
35
36
|
export const uploadName = (name: string) =>
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
clipText(
|
|
38
|
+
name
|
|
39
|
+
.replace(/^.*[\\/]/, "")
|
|
40
|
+
.replace(/\.svg$/i, "")
|
|
41
|
+
.trim(),
|
|
42
|
+
80,
|
|
43
|
+
).trim() || "Uploaded icon";
|
|
41
44
|
|
|
42
45
|
/**
|
|
43
46
|
* One stored upload safe to send to the editor. Markup that no longer passes the SVG allowlist
|
|
@@ -111,8 +114,12 @@ export const iconRenameRoute: PluginRoute<z.infer<typeof RenameInput>> = {
|
|
|
111
114
|
const current = await store(ctx).get(ctx.input.id);
|
|
112
115
|
if (!current) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
|
|
113
116
|
const name = uploadName(ctx.input.name);
|
|
117
|
+
// W-390: answer with the same checked markup the list sends; a row that fails the
|
|
118
|
+
// allowlist is not renamed or echoed back.
|
|
119
|
+
const item = publicUploadedIcon(ctx.input.id, { ...current, name });
|
|
120
|
+
if (!item) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
|
|
114
121
|
await store(ctx).put(ctx.input.id, { ...current, name });
|
|
115
|
-
return { item
|
|
122
|
+
return { item };
|
|
116
123
|
},
|
|
117
124
|
};
|
|
118
125
|
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
|
|
2
|
+
import { PAGES_COLLECTION, DESIGN_DRAFT_KEY, DESIGN_KEY } from "../constants.ts";
|
|
3
|
+
import { McpToolError } from "../mcp/errors.ts";
|
|
4
|
+
import type { RequiredFieldInfo } from "../core/index.ts";
|
|
5
|
+
import type { EmvbPorts, PageRecord, PageSummary } from "../mcp/ports.ts";
|
|
6
|
+
import { callerKey, hitRateLimit, type RateStore } from "../mcp/rate-limit.ts";
|
|
7
|
+
import { runTool, type ToolDef } from "../mcp/tools.ts";
|
|
8
|
+
import { publishDesignDraft, readDesign, writeDesignDraft } from "./design-routes.ts";
|
|
9
|
+
import { appendAgentLog, readAgentSettings } from "./agent-settings.ts";
|
|
10
|
+
|
|
11
|
+
type Item = {
|
|
12
|
+
id: string;
|
|
13
|
+
slug: string | null;
|
|
14
|
+
status: string;
|
|
15
|
+
data: Record<string, unknown>;
|
|
16
|
+
updatedAt: string;
|
|
17
|
+
publishedAt: string | null;
|
|
18
|
+
draftRevisionId?: string | null;
|
|
19
|
+
liveRevisionId?: string | null;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
type Content = {
|
|
23
|
+
list(
|
|
24
|
+
c: string,
|
|
25
|
+
o: { limit?: number; cursor?: string },
|
|
26
|
+
): Promise<{
|
|
27
|
+
items: Item[];
|
|
28
|
+
cursor?: string;
|
|
29
|
+
hasMore: boolean;
|
|
30
|
+
}>;
|
|
31
|
+
getVersioned?(c: string, id: string): Promise<{ item: Item; _rev: string } | null>;
|
|
32
|
+
listRevisions?(
|
|
33
|
+
c: string,
|
|
34
|
+
id: string,
|
|
35
|
+
o: { limit?: number },
|
|
36
|
+
): Promise<{ id: string; createdAt: string; authorId?: string | null }[]>;
|
|
37
|
+
getRevision?(
|
|
38
|
+
c: string,
|
|
39
|
+
id: string,
|
|
40
|
+
revisionId: string,
|
|
41
|
+
): Promise<{ data: Record<string, unknown> } | null>;
|
|
42
|
+
update(c: string, id: string, data: Record<string, unknown>): Promise<Item>;
|
|
43
|
+
create(c: string, data: Record<string, unknown>): Promise<Item>;
|
|
44
|
+
publish?(c: string, id: string, o: { _rev: string }): Promise<unknown>;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const parseJson = (raw: unknown) => {
|
|
48
|
+
if (typeof raw !== "string") return raw;
|
|
49
|
+
try {
|
|
50
|
+
return JSON.parse(raw) as unknown;
|
|
51
|
+
} catch {
|
|
52
|
+
return raw;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const summary = (item: Item): PageSummary => ({
|
|
57
|
+
id: item.id,
|
|
58
|
+
title: typeof item.data["title"] === "string" ? item.data["title"] : "Untitled page",
|
|
59
|
+
slug: item.slug ?? "",
|
|
60
|
+
status: item.status,
|
|
61
|
+
hasDraft: Boolean(item.draftRevisionId && item.draftRevisionId !== item.liveRevisionId),
|
|
62
|
+
updatedAt: item.updatedAt,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
const FORMS_DEFINITION = "/_emdash/api/plugins/emdash-forms/definition";
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* W-511: form fields for describe_page's required-field warnings, from the forms plugin's public
|
|
69
|
+
* definition route on this site. A plugin route has no in-process handle on another plugin, so
|
|
70
|
+
* this is a same-origin request with a short timeout; a form it can't read is left out.
|
|
71
|
+
*/
|
|
72
|
+
async function loadFormFieldsFromSite(
|
|
73
|
+
origin: string,
|
|
74
|
+
formIds: readonly string[],
|
|
75
|
+
): Promise<Map<string, RequiredFieldInfo[]>> {
|
|
76
|
+
const found = new Map<string, RequiredFieldInfo[]>();
|
|
77
|
+
await Promise.all(
|
|
78
|
+
formIds.slice(0, 20).map(async (id) => {
|
|
79
|
+
try {
|
|
80
|
+
const response = await fetch(new URL(FORMS_DEFINITION, origin), {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: { "content-type": "application/json" },
|
|
83
|
+
body: JSON.stringify({ id }),
|
|
84
|
+
signal: AbortSignal.timeout(3000),
|
|
85
|
+
});
|
|
86
|
+
if (!response.ok) return;
|
|
87
|
+
const body = (await response.json()) as { data?: unknown };
|
|
88
|
+
const data = (body?.data ?? body) as { pages?: unknown };
|
|
89
|
+
if (!Array.isArray(data?.pages)) return;
|
|
90
|
+
const fields: RequiredFieldInfo[] = [];
|
|
91
|
+
for (const page of data.pages as { fields?: unknown }[]) {
|
|
92
|
+
if (!Array.isArray(page?.fields)) continue;
|
|
93
|
+
for (const raw of page.fields as Record<string, unknown>[]) {
|
|
94
|
+
if (typeof raw?.name !== "string") continue;
|
|
95
|
+
fields.push({
|
|
96
|
+
name: raw.name,
|
|
97
|
+
label: typeof raw.label === "string" ? raw.label : raw.name,
|
|
98
|
+
required: raw.required === true,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
found.set(id, fields);
|
|
103
|
+
} catch {
|
|
104
|
+
// The forms plugin is missing, the form is unknown, or the site can't reach itself.
|
|
105
|
+
}
|
|
106
|
+
}),
|
|
107
|
+
);
|
|
108
|
+
return found;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The tool core's ports on a plugin route (D-053, R1 save path). */
|
|
112
|
+
function pluginPorts(ctx: RouteContext<unknown>): EmvbPorts {
|
|
113
|
+
const content = ctx.content as unknown as Content | undefined;
|
|
114
|
+
if (!content) throw new McpToolError("FORBIDDEN", "EmVB has no content access on this site.");
|
|
115
|
+
/**
|
|
116
|
+
* W-497: before "Set up EmVB", EmDash reads a page of the missing collection as "not found", so
|
|
117
|
+
* get_layout said "No EmVB page". A miss checks the collection once and says NOT_SET_UP instead.
|
|
118
|
+
*/
|
|
119
|
+
const versioned = async (id: string) => {
|
|
120
|
+
const found = content.getVersioned ? await content.getVersioned(PAGES_COLLECTION, id) : null;
|
|
121
|
+
if (!found) {
|
|
122
|
+
try {
|
|
123
|
+
await content.list(PAGES_COLLECTION, { limit: 1 });
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (isNotSetUp(error)) throw new McpToolError("NOT_SET_UP", NOT_SET_UP_MESSAGE);
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return found;
|
|
130
|
+
};
|
|
131
|
+
return {
|
|
132
|
+
caller: { userId: ctx.user?.id ?? null, role: Number(ctx.user?.role ?? 0) },
|
|
133
|
+
formFields: (formIds) => loadFormFieldsFromSite(ctx.request.url, formIds),
|
|
134
|
+
async rateLimit(cls) {
|
|
135
|
+
await hitRateLimit(
|
|
136
|
+
ctx.kv as unknown as RateStore,
|
|
137
|
+
await callerKey(ctx.request, ctx.user?.id ?? null),
|
|
138
|
+
cls,
|
|
139
|
+
);
|
|
140
|
+
},
|
|
141
|
+
async listPages({ cursor, limit }) {
|
|
142
|
+
let result: Awaited<ReturnType<Content["list"]>>;
|
|
143
|
+
try {
|
|
144
|
+
result = await content.list(PAGES_COLLECTION, { limit, ...(cursor ? { cursor } : {}) });
|
|
145
|
+
} catch (error) {
|
|
146
|
+
// W-474: a cursor the agent made up or truncated was an INTERNAL_ERROR.
|
|
147
|
+
if (cursor && /cursor/i.test(String((error as Error)?.message ?? error))) {
|
|
148
|
+
throw new McpToolError(
|
|
149
|
+
"INVALID_INPUT",
|
|
150
|
+
"That cursor isn't valid. Pass nextCursor exactly as list_pages returned it, or leave it out to start again.",
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
pages: result.items.map(summary),
|
|
157
|
+
...(result.hasMore && result.cursor ? { nextCursor: result.cursor } : {}),
|
|
158
|
+
};
|
|
159
|
+
},
|
|
160
|
+
async getPage(id): Promise<PageRecord | null> {
|
|
161
|
+
const found = await versioned(id);
|
|
162
|
+
if (!found) return null;
|
|
163
|
+
return {
|
|
164
|
+
...summary(found.item),
|
|
165
|
+
layout: parseJson(found.item.data["layout"]),
|
|
166
|
+
rev: found["_rev"],
|
|
167
|
+
};
|
|
168
|
+
},
|
|
169
|
+
async listRevisions(id, limit) {
|
|
170
|
+
const list = content.listRevisions
|
|
171
|
+
? await content.listRevisions(PAGES_COLLECTION, id, { limit })
|
|
172
|
+
: [];
|
|
173
|
+
return list.map((r) => ({ id: r.id, createdAt: r.createdAt, authorId: r.authorId ?? null }));
|
|
174
|
+
},
|
|
175
|
+
async getRevisionData(id, revisionId) {
|
|
176
|
+
const revision = content.getRevision
|
|
177
|
+
? await content.getRevision(PAGES_COLLECTION, id, revisionId)
|
|
178
|
+
: null;
|
|
179
|
+
return revision?.data ?? null;
|
|
180
|
+
},
|
|
181
|
+
async savePage(id, patch, expectedRev) {
|
|
182
|
+
const current = await versioned(id);
|
|
183
|
+
if (!current) throw new McpToolError("NOT_FOUND", `No EmVB page with id ${id}.`);
|
|
184
|
+
if (current["_rev"] !== expectedRev) {
|
|
185
|
+
throw new McpToolError("CONFLICT", "The page changed since it was read.", {
|
|
186
|
+
rev: current["_rev"],
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
await content.update(PAGES_COLLECTION, id, {
|
|
190
|
+
...(patch.layout ? { layout: patch.layout } : {}),
|
|
191
|
+
...(patch.title ? { title: patch.title } : {}),
|
|
192
|
+
});
|
|
193
|
+
const after = await versioned(id);
|
|
194
|
+
return {
|
|
195
|
+
rev: after?.["_rev"] ?? "",
|
|
196
|
+
...(after?.item.draftRevisionId ? { revisionId: after.item.draftRevisionId } : {}),
|
|
197
|
+
};
|
|
198
|
+
},
|
|
199
|
+
async createPage({ title, layout }) {
|
|
200
|
+
// Plugins can't choose a slug on create; EmDash derives it from the title.
|
|
201
|
+
const item = await content.create(PAGES_COLLECTION, { title, layout });
|
|
202
|
+
const after = await versioned(item.id);
|
|
203
|
+
return { id: item.id, slug: String(item.slug ?? ""), rev: after?.["_rev"] ?? "" };
|
|
204
|
+
},
|
|
205
|
+
async saveDesign(design, expectedRevision) {
|
|
206
|
+
const written = await writeDesignDraft(ctx, design, expectedRevision, "agent");
|
|
207
|
+
if (!written) throw new McpToolError("CONFLICT", "Site styles changed since they were read.");
|
|
208
|
+
return { revision: written };
|
|
209
|
+
},
|
|
210
|
+
async log(entry) {
|
|
211
|
+
const store = ctx.storage["agentlog"] as unknown as Parameters<typeof appendAgentLog>[0];
|
|
212
|
+
await appendAgentLog(store, {
|
|
213
|
+
...entry,
|
|
214
|
+
userId: ctx.user?.id ?? null,
|
|
215
|
+
client: (ctx.request.headers.get("user-agent") ?? "").slice(0, 120),
|
|
216
|
+
});
|
|
217
|
+
},
|
|
218
|
+
settings: async () => (await readAgentSettings(ctx)).settings,
|
|
219
|
+
async publishPage(id, expectedRev) {
|
|
220
|
+
if (!content.publish)
|
|
221
|
+
throw new McpToolError("FORBIDDEN", "This site can't publish from plugins.");
|
|
222
|
+
try {
|
|
223
|
+
await content.publish(PAGES_COLLECTION, id, { _rev: expectedRev });
|
|
224
|
+
} catch (error) {
|
|
225
|
+
const code = (error as { code?: string }).code ?? "";
|
|
226
|
+
if (/CONFLICT|REV/i.test(code)) {
|
|
227
|
+
throw new McpToolError(
|
|
228
|
+
"CONFLICT",
|
|
229
|
+
"The page changed since you read it. Call get_layout again.",
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
if (/NOT_FOUND/i.test(code))
|
|
233
|
+
throw new McpToolError("NOT_FOUND", `No EmVB page with id ${id}.`);
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
const after = await versioned(id);
|
|
237
|
+
return { rev: after?.["_rev"] ?? "" };
|
|
238
|
+
},
|
|
239
|
+
async publishDesign(expectedPublishedRevision) {
|
|
240
|
+
const result = await publishDesignDraft(ctx, expectedPublishedRevision, "agent");
|
|
241
|
+
if (result === "no-draft")
|
|
242
|
+
throw new McpToolError("REFUSED", "There are no style changes to publish.");
|
|
243
|
+
if (result === "conflict") {
|
|
244
|
+
throw new McpToolError(
|
|
245
|
+
"CONFLICT",
|
|
246
|
+
"Site styles were published somewhere else. Call get_site_styles again.",
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
return { revision: result.revision };
|
|
250
|
+
},
|
|
251
|
+
async getDesign() {
|
|
252
|
+
const published = await readDesign(ctx, DESIGN_KEY);
|
|
253
|
+
const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
|
|
254
|
+
if (draft.status !== "ok") {
|
|
255
|
+
return {
|
|
256
|
+
design: published.design,
|
|
257
|
+
revision: draft.revision,
|
|
258
|
+
publishedRevision: published.revision,
|
|
259
|
+
unpublished: false,
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
return {
|
|
263
|
+
design: draft.design,
|
|
264
|
+
revision: draft.revision,
|
|
265
|
+
publishedRevision: published.revision,
|
|
266
|
+
unpublished: JSON.stringify(draft.design) !== JSON.stringify(published.design),
|
|
267
|
+
};
|
|
268
|
+
},
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** W-474: before "Set up EmVB" there is no `emvb_pages` table, and every page tool was an INTERNAL_ERROR. */
|
|
273
|
+
export const NOT_SET_UP_MESSAGE =
|
|
274
|
+
'EmVB isn\'t set up on this site yet. Ask an admin to open Pages VisualBuilder in the EmDash admin and click "Set up EmVB", then try again.';
|
|
275
|
+
|
|
276
|
+
export const isNotSetUp = (error: unknown) =>
|
|
277
|
+
/no such table:?\s*\W?ec_emvb_|relation "?ec_emvb_\w+"? does not exist|collection "?emvb_(pages|theme_parts)"? (not found|does not exist)/i.test(
|
|
278
|
+
String((error as Error)?.message ?? error),
|
|
279
|
+
);
|
|
280
|
+
|
|
281
|
+
/** Routes `mcp/<tool>`: editors and above (D-056), POST JSON, one per tool (R1 D-054). */
|
|
282
|
+
export function mcpRoutes(tools: readonly ToolDef[]): Record<string, PluginRoute> {
|
|
283
|
+
return Object.fromEntries(
|
|
284
|
+
tools.map((tool) => [
|
|
285
|
+
`mcp/${tool.name}`,
|
|
286
|
+
{
|
|
287
|
+
permission: "content:edit_any",
|
|
288
|
+
input: tool.input,
|
|
289
|
+
handler: async (ctx: RouteContext<unknown>) => {
|
|
290
|
+
try {
|
|
291
|
+
return await runTool(tool, pluginPorts(ctx), ctx.input);
|
|
292
|
+
} catch (error) {
|
|
293
|
+
if (error instanceof McpToolError) {
|
|
294
|
+
throw new PluginRouteError(error.code, error.message, error.status, error.details);
|
|
295
|
+
}
|
|
296
|
+
if (isNotSetUp(error)) {
|
|
297
|
+
throw new PluginRouteError("NOT_SET_UP", NOT_SET_UP_MESSAGE, 409);
|
|
298
|
+
}
|
|
299
|
+
throw error;
|
|
300
|
+
}
|
|
301
|
+
},
|
|
302
|
+
} satisfies PluginRoute,
|
|
303
|
+
]),
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** `definePlugin({ mcp })`: EmDash lists these on /_emdash/api/mcp as `emvb__<name>`. */
|
|
308
|
+
export function mcpToolConfig(tools: readonly ToolDef[]) {
|
|
309
|
+
return {
|
|
310
|
+
tools: Object.fromEntries(
|
|
311
|
+
tools.map((tool) => [
|
|
312
|
+
tool.name,
|
|
313
|
+
{
|
|
314
|
+
description: tool.description,
|
|
315
|
+
route: `mcp/${tool.name}`,
|
|
316
|
+
input: tool.input,
|
|
317
|
+
output: tool.output,
|
|
318
|
+
destructive: tool.destructive,
|
|
319
|
+
},
|
|
320
|
+
]),
|
|
321
|
+
),
|
|
322
|
+
};
|
|
323
|
+
}
|