@mainsoft/agent-cms 0.0.0-stage → 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 (108) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +21 -0
  3. package/README.md +359 -2
  4. package/TODO.md +178 -0
  5. package/UPGRADE-0.6.md +236 -0
  6. package/dist/agent.cjs +250 -0
  7. package/dist/agent.d.cts +88 -0
  8. package/dist/agent.d.ts +88 -0
  9. package/dist/agent.js +24 -0
  10. package/dist/ai.cjs +555 -0
  11. package/dist/ai.d.cts +48 -0
  12. package/dist/ai.d.ts +48 -0
  13. package/dist/ai.js +73 -0
  14. package/dist/bin.js +1556 -0
  15. package/dist/chunk-2NTK7H4W.js +10 -0
  16. package/dist/chunk-52NUUZC7.js +1446 -0
  17. package/dist/chunk-6K5ZTGHQ.js +30 -0
  18. package/dist/chunk-AKN7SUXU.js +281 -0
  19. package/dist/chunk-CRDW6Q72.js +188 -0
  20. package/dist/chunk-DD56PTZ4.js +78 -0
  21. package/dist/chunk-DOADAH4L.js +52 -0
  22. package/dist/chunk-EXV6JNLY.js +251 -0
  23. package/dist/chunk-IGL2V6US.js +324 -0
  24. package/dist/chunk-IW3D4I7Q.js +317 -0
  25. package/dist/chunk-OQ55GEF3.js +6 -0
  26. package/dist/chunk-QC2M4NZY.js +158 -0
  27. package/dist/chunk-QQV6VLYJ.js +204 -0
  28. package/dist/chunk-T66ZKBHF.js +25 -0
  29. package/dist/chunk-VICZ76TR.js +118 -0
  30. package/dist/chunk-Y63XQS2J.js +6 -0
  31. package/dist/cli.cjs +1596 -0
  32. package/dist/cli.d.cts +89 -0
  33. package/dist/cli.d.ts +89 -0
  34. package/dist/cli.js +534 -0
  35. package/dist/client.cjs +185 -0
  36. package/dist/client.d.cts +228 -0
  37. package/dist/client.d.ts +228 -0
  38. package/dist/client.js +13 -0
  39. package/dist/cms-BPp01z-8.d.ts +411 -0
  40. package/dist/cms-D6D89-qZ.d.cts +411 -0
  41. package/dist/config.cjs +61 -0
  42. package/dist/config.d.cts +36 -0
  43. package/dist/config.d.ts +36 -0
  44. package/dist/config.js +11 -0
  45. package/dist/diff.cjs +316 -0
  46. package/dist/diff.d.cts +122 -0
  47. package/dist/diff.d.ts +122 -0
  48. package/dist/diff.js +29 -0
  49. package/dist/drizzle-repo-B1rt7r4j.d.ts +90 -0
  50. package/dist/drizzle-repo-Cn-kL2FK.d.cts +90 -0
  51. package/dist/errors.cjs +193 -0
  52. package/dist/errors.d.cts +109 -0
  53. package/dist/errors.d.ts +109 -0
  54. package/dist/errors.js +16 -0
  55. package/dist/frontmatter.cjs +103 -0
  56. package/dist/frontmatter.d.cts +32 -0
  57. package/dist/frontmatter.d.ts +32 -0
  58. package/dist/frontmatter.js +9 -0
  59. package/dist/http.cjs +1105 -0
  60. package/dist/http.d.cts +75 -0
  61. package/dist/http.d.ts +75 -0
  62. package/dist/http.js +321 -0
  63. package/dist/index.cjs +3066 -0
  64. package/dist/index.d.cts +19 -0
  65. package/dist/index.d.ts +19 -0
  66. package/dist/index.js +263 -0
  67. package/dist/markdown.cjs +220 -0
  68. package/dist/markdown.d.cts +88 -0
  69. package/dist/markdown.d.ts +88 -0
  70. package/dist/markdown.js +23 -0
  71. package/dist/mcp.cjs +652 -0
  72. package/dist/mcp.d.cts +43 -0
  73. package/dist/mcp.d.ts +43 -0
  74. package/dist/mcp.js +26 -0
  75. package/dist/messages/en.cjs +76 -0
  76. package/dist/messages/en.d.cts +7 -0
  77. package/dist/messages/en.d.ts +7 -0
  78. package/dist/messages/en.js +7 -0
  79. package/dist/messages/ko.cjs +76 -0
  80. package/dist/messages/ko.d.cts +7 -0
  81. package/dist/messages/ko.d.ts +7 -0
  82. package/dist/messages/ko.js +53 -0
  83. package/dist/registry/cms-audit.json +25 -0
  84. package/dist/registry/cms-command.json +23 -0
  85. package/dist/registry/cms-doc-editor.json +36 -0
  86. package/dist/registry/cms-doc-list.json +29 -0
  87. package/dist/registry/cms-empty.json +22 -0
  88. package/dist/registry/cms-keys.json +29 -0
  89. package/dist/registry/cms-lib.json +33 -0
  90. package/dist/registry/cms-merge.json +26 -0
  91. package/dist/registry/cms-shell.json +22 -0
  92. package/dist/registry/cms-versions.json +26 -0
  93. package/dist/registry/registry.json +255 -0
  94. package/dist/repo-BWI2Pkrv.d.ts +162 -0
  95. package/dist/repo-CeDxUxO6.d.cts +162 -0
  96. package/dist/tables.cjs +356 -0
  97. package/dist/tables.d.cts +3515 -0
  98. package/dist/tables.d.ts +3515 -0
  99. package/dist/tables.js +35 -0
  100. package/dist/tools.cjs +420 -0
  101. package/dist/tools.d.cts +27 -0
  102. package/dist/tools.d.ts +27 -0
  103. package/dist/tools.js +18 -0
  104. package/dist/types.cjs +226 -0
  105. package/dist/types.d.cts +286 -0
  106. package/dist/types.d.ts +286 -0
  107. package/dist/types.js +28 -0
  108. package/package.json +277 -4
@@ -0,0 +1,75 @@
1
+ import { C as CmsLike } from './cms-D6D89-qZ.cjs';
2
+ import { McpOptions } from './mcp.cjs';
3
+ import { Actor } from './types.cjs';
4
+ import 'zod';
5
+ import './diff.cjs';
6
+ import './errors.cjs';
7
+ import './repo-CeDxUxO6.cjs';
8
+ import '@modelcontextprotocol/sdk/server/index.js';
9
+
10
+ /**
11
+ * REST API + MCP endpoint over one catch-all route. Mount as
12
+ * `app/api/cms/[...path]/route.ts`:
13
+ *
14
+ * const handler = createCmsHandler({ cms, resolveUser });
15
+ * export { handler as GET, handler as POST, handler as PUT, handler as PATCH, handler as DELETE };
16
+ *
17
+ * Auth: an `Authorization: Bearer sgk_…` key, else the app's session user
18
+ * (`resolveUser`), else anonymous (published reads only).
19
+ *
20
+ * Concurrency: GET of a document sends `ETag: "v<n>"`; writes take
21
+ * `If-Match: "v<n>"` (or `expectedVersion` in the body) and answer 409 with
22
+ * the current working copy (`current`) when someone saved in between.
23
+ *
24
+ * GET /_me who am I, what may I do
25
+ * GET /collections/:c list (?fields=summary&state=&q=&category=&by=&limit=&cursor=&hits=1, ?drafts=1)
26
+ * POST /collections/:c create {doc, publish?, note?}
27
+ * GET /collections/:c/_counts numbers per state (editors)
28
+ * GET /collections/:c/_schema fields as JSON Schema + admin hints
29
+ * POST /collections/:c/_diagnose {doc, slug?} → every problem, nothing saved
30
+ * POST /collections/:c/_bulk {action, items:[{slug, expectedVersion?}]}
31
+ * GET /collections/:c/:slug read (?draft=1 for the working copy)
32
+ * PATCH /collections/:c/:slug update {doc, expectedVersion?, publish?, note?}
33
+ * DELETE /collections/:c/:slug
34
+ * POST /collections/:c/:slug/patch {ops, expectedVersion?, dryRun?}
35
+ * GET /collections/:c/:slug/sections
36
+ * PUT /collections/:c/:slug/autosave {doc, baseVersion} DELETE: discard
37
+ * GET /collections/:c/:slug/changes agent changes waiting for review
38
+ * POST /collections/:c/:slug/review {hunks: [...] | "all", action?}
39
+ * POST /collections/:c/:slug/preview {ttl: "1h" | "24h" | "7d"}
40
+ * POST /collections/:c/:slug/publish | archive | unarchive | unpublish
41
+ * GET /collections/:c/:slug/versions[/:n] (?fields=summary)
42
+ * GET /collections/:c/:slug/diff?a=&b=
43
+ * POST /collections/:c/:slug/versions/:n/restore {publish?}
44
+ * GET /search?q=&collections=a,b&miss=1 miss=1: call onSearchMiss when nothing is found
45
+ * GET /preview?token= the version a preview link points at
46
+ * GET /keys | POST /keys {name, scopes, collections?, expiresAt?} | DELETE /keys/:id
47
+ * GET /audit?cursor=&action=&outcome=&actorKind= (also /_audit)
48
+ * POST /mcp MCP (official SDK, streamable HTTP, stateless)
49
+ */
50
+
51
+ interface CmsHandlerOptions {
52
+ cms: CmsLike;
53
+ /** The signed-in app user, if any. */
54
+ resolveUser: (req: Request) => Promise<Extract<Actor, {
55
+ kind: "user";
56
+ }> | null>;
57
+ /** Mount point, used to find the sub-path. Default "/api/cms". */
58
+ basePath?: string;
59
+ /** Refuse PATCH and DELETE of a document without If-Match / expectedVersion (428). Default false. */
60
+ requireIfMatch?: boolean;
61
+ /**
62
+ * MCP options. `anonymous: "read"` lets requests without a key use the MCP
63
+ * endpoint with read tools only (published documents of collections anyone
64
+ * can read). Default: a key is required (401).
65
+ */
66
+ mcp?: McpOptions;
67
+ }
68
+ declare function json(data: unknown, status?: number, headers?: Record<string, string>): Response;
69
+ declare function errorResponse(err: unknown, cms?: CmsLike): Response;
70
+ declare function resolveActor(cms: CmsLike, req: Request, resolveUser: CmsHandlerOptions["resolveUser"]): Promise<Actor>;
71
+ /** `If-Match: "v12"` (or W/"v12", or 12) → 12. */
72
+ declare function versionFromIfMatch(h: string | null): number | undefined;
73
+ declare function createCmsHandler(opts: CmsHandlerOptions): (req: Request) => Promise<Response>;
74
+
75
+ export { type CmsHandlerOptions, createCmsHandler, errorResponse, json, resolveActor, versionFromIfMatch };
package/dist/http.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ import { C as CmsLike } from './cms-BPp01z-8.js';
2
+ import { McpOptions } from './mcp.js';
3
+ import { Actor } from './types.js';
4
+ import 'zod';
5
+ import './diff.js';
6
+ import './errors.js';
7
+ import './repo-BWI2Pkrv.js';
8
+ import '@modelcontextprotocol/sdk/server/index.js';
9
+
10
+ /**
11
+ * REST API + MCP endpoint over one catch-all route. Mount as
12
+ * `app/api/cms/[...path]/route.ts`:
13
+ *
14
+ * const handler = createCmsHandler({ cms, resolveUser });
15
+ * export { handler as GET, handler as POST, handler as PUT, handler as PATCH, handler as DELETE };
16
+ *
17
+ * Auth: an `Authorization: Bearer sgk_…` key, else the app's session user
18
+ * (`resolveUser`), else anonymous (published reads only).
19
+ *
20
+ * Concurrency: GET of a document sends `ETag: "v<n>"`; writes take
21
+ * `If-Match: "v<n>"` (or `expectedVersion` in the body) and answer 409 with
22
+ * the current working copy (`current`) when someone saved in between.
23
+ *
24
+ * GET /_me who am I, what may I do
25
+ * GET /collections/:c list (?fields=summary&state=&q=&category=&by=&limit=&cursor=&hits=1, ?drafts=1)
26
+ * POST /collections/:c create {doc, publish?, note?}
27
+ * GET /collections/:c/_counts numbers per state (editors)
28
+ * GET /collections/:c/_schema fields as JSON Schema + admin hints
29
+ * POST /collections/:c/_diagnose {doc, slug?} → every problem, nothing saved
30
+ * POST /collections/:c/_bulk {action, items:[{slug, expectedVersion?}]}
31
+ * GET /collections/:c/:slug read (?draft=1 for the working copy)
32
+ * PATCH /collections/:c/:slug update {doc, expectedVersion?, publish?, note?}
33
+ * DELETE /collections/:c/:slug
34
+ * POST /collections/:c/:slug/patch {ops, expectedVersion?, dryRun?}
35
+ * GET /collections/:c/:slug/sections
36
+ * PUT /collections/:c/:slug/autosave {doc, baseVersion} DELETE: discard
37
+ * GET /collections/:c/:slug/changes agent changes waiting for review
38
+ * POST /collections/:c/:slug/review {hunks: [...] | "all", action?}
39
+ * POST /collections/:c/:slug/preview {ttl: "1h" | "24h" | "7d"}
40
+ * POST /collections/:c/:slug/publish | archive | unarchive | unpublish
41
+ * GET /collections/:c/:slug/versions[/:n] (?fields=summary)
42
+ * GET /collections/:c/:slug/diff?a=&b=
43
+ * POST /collections/:c/:slug/versions/:n/restore {publish?}
44
+ * GET /search?q=&collections=a,b&miss=1 miss=1: call onSearchMiss when nothing is found
45
+ * GET /preview?token= the version a preview link points at
46
+ * GET /keys | POST /keys {name, scopes, collections?, expiresAt?} | DELETE /keys/:id
47
+ * GET /audit?cursor=&action=&outcome=&actorKind= (also /_audit)
48
+ * POST /mcp MCP (official SDK, streamable HTTP, stateless)
49
+ */
50
+
51
+ interface CmsHandlerOptions {
52
+ cms: CmsLike;
53
+ /** The signed-in app user, if any. */
54
+ resolveUser: (req: Request) => Promise<Extract<Actor, {
55
+ kind: "user";
56
+ }> | null>;
57
+ /** Mount point, used to find the sub-path. Default "/api/cms". */
58
+ basePath?: string;
59
+ /** Refuse PATCH and DELETE of a document without If-Match / expectedVersion (428). Default false. */
60
+ requireIfMatch?: boolean;
61
+ /**
62
+ * MCP options. `anonymous: "read"` lets requests without a key use the MCP
63
+ * endpoint with read tools only (published documents of collections anyone
64
+ * can read). Default: a key is required (401).
65
+ */
66
+ mcp?: McpOptions;
67
+ }
68
+ declare function json(data: unknown, status?: number, headers?: Record<string, string>): Response;
69
+ declare function errorResponse(err: unknown, cms?: CmsLike): Response;
70
+ declare function resolveActor(cms: CmsLike, req: Request, resolveUser: CmsHandlerOptions["resolveUser"]): Promise<Actor>;
71
+ /** `If-Match: "v12"` (or W/"v12", or 12) → 12. */
72
+ declare function versionFromIfMatch(h: string | null): number | undefined;
73
+ declare function createCmsHandler(opts: CmsHandlerOptions): (req: Request) => Promise<Response>;
74
+
75
+ export { type CmsHandlerOptions, createCmsHandler, errorResponse, json, resolveActor, versionFromIfMatch };
package/dist/http.js ADDED
@@ -0,0 +1,321 @@
1
+ import {
2
+ handleMcp,
3
+ toJsonSchema
4
+ } from "./chunk-EXV6JNLY.js";
5
+ import "./chunk-Y63XQS2J.js";
6
+ import "./chunk-QQV6VLYJ.js";
7
+ import {
8
+ BULK_ACTIONS,
9
+ PREVIEW_TTLS,
10
+ coreOf,
11
+ keyFromHeader
12
+ } from "./chunk-52NUUZC7.js";
13
+ import {
14
+ DOC_STATUSES,
15
+ KEY_SCOPES
16
+ } from "./chunk-6K5ZTGHQ.js";
17
+ import "./chunk-OQ55GEF3.js";
18
+ import "./chunk-AKN7SUXU.js";
19
+ import {
20
+ CmsError,
21
+ formatMessage,
22
+ isCmsError
23
+ } from "./chunk-VICZ76TR.js";
24
+ import "./chunk-DOADAH4L.js";
25
+ import "./chunk-CRDW6Q72.js";
26
+ import "./chunk-2NTK7H4W.js";
27
+
28
+ // src/http.ts
29
+ import { z } from "zod";
30
+ var DocInput = z.object({
31
+ slug: z.string().optional(),
32
+ title: z.string().optional(),
33
+ summary: z.string().optional(),
34
+ body: z.string().optional(),
35
+ category: z.string().nullable().optional(),
36
+ keywords: z.array(z.string()).optional(),
37
+ fields: z.record(z.unknown()).optional()
38
+ }).strict();
39
+ var WriteBody = z.object({
40
+ doc: DocInput,
41
+ expectedVersion: z.number().int().positive().optional(),
42
+ publish: z.boolean().optional(),
43
+ note: z.string().max(300).nullable().optional()
44
+ });
45
+ var Expected = z.object({ expectedVersion: z.number().int().positive().optional() });
46
+ function json(data, status = 200, headers = {}) {
47
+ return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...headers } });
48
+ }
49
+ function errorResponse(err, cms) {
50
+ const core = cms ? coreOf(cms) : null;
51
+ if (isCmsError(err)) {
52
+ const body2 = { ...err.toJSON(), message: core ? core.message(err) : err.message };
53
+ return json(body2, err.status);
54
+ }
55
+ if (err instanceof z.ZodError) {
56
+ const issues = err.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
57
+ return json({ error: "invalid_request", kind: "invalid", message: formatMessage(core?.messages, "invalid_request", { issues }), params: { issues } }, 422);
58
+ }
59
+ console.error("[agent-cms] request failed:", err);
60
+ return json({ error: "internal", kind: "internal", message: formatMessage(core?.messages, "internal"), params: {} }, 500);
61
+ }
62
+ var MAX_BODY_BYTES = 512 * 1024;
63
+ async function resolveActor(cms, req, resolveUser) {
64
+ const core = coreOf(cms);
65
+ const raw = keyFromHeader(req.headers.get("authorization"));
66
+ if (raw) {
67
+ const actor = await core.authenticateKey(raw);
68
+ if (!actor) throw new CmsError("invalid_key", {}, { messages: core.messages });
69
+ return actor;
70
+ }
71
+ if (/\bsgk_/.test(req.headers.get("authorization") ?? "")) throw new CmsError("invalid_key", {}, { messages: core.messages });
72
+ const user = await resolveUser(req);
73
+ if (user && !["GET", "HEAD"].includes(req.method.toUpperCase())) {
74
+ const site = req.headers.get("sec-fetch-site");
75
+ const origin = req.headers.get("origin");
76
+ if (site === "cross-site" || origin && new URL(req.url).host !== safeHost(origin)) throw new CmsError("cross_site", {}, { messages: core.messages });
77
+ }
78
+ return user ?? { kind: "anonymous" };
79
+ }
80
+ function safeHost(origin) {
81
+ try {
82
+ return new URL(origin).host;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+ async function readJson(req, optional) {
88
+ const text = await req.text();
89
+ if (text.length > MAX_BODY_BYTES) throw new CmsError("body_too_large", {}, { status: 413 });
90
+ if (!text.trim()) {
91
+ if (optional) return {};
92
+ throw new CmsError("invalid_json");
93
+ }
94
+ try {
95
+ return JSON.parse(text);
96
+ } catch {
97
+ throw new CmsError("invalid_json");
98
+ }
99
+ }
100
+ async function body(req, schema, optional = false) {
101
+ return schema.parse(await readJson(req, optional));
102
+ }
103
+ function versionFromIfMatch(h) {
104
+ if (!h) return void 0;
105
+ const m = /^(?:W\/)?"?v?(\d+)"?$/.exec(h.trim());
106
+ if (!m) throw new CmsError("invalid_version", {}, { status: 400 });
107
+ return Number(m[1]);
108
+ }
109
+ var etag = (d) => `"v${d.version}"`;
110
+ var wire = (d) => d;
111
+ function createCmsHandler(opts) {
112
+ const core = coreOf(opts.cms);
113
+ const base = (opts.basePath ?? "/api/cms").replace(/\/$/, "");
114
+ return async function handler(req) {
115
+ try {
116
+ const url = new URL(req.url);
117
+ if (url.pathname !== base && !url.pathname.startsWith(base + "/")) throw new CmsError("route_not_found");
118
+ const path = url.pathname.slice(base.length);
119
+ let seg;
120
+ try {
121
+ seg = path.split("/").filter(Boolean).map(decodeURIComponent);
122
+ } catch {
123
+ throw new CmsError("invalid_request", { issues: "path encoding" }, { status: 400 });
124
+ }
125
+ const m = req.method.toUpperCase();
126
+ const client = req.headers.get("x-agent-cms-client");
127
+ const who = await resolveActor(core, req, opts.resolveUser);
128
+ const actor = { ...who, via: seg[0] === "mcp" ? client === "cli" ? "cli" : "mcp" : client === "cli" ? "cli" : "rest" };
129
+ const q = url.searchParams;
130
+ const expected = (fromBody) => versionFromIfMatch(req.headers.get("if-match")) ?? fromBody;
131
+ const needMatch = (v) => {
132
+ if (opts.requireIfMatch && v === void 0) throw new CmsError("precondition_required", {}, { messages: core.messages });
133
+ return v;
134
+ };
135
+ if (seg[0] === "mcp" && seg.length === 1) return handleMcp(core, actor, req, opts.mcp);
136
+ if (seg[0] === "_me" && m === "GET") {
137
+ return json({
138
+ actor: actor.kind === "anonymous" ? { kind: "anonymous" } : { kind: actor.kind, label: actor.label, id: "id" in actor ? actor.id : null },
139
+ isAdmin: core.isAdmin(actor),
140
+ previewLinks: core.previewEnabled(),
141
+ collections: core.collections().filter((c) => core.can(actor, c.slug, "read")).map((c) => ({ slug: c.slug, label: c.label, visibility: c.visibility, canWrite: core.can(actor, c.slug, "write"), canPublish: core.can(actor, c.slug, "publish") }))
142
+ });
143
+ }
144
+ if (seg[0] === "search" && m === "GET") {
145
+ const cols = (q.get("collections") ?? "").split(",").filter(Boolean);
146
+ const readable = core.collections().map((c) => c.slug).filter((c) => core.can(actor, c, "read"));
147
+ if (q.has("log")) console.warn("[agent-cms] /search?log=1 was renamed to ?miss=1 in 0.6.0");
148
+ const r = await core.search(actor, cols.length ? cols : readable, q.get("q") ?? "", {
149
+ limit: Math.max(1, Math.min(Number(q.get("limit") ?? 8) || 8, 20)),
150
+ reportMiss: q.get("miss") === "1" || q.get("log") === "1"
151
+ });
152
+ return json({
153
+ empty: r.empty,
154
+ hits: r.hits.map((h) => ({ collection: h.unit.collection, slug: h.unit.slug, title: h.unit.title, summary: h.unit.summary, category: h.unit.category, heading: h.unit.heading, anchor: h.unit.anchor, score: Number(h.score.toFixed(3)) }))
155
+ });
156
+ }
157
+ if (seg[0] === "preview" && seg.length === 1 && m === "GET") return json(await core.readPreview(q.get("token") ?? ""));
158
+ if ((seg[0] === "audit" || seg[0] === "_audit") && seg.length === 1 && m === "GET") {
159
+ const outcome = q.get("outcome");
160
+ return json(
161
+ await core.audit(actor, {
162
+ cursor: q.get("cursor"),
163
+ limit: Number(q.get("limit") ?? 50) || 50,
164
+ action: q.get("action") ?? void 0,
165
+ outcome: outcome === "ok" || outcome === "denied" || outcome === "failed" ? outcome : void 0,
166
+ actorKind: ["user", "key", "system", "anonymous"].find((k) => k === q.get("actorKind"))
167
+ })
168
+ );
169
+ }
170
+ if (seg[0] === "keys") {
171
+ if (seg.length === 1 && m === "GET") return json({ keys: await core.listKeys(actor) });
172
+ if (seg.length === 1 && m === "POST") {
173
+ const b = await body(req, z.object({ name: z.string(), scopes: z.array(z.enum(KEY_SCOPES)).min(1), collections: z.array(z.string()).nullable().optional(), expiresAt: z.string().nullable().optional() }));
174
+ return json(await core.createKey(actor, b), 201);
175
+ }
176
+ if (seg.length === 2 && m === "DELETE") {
177
+ await core.revokeKey(actor, seg[1]);
178
+ return json({ ok: true });
179
+ }
180
+ }
181
+ if (seg[0] === "collections" && seg[1]) {
182
+ const col = seg[1];
183
+ const cfg = core.collection(col);
184
+ if (seg.length === 3 && seg[2] === "_counts" && m === "GET") return json({ counts: await core.counts(actor, col) });
185
+ if (seg.length === 3 && seg[2] === "_schema" && m === "GET") {
186
+ return json({
187
+ slug: cfg.slug,
188
+ label: cfg.label,
189
+ visibility: cfg.visibility,
190
+ categories: cfg.categories ?? null,
191
+ draftsMode: cfg.versions?.drafts !== false,
192
+ hasUrl: !!cfg.url,
193
+ fields: cfg.fields ? toJsonSchema(cfg.fields) : null,
194
+ admin: cfg.admin?.fields ?? {},
195
+ forbiddenChars: cfg.forbiddenChars ?? [],
196
+ canWrite: core.can(actor, col, "write"),
197
+ canPublish: core.can(actor, col, "publish")
198
+ });
199
+ }
200
+ if (seg.length === 3 && seg[2] === "_diagnose" && m === "POST") {
201
+ const b = await body(req, z.object({ doc: DocInput, slug: z.string().optional() }));
202
+ return json({ diagnostics: await core.diagnose(actor, col, b.doc, { slug: b.slug }) });
203
+ }
204
+ if (seg.length === 3 && seg[2] === "_bulk" && m === "POST") {
205
+ const b = await body(req, z.object({ action: z.enum(BULK_ACTIONS), items: z.array(z.object({ slug: z.string(), expectedVersion: z.number().int().positive().optional() })).min(1).max(200) }));
206
+ return json({ results: await core.bulk(actor, col, b.action, b.items) });
207
+ }
208
+ if (seg.length === 2) {
209
+ if (m === "GET") {
210
+ const status = q.get("status");
211
+ const state = q.get("state");
212
+ const by = q.get("by");
213
+ const lo = {
214
+ drafts: q.get("drafts") === "1" || q.get("fields") === "summary",
215
+ status: DOC_STATUSES.includes(status ?? "") ? status : void 0,
216
+ state: ["draft", "published", "modified", "archived"].find((x) => x === state),
217
+ by: ["user", "key", "system"].find((x) => x === by),
218
+ category: q.get("category") ?? void 0,
219
+ q: q.get("q") ?? void 0
220
+ };
221
+ if (q.get("fields") === "summary") {
222
+ return json(await core.page(actor, col, { ...lo, limit: Number(q.get("limit") ?? 50) || 50, cursor: q.get("cursor"), hits: q.get("hits") === "1" }));
223
+ }
224
+ const docs = await core.list(actor, col, lo);
225
+ let counts = null;
226
+ if (q.get("hits") === "1" && core.can(actor, col, "write")) counts = await core.hitCounts(actor, col, 7);
227
+ return json({ docs: docs.map((d) => ({ ...wire(d), hits7d: counts?.get(d.id) ?? void 0 })) });
228
+ }
229
+ if (m === "POST") {
230
+ const b = await body(req, WriteBody);
231
+ return json({ doc: wire(await core.create(actor, col, b.doc, b)) }, 201);
232
+ }
233
+ }
234
+ const slug = seg[2];
235
+ if (slug && seg.length === 3) {
236
+ if (m === "GET" || m === "HEAD") {
237
+ const doc = await core.get(actor, col, slug, { draft: q.get("draft") === "1" });
238
+ const tag = etag(doc);
239
+ if (req.headers.get("if-none-match") === tag) return new Response(null, { status: 304, headers: { etag: tag } });
240
+ return json({ doc: wire(doc) }, 200, { etag: tag });
241
+ }
242
+ if (m === "PATCH") {
243
+ const b = await body(req, WriteBody);
244
+ const doc = await core.update(actor, col, slug, b.doc, { ...b, expectedVersion: needMatch(expected(b.expectedVersion)) });
245
+ return json({ doc: wire(doc) }, 200, { etag: etag(doc) });
246
+ }
247
+ if (m === "DELETE") {
248
+ await core.remove(actor, col, slug, { expectedVersion: needMatch(expected(Number(q.get("expectedVersion")) || void 0)) });
249
+ return json({ ok: true });
250
+ }
251
+ }
252
+ if (slug && seg.length === 4) {
253
+ const action = seg[3];
254
+ if (action === "patch" && m === "POST") {
255
+ const b = await body(
256
+ req,
257
+ z.object({
258
+ ops: z.array(z.object({ op: z.enum(["replace", "insert_after", "insert_before", "delete", "append"]), anchor: z.string().optional(), markdown: z.string().optional(), heading: z.string().optional() })).min(1).max(50),
259
+ expectedVersion: z.number().int().positive().optional(),
260
+ dryRun: z.boolean().optional(),
261
+ note: z.string().max(300).optional()
262
+ })
263
+ );
264
+ return json(await core.patch(actor, col, slug, b.ops, { ...b, expectedVersion: expected(b.expectedVersion) }));
265
+ }
266
+ if (action === "sections" && m === "GET") return json({ sections: await core.sections(actor, col, slug) });
267
+ if (action === "autosave" && m === "PUT") {
268
+ const b = await body(req, z.object({ doc: DocInput, baseVersion: z.number().int().positive() }));
269
+ return json({ autosave: await core.autosave(actor, col, slug, b.doc, b.baseVersion) });
270
+ }
271
+ if (action === "autosave" && m === "DELETE") {
272
+ await core.discardAutosave(actor, col, slug);
273
+ return json({ ok: true });
274
+ }
275
+ if (action === "changes" && m === "GET") return json({ changes: await core.agentChanges(actor, col, slug) });
276
+ if (action === "review" && m === "POST") {
277
+ const b = await body(req, z.object({ hunks: z.union([z.literal("all"), z.array(z.string()).min(1)]), action: z.enum(["accepted", "reverted"]).optional() }));
278
+ return json(await core.reviewChanges(actor, col, slug, b));
279
+ }
280
+ if (action === "preview" && m === "POST") {
281
+ const b = await body(req, z.object({ ttl: z.enum(Object.keys(PREVIEW_TTLS)).optional() }), true);
282
+ return json(await core.createPreviewLink(actor, col, slug, b), 201);
283
+ }
284
+ if (action === "diff" && m === "GET") {
285
+ const a = Number(q.get("a"));
286
+ const b = Number(q.get("b"));
287
+ if (!Number.isInteger(a) || !Number.isInteger(b) || a < 1 || b < 1) throw new CmsError("invalid_version", {}, { messages: core.messages });
288
+ return json(await core.diff(actor, col, slug, a, b));
289
+ }
290
+ if (m === "POST" && ["publish", "archive", "unarchive", "unpublish"].includes(action)) {
291
+ const b = await body(req, z.object({ version: z.number().int().positive().optional(), expectedVersion: z.number().int().positive().optional() }), true);
292
+ const o = { expectedVersion: expected(b.expectedVersion) };
293
+ const doc = action === "publish" ? await core.publish(actor, col, slug, { ...o, version: b.version }) : action === "archive" ? await core.archive(actor, col, slug, o) : action === "unarchive" ? await core.unarchive(actor, col, slug, o) : await core.unpublish(actor, col, slug, o);
294
+ return json({ doc: wire(doc) }, 200, { etag: etag(doc) });
295
+ }
296
+ }
297
+ if (slug && seg[3] === "versions") {
298
+ if (seg.length === 4 && m === "GET") return json({ versions: q.get("fields") === "summary" ? await core.versionList(actor, col, slug) : await core.versions(actor, col, slug) });
299
+ const n = Number(seg[4]);
300
+ if (!Number.isInteger(n) || n < 1) throw new CmsError("invalid_version", {}, { messages: core.messages });
301
+ if (seg.length === 5 && m === "GET") return json({ version: await core.version(actor, col, slug, n) });
302
+ if (seg.length === 6 && seg[5] === "restore" && m === "POST") {
303
+ const b = await body(req, Expected.extend({ publish: z.boolean().optional() }), true);
304
+ const doc = await core.restore(actor, col, slug, n, { ...b, expectedVersion: expected(b.expectedVersion) });
305
+ return json({ doc: wire(doc) }, 200, { etag: etag(doc) });
306
+ }
307
+ }
308
+ }
309
+ throw new CmsError("route_not_found");
310
+ } catch (err) {
311
+ return errorResponse(err, core);
312
+ }
313
+ };
314
+ }
315
+ export {
316
+ createCmsHandler,
317
+ errorResponse,
318
+ json,
319
+ resolveActor,
320
+ versionFromIfMatch
321
+ };