@mainsoft/agent-cms 0.10.0 → 0.10.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.2
4
+
5
+ - **Fix (REST):** a signed-in person's writes were refused with `cross_site` ("Cross-site request refused") whenever the app was reached through an address other than the one the server listens on: behind a reverse proxy or a preview tunnel, in a container, or simply by opening a `next start` server as `127.0.0.1` instead of `localhost`. The check compared the page's `Origin` only with `req.url`, which under `next start` holds the listening address. It now also reads the address from `Host` and `X-Forwarded-Host`, the way Next.js does for Server Actions. A page on another site still cannot change any of the three, so the protection is the same. Apps on Vercel were not affected.
6
+ - **New:** `createCmsHandler({ trustedOrigins: ["https://admin.example.com"] })` lets pages at other addresses write with a person's session, for an admin served from its own domain. The app's own address needs no entry.
7
+
8
+ ## 0.10.1
9
+
10
+ - **Fix (cms-doc-editor):** saving or publishing a new document lost its confirmation line ("Saved v1", "Published v1") when the app answered `onCreated` by moving to the document's own address, which is what the examples do. The line now waits for the editor that opens next and shows there once. Update the copy with `npx agent-cms add cms-doc-editor --update`.
11
+
3
12
  ## 0.10.0
4
13
 
5
14
  The first npm release since 0.7.0. It contains 0.8.0 and 0.9.0 below, which were not published on their own: coming from 0.7.0, read [UPGRADE-0.8.md](./UPGRADE-0.8.md) first, then [UPGRADE-0.10.md](./UPGRADE-0.10.md).
package/README.md CHANGED
@@ -139,6 +139,13 @@ That gives you REST under `/api/cms/...` (route list at the top of
139
139
  `ETag: "v<n>"`; send it back as `If-Match` on PATCH/DELETE (or pass
140
140
  `expectedVersion`). `requireIfMatch: true` refuses writes without one (428).
141
141
 
142
+ A write that rides on a person's session must come from a page of the app
143
+ itself: the handler compares the browser's `Origin` with the address of the
144
+ request (`Host`, or `X-Forwarded-Host` behind a proxy) and answers 403
145
+ `cross_site` otherwise. Requests with an API key are not checked. If the
146
+ admin lives at another address, list it:
147
+ `createCmsHandler({ ..., trustedOrigins: ["https://admin.example.com"] })`.
148
+
142
149
  ## Admin screens
143
150
 
144
151
  The screens are source files you copy into your app and then own, like
package/UPGRADE-0.10.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Upgrading to 0.10
2
2
 
3
- 0.10 is not released yet. This file grows as its parts land.
3
+ 0.10.0 is the first npm release after 0.7.0 and contains 0.8.0 and 0.9.0. Coming from 0.7.0, do [UPGRADE-0.8.md](./UPGRADE-0.8.md) first. 0.9.0 needs nothing.
4
4
 
5
5
  ## 1. Schema version 4
6
6
 
@@ -29,7 +29,7 @@ POST /api/cms/_cron
29
29
  Authorization: Bearer <cronSecret>
30
30
  ```
31
31
 
32
- Without `cronSecret` the route answers 404. On Vercel, a cron job with `CRON_SECRET` sends exactly this header. Calling it from two places at once is safe.
32
+ `GET` works too. Without `cronSecret` the route answers 404. On Vercel, a cron job with `CRON_SECRET` sends exactly this header. Calling it from two places at once is safe.
33
33
 
34
34
  ## 4. Type changes
35
35
 
package/UPGRADE-0.8.md CHANGED
@@ -1,7 +1,8 @@
1
1
  # Upgrading to agent-cms 0.8
2
2
 
3
- 0.8 is not released yet. This file grows as its parts land; what is here is
4
- already on `main`.
3
+ 0.8.0 was not published to npm on its own. It is part of 0.10.0, the first
4
+ release after 0.7.0: coming from 0.7.0, do this file first, then
5
+ [UPGRADE-0.10.md](./UPGRADE-0.10.md).
5
6
 
6
7
  ## 1. `./ai` is gone: the package no longer calls into a model library
7
8
 
package/dist/bin.js CHANGED
@@ -5057,7 +5057,7 @@ import { basename, dirname, join, relative, resolve } from "path";
5057
5057
  import { fileURLToPath } from "url";
5058
5058
 
5059
5059
  // src/version.ts
5060
- var VERSION = "0.10.0";
5060
+ var VERSION = "0.10.2";
5061
5061
 
5062
5062
  // src/registry.ts
5063
5063
  var sha = (s) => createHash3("sha256").update(s).digest("hex");
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  VERSION
3
- } from "./chunk-TOZQYJFG.js";
3
+ } from "./chunk-5ODZ2ZJF.js";
4
4
  import {
5
5
  CMS_TOOL_NAMES,
6
6
  runTool,
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var VERSION = "0.10.0";
2
+ var VERSION = "0.10.2";
3
3
 
4
4
  export {
5
5
  VERSION
package/dist/cli.cjs CHANGED
@@ -5097,7 +5097,7 @@ var import_node_path = require("path");
5097
5097
  var import_node_url = require("url");
5098
5098
 
5099
5099
  // src/version.ts
5100
- var VERSION = "0.10.0";
5100
+ var VERSION = "0.10.2";
5101
5101
 
5102
5102
  // src/registry.ts
5103
5103
  var sha = (s) => (0, import_node_crypto3.createHash)("sha256").update(s).digest("hex");
package/dist/cli.js CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  } from "./chunk-IU2SMWAM.js";
17
17
  import {
18
18
  VERSION
19
- } from "./chunk-TOZQYJFG.js";
19
+ } from "./chunk-5ODZ2ZJF.js";
20
20
  import {
21
21
  CmsRemoteError,
22
22
  createCmsClient,
package/dist/http.cjs CHANGED
@@ -24,6 +24,7 @@ __export(http_exports, {
24
24
  errorResponse: () => errorResponse,
25
25
  json: () => json,
26
26
  resolveActor: () => resolveActor,
27
+ sameSite: () => sameSite,
27
28
  versionFromIfMatch: () => versionFromIfMatch
28
29
  });
29
30
  module.exports = __toCommonJS(http_exports);
@@ -957,7 +958,7 @@ async function runTool(cms, actor, name, args = {}, opts = {}) {
957
958
  }
958
959
 
959
960
  // src/version.ts
960
- var VERSION = "0.10.0";
961
+ var VERSION = "0.10.2";
961
962
 
962
963
  // src/mcp.ts
963
964
  var ANONYMOUS_READ_TOOLS = ["list_collections", "search_documents", "read_for_answer", "list_documents", "get_document"];
@@ -1204,7 +1205,17 @@ function errorResponse(err, cms) {
1204
1205
  return json({ error: "internal", kind: "internal", message: formatMessage(core?.messages, "internal"), params: {} }, 500);
1205
1206
  }
1206
1207
  var MAX_BODY_BYTES2 = 512 * 1024;
1207
- async function resolveActor(cms, req, resolveUser) {
1208
+ function sameSite(req, trusted = []) {
1209
+ const origin = req.headers.get("origin");
1210
+ const from = origin ? safeHost(origin) : null;
1211
+ if (from && trusted.some((o) => safeHost(o) === from || o === from)) return true;
1212
+ if (req.headers.get("sec-fetch-site") === "cross-site") return false;
1213
+ if (!origin) return true;
1214
+ if (!from) return false;
1215
+ const own = [safeHost(req.url), req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || null, req.headers.get("host")];
1216
+ return own.some((h) => !!h && h.toLowerCase() === from.toLowerCase());
1217
+ }
1218
+ async function resolveActor(cms, req, resolveUser, trustedOrigins) {
1208
1219
  const core = coreOf(cms);
1209
1220
  const raw = keyFromHeader(req.headers.get("authorization"));
1210
1221
  if (raw) {
@@ -1215,9 +1226,7 @@ async function resolveActor(cms, req, resolveUser) {
1215
1226
  if (/\bsgk_/.test(req.headers.get("authorization") ?? "")) throw new CmsError("invalid_key", {}, { messages: core.messages });
1216
1227
  const user = await resolveUser(req);
1217
1228
  if (user && !["GET", "HEAD"].includes(req.method.toUpperCase())) {
1218
- const site = req.headers.get("sec-fetch-site");
1219
- const origin = req.headers.get("origin");
1220
- if (site === "cross-site" || origin && new URL(req.url).host !== safeHost(origin)) throw new CmsError("cross_site", {}, { messages: core.messages });
1229
+ if (!sameSite(req, trustedOrigins)) throw new CmsError("cross_site", {}, { messages: core.messages });
1221
1230
  }
1222
1231
  if (!user) return { kind: "anonymous" };
1223
1232
  const { agent: _agent, ...person } = user;
@@ -1277,7 +1286,7 @@ function createCmsHandler(opts) {
1277
1286
  return json(await core.runScheduled());
1278
1287
  }
1279
1288
  const client = req.headers.get("x-agent-cms-client");
1280
- const who = await resolveActor(core, req, opts.resolveUser);
1289
+ const who = await resolveActor(core, req, opts.resolveUser, opts.trustedOrigins);
1281
1290
  const actor = { ...who, via: seg[0] === "mcp" ? client === "cli" ? "cli" : "mcp" : client === "cli" ? "cli" : "rest" };
1282
1291
  const q = url.searchParams;
1283
1292
  const expected = (fromBody) => versionFromIfMatch(req.headers.get("if-match")) ?? fromBody;
@@ -1647,5 +1656,6 @@ function createCmsHandler(opts) {
1647
1656
  errorResponse,
1648
1657
  json,
1649
1658
  resolveActor,
1659
+ sameSite,
1650
1660
  versionFromIfMatch
1651
1661
  });
package/dist/http.d.cts CHANGED
@@ -107,6 +107,12 @@ interface CmsHandlerOptions {
107
107
  basePath?: string;
108
108
  /** Refuse PATCH and DELETE of a document without If-Match / expectedVersion (428). Default false. */
109
109
  requireIfMatch?: boolean;
110
+ /**
111
+ * Other addresses whose pages may write with a person's session, e.g.
112
+ * `["https://admin.example.com"]`. The app's own address needs no entry:
113
+ * it is read from the request (`Host`, `X-Forwarded-Host`).
114
+ */
115
+ trustedOrigins?: readonly string[];
110
116
  /**
111
117
  * MCP options. `anonymous: "read"` lets requests without a key use the MCP
112
118
  * endpoint with read tools only (published documents of collections anyone
@@ -116,9 +122,17 @@ interface CmsHandlerOptions {
116
122
  }
117
123
  declare function json(data: unknown, status?: number, headers?: Record<string, string>): Response;
118
124
  declare function errorResponse(err: unknown, cms?: CmsLike): Response;
119
- declare function resolveActor(cms: CmsLike, req: Request, resolveUser: CmsHandlerOptions["resolveUser"]): Promise<Actor>;
125
+ /**
126
+ * Is this write from a page of the app itself? Browsers put the page's
127
+ * address in `Origin`; a page elsewhere cannot change it, nor `Host`, nor
128
+ * add `X-Forwarded-Host`. Behind a proxy (and under `next start`) `req.url`
129
+ * holds the address the server listens on, not the one people open, so the
130
+ * address is also read from those two headers.
131
+ */
132
+ declare function sameSite(req: Request, trusted?: readonly string[]): boolean;
133
+ declare function resolveActor(cms: CmsLike, req: Request, resolveUser: CmsHandlerOptions["resolveUser"], trustedOrigins?: readonly string[]): Promise<Actor>;
120
134
  /** `If-Match: "v12"` (or W/"v12", or 12) → 12. */
121
135
  declare function versionFromIfMatch(h: string | null): number | undefined;
122
136
  declare function createCmsHandler(opts: CmsHandlerOptions): (req: Request) => Promise<Response>;
123
137
 
124
- export { type CmsHandlerOptions, createCmsHandler, errorResponse, json, resolveActor, versionFromIfMatch };
138
+ export { type CmsHandlerOptions, createCmsHandler, errorResponse, json, resolveActor, sameSite, versionFromIfMatch };
package/dist/http.d.ts CHANGED
@@ -107,6 +107,12 @@ interface CmsHandlerOptions {
107
107
  basePath?: string;
108
108
  /** Refuse PATCH and DELETE of a document without If-Match / expectedVersion (428). Default false. */
109
109
  requireIfMatch?: boolean;
110
+ /**
111
+ * Other addresses whose pages may write with a person's session, e.g.
112
+ * `["https://admin.example.com"]`. The app's own address needs no entry:
113
+ * it is read from the request (`Host`, `X-Forwarded-Host`).
114
+ */
115
+ trustedOrigins?: readonly string[];
110
116
  /**
111
117
  * MCP options. `anonymous: "read"` lets requests without a key use the MCP
112
118
  * endpoint with read tools only (published documents of collections anyone
@@ -116,9 +122,17 @@ interface CmsHandlerOptions {
116
122
  }
117
123
  declare function json(data: unknown, status?: number, headers?: Record<string, string>): Response;
118
124
  declare function errorResponse(err: unknown, cms?: CmsLike): Response;
119
- declare function resolveActor(cms: CmsLike, req: Request, resolveUser: CmsHandlerOptions["resolveUser"]): Promise<Actor>;
125
+ /**
126
+ * Is this write from a page of the app itself? Browsers put the page's
127
+ * address in `Origin`; a page elsewhere cannot change it, nor `Host`, nor
128
+ * add `X-Forwarded-Host`. Behind a proxy (and under `next start`) `req.url`
129
+ * holds the address the server listens on, not the one people open, so the
130
+ * address is also read from those two headers.
131
+ */
132
+ declare function sameSite(req: Request, trusted?: readonly string[]): boolean;
133
+ declare function resolveActor(cms: CmsLike, req: Request, resolveUser: CmsHandlerOptions["resolveUser"], trustedOrigins?: readonly string[]): Promise<Actor>;
120
134
  /** `If-Match: "v12"` (or W/"v12", or 12) → 12. */
121
135
  declare function versionFromIfMatch(h: string | null): number | undefined;
122
136
  declare function createCmsHandler(opts: CmsHandlerOptions): (req: Request) => Promise<Response>;
123
137
 
124
- export { type CmsHandlerOptions, createCmsHandler, errorResponse, json, resolveActor, versionFromIfMatch };
138
+ export { type CmsHandlerOptions, createCmsHandler, errorResponse, json, resolveActor, sameSite, versionFromIfMatch };
package/dist/http.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  handleMcp,
3
3
  toJsonSchema
4
- } from "./chunk-AKCXMT3X.js";
5
- import "./chunk-TOZQYJFG.js";
4
+ } from "./chunk-5FMVVBDR.js";
5
+ import "./chunk-5ODZ2ZJF.js";
6
6
  import "./chunk-DSJETZT4.js";
7
7
  import "./chunk-BFVBHIHV.js";
8
8
  import "./chunk-7Y6TU2UA.js";
@@ -65,7 +65,17 @@ function errorResponse(err, cms) {
65
65
  return json({ error: "internal", kind: "internal", message: formatMessage(core?.messages, "internal"), params: {} }, 500);
66
66
  }
67
67
  var MAX_BODY_BYTES = 512 * 1024;
68
- async function resolveActor(cms, req, resolveUser) {
68
+ function sameSite(req, trusted = []) {
69
+ const origin = req.headers.get("origin");
70
+ const from = origin ? safeHost(origin) : null;
71
+ if (from && trusted.some((o) => safeHost(o) === from || o === from)) return true;
72
+ if (req.headers.get("sec-fetch-site") === "cross-site") return false;
73
+ if (!origin) return true;
74
+ if (!from) return false;
75
+ const own = [safeHost(req.url), req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || null, req.headers.get("host")];
76
+ return own.some((h) => !!h && h.toLowerCase() === from.toLowerCase());
77
+ }
78
+ async function resolveActor(cms, req, resolveUser, trustedOrigins) {
69
79
  const core = coreOf(cms);
70
80
  const raw = keyFromHeader(req.headers.get("authorization"));
71
81
  if (raw) {
@@ -76,9 +86,7 @@ async function resolveActor(cms, req, resolveUser) {
76
86
  if (/\bsgk_/.test(req.headers.get("authorization") ?? "")) throw new CmsError("invalid_key", {}, { messages: core.messages });
77
87
  const user = await resolveUser(req);
78
88
  if (user && !["GET", "HEAD"].includes(req.method.toUpperCase())) {
79
- const site = req.headers.get("sec-fetch-site");
80
- const origin = req.headers.get("origin");
81
- if (site === "cross-site" || origin && new URL(req.url).host !== safeHost(origin)) throw new CmsError("cross_site", {}, { messages: core.messages });
89
+ if (!sameSite(req, trustedOrigins)) throw new CmsError("cross_site", {}, { messages: core.messages });
82
90
  }
83
91
  if (!user) return { kind: "anonymous" };
84
92
  const { agent: _agent, ...person } = user;
@@ -138,7 +146,7 @@ function createCmsHandler(opts) {
138
146
  return json(await core.runScheduled());
139
147
  }
140
148
  const client = req.headers.get("x-agent-cms-client");
141
- const who = await resolveActor(core, req, opts.resolveUser);
149
+ const who = await resolveActor(core, req, opts.resolveUser, opts.trustedOrigins);
142
150
  const actor = { ...who, via: seg[0] === "mcp" ? client === "cli" ? "cli" : "mcp" : client === "cli" ? "cli" : "rest" };
143
151
  const q = url.searchParams;
144
152
  const expected = (fromBody) => versionFromIfMatch(req.headers.get("if-match")) ?? fromBody;
@@ -507,5 +515,6 @@ export {
507
515
  errorResponse,
508
516
  json,
509
517
  resolveActor,
518
+ sameSite,
510
519
  versionFromIfMatch
511
520
  };
package/dist/index.cjs CHANGED
@@ -6176,7 +6176,7 @@ function docFromMarkdown(text2, fallbackSlug) {
6176
6176
  }
6177
6177
 
6178
6178
  // src/version.ts
6179
- var VERSION = "0.10.0";
6179
+ var VERSION = "0.10.2";
6180
6180
  // Annotate the CommonJS export names for ESM import in node:
6181
6181
  0 && (module.exports = {
6182
6182
  ASSET_KINDS,
package/dist/index.d.cts CHANGED
@@ -14,6 +14,6 @@ import './diff.cjs';
14
14
  import 'drizzle-orm/pg-core';
15
15
 
16
16
  /** Package version (kept in step with package.json by `src/parts.test.ts`). */
17
- declare const VERSION = "0.10.0";
17
+ declare const VERSION = "0.10.2";
18
18
 
19
19
  export { VERSION };
package/dist/index.d.ts CHANGED
@@ -14,6 +14,6 @@ import './diff.js';
14
14
  import 'drizzle-orm/pg-core';
15
15
 
16
16
  /** Package version (kept in step with package.json by `src/parts.test.ts`). */
17
- declare const VERSION = "0.10.0";
17
+ declare const VERSION = "0.10.2";
18
18
 
19
19
  export { VERSION };
package/dist/index.js CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  } from "./chunk-IU2SMWAM.js";
28
28
  import {
29
29
  VERSION
30
- } from "./chunk-TOZQYJFG.js";
30
+ } from "./chunk-5ODZ2ZJF.js";
31
31
  import {
32
32
  CMS_TOOLS,
33
33
  CMS_TOOL_NAMES,
package/dist/mcp.cjs CHANGED
@@ -705,7 +705,7 @@ async function runTool(cms, actor, name, args = {}, opts = {}) {
705
705
  }
706
706
 
707
707
  // src/version.ts
708
- var VERSION = "0.10.0";
708
+ var VERSION = "0.10.2";
709
709
 
710
710
  // src/mcp.ts
711
711
  var ANONYMOUS_READ_TOOLS = ["list_collections", "search_documents", "read_for_answer", "list_documents", "get_document"];
package/dist/mcp.js CHANGED
@@ -5,8 +5,8 @@ import {
5
5
  createMcpServer,
6
6
  handleMcp,
7
7
  toJsonSchema
8
- } from "./chunk-AKCXMT3X.js";
9
- import "./chunk-TOZQYJFG.js";
8
+ } from "./chunk-5FMVVBDR.js";
9
+ import "./chunk-5ODZ2ZJF.js";
10
10
  import "./chunk-DSJETZT4.js";
11
11
  import "./chunk-BFVBHIHV.js";
12
12
  import "./chunk-7Y6TU2UA.js";
@@ -26,7 +26,7 @@
26
26
  {
27
27
  "path": "registry/cms/cms-doc-editor.tsx",
28
28
  "type": "registry:component",
29
- "content": "// agent-cms registry: cms-doc-editor (0.10.0). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// One document: the info form (from `_schema`), the markdown body with a\n// live preview, autosave, problems from `diagnose()`, agents' changes to\n// accept or revert, save / publish (now or at a set time), review requests,\n// comments, who else has it open, preview links, and a merge screen when\n// someone saved first and the two edits overlap.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Bot, Check, ChevronDown, ChevronLeft, CircleAlert, CircleCheck, Cloud, ExternalLink, FileText, History, Eye, ImagePlus, Layers, Link as LinkIcon, MessageSquare, MoreHorizontal } from \"lucide-react\";\nimport { isCmsRemoteError, type CollectionSchema, type CommentThread, type DocRelease } from \"@mainsoft/agent-cms/client\";\nimport { mergeDocs, resolveDocMerge, splitLines } from \"@mainsoft/agent-cms/diff\";\nimport { docState, type CmsDoc, type AutosaveState, type Presence } from \"@mainsoft/agent-cms/types\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from \"@/components/ui/dropdown-menu\";\nimport { Label } from \"@/components/ui/label\";\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@/components/ui/tabs\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage } from \"./cms-messages\";\nimport { CmsFieldForm, problemKey, type FieldProblem } from \"./cms-field-form\";\nimport { AddToReleaseDialog, BodyBackdrop, CommentsPanel, offsetOf, placeOf, PublishButton, ReviewStrip, ScheduleStrip, type BodyCursor } from \"./cms-flow\";\nimport { assetMarkdown, CmsMediaPicker } from \"./cms-media-picker\";\nimport { pasteAsMarkdown } from \"./cms-paste\";\nimport { CmsMerge } from \"./cms-merge\";\nimport { CodeBox, MarkdownPreview, ModifiedMark, PageHeader, People, Segmented, StateBadge, StatusText } from \"./cms-parts\";\nimport { contentOf, formatTime, formatUntil, formatZoned as formatZonedTime, personColor, relativeTime, sameContent, toInput, useAsync, useCms, useDebounced, useIsMobile, type DocContent } from \"./use-cms\";\n\ntype AgentChange = Awaited<ReturnType<import(\"@mainsoft/agent-cms/client\").RestClient[\"changes\"]>>[number];\ntype PreviewTtl = NonNullable<Parameters<import(\"@mainsoft/agent-cms/client\").RestClient[\"previewLink\"]>[2]>;\ntype Diagnostic = FieldProblem & { code: string };\n\nexport interface CmsDocEditorProps {\n collection: string;\n /** The document to edit; leave out for a new document. */\n slug?: string | null;\n /** Back to the list (mobile header, after delete). */\n onBack?: () => void;\n /** A new document was created (navigate to its editor). */\n onCreated?: (collection: string, slug: string) => void;\n /** After every save or publish. */\n onSaved?: (doc: CmsDoc) => void;\n /** Open the version history. */\n onOpenVersions?: (collection: string, slug: string) => void;\n /** The public page of a published document (shown as \"Public page\" when the collection has a URL). */\n publicUrlFor?: (collection: string, slug: string) => string;\n /** Text before the slug field, e.g. \"/guide/\". */\n slugPrefix?: string;\n /** Milliseconds of quiet before an autosave. Default 1500. */\n autosaveDelay?: number;\n /** Open a release (the \"in the release ...\" strip). */\n onOpenRelease?: (id: string) => void;\n /** How often this screen says \"I am here\" and looks for other people's saves, in ms. Default 15000 (3000 while someone else is here); 0 turns it off. */\n presenceMs?: number;\n className?: string;\n}\n\nconst EMPTY: DocContent = { slug: \"\", title: \"\", summary: \"\", body: \"\", category: null, keywords: [], fields: {} };\n\n/**\n * Undo one agent change in `body`: the added lines go, the removed lines\n * come back (after the line that preceded them). Null when the change can no\n * longer be found.\n */\nexport function revertChange(body: string, ch: Pick<AgentChange, \"added\" | \"removed\" | \"before\">): string | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) {\n if (ch.added.every((l, k) => lines[i + k] === l)) {\n lines.splice(i, ch.added.length, ...ch.removed);\n return lines.join(\"\\n\");\n }\n }\n return null;\n }\n if (ch.before === null) {\n lines.splice(0, 0, ...ch.removed);\n return lines.join(\"\\n\");\n }\n const at = lines.indexOf(ch.before);\n if (at < 0) return null;\n lines.splice(at + 1, 0, ...ch.removed);\n return lines.join(\"\\n\");\n}\n\n/** 1-based line where an agent change sits in `body` (null if gone). */\nfunction lineOf(body: string, ch: AgentChange): number | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) if (ch.added.every((l, k) => lines[i + k] === l)) return i + 1;\n return null;\n }\n if (ch.before === null) return 1;\n const at = lines.indexOf(ch.before);\n return at < 0 ? null : at + 2;\n}\n\ntype Mode = { kind: \"edit\" } | { kind: \"merge\"; base: DocContent; baseVersion: number; mine: DocContent; theirs: CmsDoc };\n\nexport function CmsDocEditor({ collection, slug, onBack, onCreated, onSaved, onOpenVersions, publicUrlFor, slugPrefix, autosaveDelay = 1500, onOpenRelease, presenceMs = 15000, className }: CmsDocEditorProps) {\n const { client, t, locale, me } = useCms();\n const bodyRef = React.useRef<HTMLTextAreaElement>(null);\n /** Where the cursor last was in the body (null: the person never put it there). */\n const caretRef = React.useRef<[number, number] | null>(null);\n const [picking, setPicking] = React.useState(false);\n const mobile = useIsMobile();\n const schemaQ = useAsync(() => client.schema(collection), [client, collection]);\n const schema = schemaQ.data;\n\n const [doc, setDoc] = React.useState<CmsDoc | null>(null);\n const [loadError, setLoadError] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(!!slug);\n const [content, setContentRaw] = React.useState<DocContent>(EMPTY);\n const [saved, setSaved] = React.useState<DocContent>(EMPTY);\n const [baseVersion, setBaseVersion] = React.useState(0);\n const [restoreOffer, setRestoreOffer] = React.useState<AutosaveState | null>(null);\n const [changes, setChanges] = React.useState<AgentChange[]>([]);\n const [reviewed, setReviewed] = React.useState<Record<string, { action: \"accepted\" | \"reverted\"; by: string }>>({});\n const [problems, setProblems] = React.useState<Diagnostic[]>([]);\n const [auto, setAuto] = React.useState<{ state: \"idle\" | \"saving\" | \"saved\" | \"failed\"; at?: string }>({ state: \"idle\" });\n const [status, setStatus] = React.useState<{ text: string; tone: \"muted\" | \"error\" | \"ok\" } | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [mode, setMode] = React.useState<Mode>({ kind: \"edit\" });\n const [previewOpen, setPreviewOpen] = React.useState(false);\n const [infoOpen, setInfoOpen] = React.useState(false);\n const [mobileTab, setMobileTab] = React.useState(\"edit\");\n const [width, setWidth] = React.useState<\"375\" | \"768\" | \"full\">(\"full\");\n const [showProblems, setShowProblems] = React.useState(false);\n const edited = React.useRef(false);\n const [release, setRelease] = React.useState<DocRelease | null>(null);\n const [threads, setThreads] = React.useState<CommentThread[]>([]);\n const [commentsOpen, setCommentsOpen] = React.useState(false);\n const [releaseOpen, setReleaseOpen] = React.useState(false);\n const [others, setOthers] = React.useState<Presence[]>([]);\n\n const isNew = !slug;\n const currentSlug = doc?.slug ?? slug ?? \"\";\n const myLabel = me?.actor.label ?? \"\";\n\n const applyDoc = React.useCallback((d: CmsDoc) => {\n const c = contentOf(d);\n setDoc(d);\n setContentRaw(c);\n setSaved(c);\n setBaseVersion(d.version);\n edited.current = false;\n }, []);\n\n const loadChanges = React.useCallback(\n async (s: string) => {\n try {\n setChanges(await client.changes(collection, s));\n } catch {\n setChanges([]);\n }\n },\n [client, collection]\n );\n\n const loadComments = React.useCallback(\n async (s: string) => {\n try {\n setThreads(await client.comments(collection, s));\n } catch {\n /* readers do not see comments */\n }\n },\n [client, collection]\n );\n\n React.useEffect(() => {\n if (!slug) {\n setDoc(null);\n setContentRaw(EMPTY);\n setSaved(EMPTY);\n setLoading(false);\n return;\n }\n let live = true;\n setLoading(true);\n Promise.all([client.getWithRelease(collection, slug), client.changes(collection, slug).catch(() => [] as AgentChange[]), client.comments(collection, slug).catch(() => [] as CommentThread[])]).then(\n ([r, ch, cm]) => {\n if (!live) return;\n const d = r.doc;\n applyDoc(d);\n setRelease(r.release ?? null);\n setThreads(cm);\n setChanges(ch);\n setReviewed({});\n setRestoreOffer(d.autosave && !sameContent(d.autosave.content, d) ? d.autosave : null);\n setLoadError(null);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLoadError(e);\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [client, collection, slug, applyDoc]);\n\n // ── diagnose and autosave ──\n const diagnose = useDebounced(async (c: DocContent) => {\n try {\n const d = await client.diagnose(collection, toInput(c, doc?.fields), doc?.slug);\n setProblems(d as Diagnostic[]);\n } catch {\n /* the save will tell */\n }\n }, 400);\n\n const autosave = useDebounced(async (c: DocContent, base: number, s: string) => {\n setAuto({ state: \"saving\" });\n try {\n const a = await client.autosave(collection, s, toInput(c, doc?.fields), base);\n setAuto({ state: \"saved\", at: a.at });\n } catch {\n setAuto({ state: \"failed\" });\n }\n }, autosaveDelay);\n\n const setContent = (next: DocContent) => {\n edited.current = true;\n setContentRaw(next);\n };\n\n React.useEffect(() => {\n if (!schema?.canWrite) return;\n if (loading) return;\n void diagnose(content);\n if (edited.current && doc && !sameContent(content, saved)) autosave(content, baseVersion, doc.slug);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [content, schema?.canWrite, loading]);\n\n React.useEffect(() => () => autosave.cancel(), [autosave]);\n\n const byField = React.useMemo(() => {\n const out: Record<string, FieldProblem[]> = {};\n for (const p of problems) (out[problemKey(p.path)] ??= []).push(p);\n return out;\n }, [problems]);\n\n // ── agent changes ──\n const pending = changes.filter((c) => !reviewed[c.id]);\n const revertedIds = Object.entries(reviewed)\n .filter(([, r]) => r.action === \"reverted\")\n .map(([id]) => id);\n\n const accept = async (ids: string[]) => {\n if (!doc || !ids.length) return;\n try {\n await client.review(collection, doc.slug, ids, \"accepted\");\n setReviewed((r) => ({ ...r, ...Object.fromEntries(ids.map((id) => [id, { action: \"accepted\" as const, by: myLabel }])) }));\n } catch (e) {\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n }\n };\n\n const revert = (ch: AgentChange) => {\n const next = revertChange(content.body, ch);\n if (next === null) return;\n setContent({ ...content, body: next });\n setReviewed((r) => ({ ...r, [ch.id]: { action: \"reverted\", by: myLabel } }));\n };\n\n // ── save ──\n const dirty = !sameContent(content, saved) || revertedIds.length > 0;\n\n const save = async (publish: boolean): Promise<CmsDoc | null> => {\n setBusy(true);\n setStatus(null);\n autosave.cancel();\n try {\n let d: CmsDoc;\n if (isNew && !doc) {\n d = await client.create(collection, toInput(content), { publish });\n applyDoc(d);\n setStatus({ text: publish ? t(\"published_v\", { version: d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n onCreated?.(collection, d.slug);\n return d;\n }\n if (!doc) return null;\n if (revertedIds.length) await client.review(collection, doc.slug, revertedIds, \"reverted\").catch(() => undefined);\n if (!sameContent(content, saved) || !publish) d = await client.update(collection, doc.slug, toInput(content, doc.fields), { expectedVersion: baseVersion, publish });\n else d = await client.publish(collection, doc.slug, { expectedVersion: baseVersion });\n applyDoc(d);\n setRestoreOffer(null);\n setAuto({ state: \"idle\" });\n setReviewed((r) => Object.fromEntries(Object.entries(r).filter(([, x]) => x.action === \"accepted\")));\n await loadChanges(d.slug);\n setStatus({ text: publish ? t(\"published_v\", { version: d.publishedVersion ?? d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n return d;\n } catch (e) {\n if (isCmsRemoteError(e) && e.code === \"conflict_version\" && doc) {\n if (!e.current) {\n setStatus({ text: t(\"merge_no_current\"), tone: \"error\" });\n return null;\n }\n try {\n const base = baseVersion === doc.version ? contentOf(doc) : (await client.version(collection, doc.slug, baseVersion)).snapshot;\n setMode({ kind: \"merge\", base, baseVersion, mine: content, theirs: e.current as CmsDoc });\n } catch (e2) {\n setStatus({ text: errorMessage(e2, t), tone: \"error\" });\n }\n return null;\n }\n if (isCmsRemoteError(e) && e.diagnostics?.length) setProblems(e.diagnostics as Diagnostic[]);\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n return null;\n } finally {\n setBusy(false);\n }\n };\n\n // ── schedule and review ──\n /** The saved document these actions apply to: unsaved edits are saved first. */\n const savedDoc = async (): Promise<CmsDoc> => {\n const d = dirty ? await save(false) : doc;\n if (!d) throw new Error(\"not saved\");\n return d;\n };\n const flow = async (fn: (d: CmsDoc) => Promise<CmsDoc>, done: (d: CmsDoc) => string, rethrow = false) => {\n setBusy(true);\n setStatus(null);\n try {\n const d = await fn(await savedDoc());\n applyDoc(d);\n setStatus({ text: done(d), tone: \"ok\" });\n onSaved?.(d);\n } catch (e) {\n if (isCmsRemoteError(e)) setStatus({ text: errorMessage(e, t), tone: \"error\" });\n if (rethrow) throw e;\n } finally {\n setBusy(false);\n }\n };\n const zone = me?.timeZone;\n const scheduleAt = (when: { publishAt: string | null; unpublishAt: string | null }) =>\n flow(\n (d) => client.schedule(collection, d.slug, { ...when, expectedVersion: d.version }),\n (d) => (d.schedule?.publishAt ? t(\"sched_done\", { version: d.schedule.version, time: formatZonedTime(d.schedule.publishAt, locale, zone) }) : t(\"sched_go\")),\n true\n );\n const unschedule = () => flow((d) => client.unschedule(collection, d.slug), () => t(\"sched_cleared\"), true);\n const requestReview = () => flow((d) => client.requestReview(collection, d.slug), () => t(\"review_requested_done\"));\n const approve = () => flow((d) => client.approveReview(collection, d.slug, { publish: true }), (d) => t(\"published_v\", { version: d.publishedVersion ?? d.version }));\n const reject = (note: string) => flow((d) => client.rejectReview(collection, d.slug, note || null), () => t(\"review_rejected_done\"), true);\n\n const restore = () => {\n if (!restoreOffer) return;\n setContent(contentOf(restoreOffer.content));\n setBaseVersion(restoreOffer.baseVersion);\n setRestoreOffer(null);\n };\n const discard = async () => {\n setRestoreOffer(null);\n if (doc) await client.discardAutosave(collection, doc.slug).catch(() => undefined);\n };\n\n // ── who else is here, and their saves ──\n const live = React.useRef({ content, saved, baseVersion, dirty, others: 0 });\n live.current = { content, saved, baseVersion, dirty, others: others.length };\n const slugNow = doc?.slug;\n React.useEffect(() => {\n if (!slugNow || !presenceMs || mode.kind !== \"edit\") return;\n let stop = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const point = (at: number) => {\n const before = live.current.content.body.slice(0, at).split(\"\\n\");\n return { line: before.length, ch: before[before.length - 1].length };\n };\n /** Someone else saved: take it when nothing is unsaved here, merge when the two edits do not overlap. */\n const catchUp = async () => {\n const latest = await client.get(collection, slugNow, { draft: true });\n const now = live.current;\n if (stop || latest.version <= now.baseVersion) return;\n const who = latest.updatedByAgent ?? latest.updatedBy ?? \"\";\n if (!now.dirty) {\n applyDoc(latest);\n void loadChanges(slugNow);\n setStatus({ text: t(\"other_saved\", { who, version: latest.version }), tone: \"muted\" });\n return;\n }\n const m = mergeDocs(now.saved, now.content, contentOf(latest));\n if (m.body.conflicts.length || m.fieldConflicts.length) return; // saving opens the merge screen\n autosave.cancel();\n const merged = contentOf(resolveDocMerge(m, {}));\n // Keep the cursor where it was: text that arrived above it pushes it down.\n const el = bodyRef.current;\n const sel = caretRef.current;\n let same = 0;\n while (same < merged.body.length && merged.body[same] === now.content.body[same]) same++;\n const shift = (at: number) => (at <= same ? at : Math.max(same, at + merged.body.length - now.content.body.length));\n setDoc(latest);\n setSaved(contentOf(latest));\n setBaseVersion(latest.version);\n setContentRaw(merged);\n if (el && sel && document.activeElement === el)\n requestAnimationFrame(() => {\n el.setSelectionRange(shift(sel[0]), shift(sel[1]));\n caretRef.current = [shift(sel[0]), shift(sel[1])];\n });\n setStatus({ text: t(\"other_merged\", { who, version: latest.version }), tone: \"muted\" });\n };\n const beat = async () => {\n try {\n if (document.visibilityState !== \"hidden\") {\n const sel = caretRef.current;\n const r = await client.presence(collection, slugNow, { cursor: sel ? point(sel[1]) : null, selection: sel && sel[0] !== sel[1] ? point(sel[0]) : null });\n if (stop) return;\n setOthers(r.others);\n if (r.version > live.current.baseVersion) await catchUp();\n }\n } catch {\n /* a reader, or offline: nobody is shown */\n }\n if (!stop) timer = setTimeout(() => void beat(), live.current.others ? Math.min(presenceMs, 3000) : presenceMs);\n };\n void beat();\n return () => {\n stop = true;\n if (timer) clearTimeout(timer);\n setOthers([]);\n void client.leave(collection, slugNow).catch(() => undefined);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, collection, slugNow, presenceMs, mode.kind]);\n\n // ── render ──\n if (mode.kind === \"merge\" && doc)\n return (\n <CmsMerge\n collection={collection}\n slug={doc.slug}\n base={mode.base}\n baseVersion={mode.baseVersion}\n mine={mode.mine}\n theirs={mode.theirs}\n crumbs={[schema?.label ?? collection, content.title || doc.slug]}\n className={className}\n onCancel={() => setMode({ kind: \"edit\" })}\n onSaved={(d) => {\n setMode({ kind: \"edit\" });\n setReviewed({});\n applyDoc(d);\n void loadChanges(d.slug);\n setStatus({ text: t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n }}\n />\n );\n\n if (loadError)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText tone=\"error\">{errorMessage(loadError, t)}</StatusText>\n </div>\n );\n if (loading || !schema)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText>{t(\"loading\")}</StatusText>\n </div>\n );\n\n const st = doc ? docState(doc) : null;\n const canWrite = schema.canWrite;\n const canPublish = schema.canPublish;\n const published = !!doc && doc.publishedVersion !== null && doc.status !== \"archived\";\n const publicUrl = published && schema.hasUrl && publicUrlFor && doc ? publicUrlFor(collection, doc.slug) : null;\n const previewAllowed = !!doc && !!me?.previewLinks && schema.hasUrl;\n const title = content.title || (isNew ? t(\"new_doc_title\") : currentSlug);\n const fieldCount = Object.keys(((schema.fields ?? {}) as { properties?: object }).properties ?? {}).length;\n\n const stateBits = st ? (\n <>\n <StateBadge state={doc?.review ? (doc.review.state === \"requested\" ? \"review\" : \"changes\") : st.state} />\n {doc?.schedule?.publishAt ? <StateBadge state=\"scheduled\" /> : null}\n {st.modifiedSincePublish ? <ModifiedMark /> : null}\n </>\n ) : null;\n const mustReview = !!schema.needsReview;\n const openThreads = threads.filter((x) => !x.resolvedAt);\n /** Answering a request is for people who may publish, and never for the one who asked when everyone needs a review. */\n const mayAnswer = canPublish && me?.actor.kind === \"user\" && !(schema.review?.everyone === \"required\" && doc?.review?.byKind === \"user\" && !doc.review.byAgent && doc.review.byId === me.actor.id);\n const quiet = (p: Promise<unknown>) => void p.catch(() => undefined);\n\n const saveButtons = (cls?: string, up?: boolean) =>\n canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" className={cls} disabled={busy || (!dirty && !isNew)} onClick={() => void save(false)}>\n {t(\"save\")}\n </Button>\n {canPublish && !mustReview ? (\n <PublishButton\n className={cls}\n up={up}\n busy={busy}\n disabled={!dirty && !!st && st.state === \"published\" && !st.modifiedSincePublish}\n canSchedule={!!doc}\n schedule={doc?.schedule ?? null}\n onPublish={() => void save(true)}\n onSchedule={scheduleAt}\n onUnschedule={unschedule}\n />\n ) : doc && doc.review?.state !== \"requested\" ? (\n <Button type=\"button\" className={cls} disabled={busy} title={mustReview ? t(\"review_needed\") : undefined} onClick={() => void requestReview()}>\n {t(\"review_request\")}\n </Button>\n ) : null}\n </>\n ) : null;\n\n const strips = doc ? (\n <>\n <ReviewStrip doc={doc} canAnswer={!!mayAnswer} canWrite={canWrite} busy={busy} onApprove={() => void approve()} onReject={reject} onRequest={() => void requestReview()} />\n <ScheduleStrip\n doc={doc}\n canPublish={canPublish}\n busy={busy}\n onAgain={() => doc.schedule && quiet(scheduleAt({ publishAt: doc.schedule.publishAt, unpublishAt: doc.schedule.unpublishAt }))}\n onUnschedule={() => quiet(unschedule())}\n />\n {release ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2.5 border-b bg-muted/50 px-4 py-2 text-[13.5px] md:px-6\">\n <Layers aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"release_in\", { name: release.name })}</span>\n {release.publishAt ? <span className=\"text-xs tabular-nums text-muted-foreground\">{formatZonedTime(release.publishAt, locale, zone)}</span> : null}\n <span className=\"flex-1\" />\n {onOpenRelease ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => onOpenRelease(release.id)}>\n {t(\"open\")}\n </Button>\n ) : null}\n </div>\n ) : null}\n </>\n ) : null;\n\n /** Select a part of the body and bring it into view (a comment was pressed). */\n const showInBody = (start: number, end: number) => {\n setMobileTab(\"edit\");\n requestAnimationFrame(() => {\n const el = bodyRef.current;\n if (!el) return;\n el.focus();\n el.setSelectionRange(start, end);\n caretRef.current = [start, end];\n const line = content.body.slice(0, start).split(\"\\n\").length - 1;\n el.scrollTop = Math.max(0, line * (parseFloat(getComputedStyle(el).lineHeight) || 24) - el.clientHeight / 3);\n });\n };\n const comments = (onClose?: () => void) =>\n doc ? (\n <CommentsPanel collection={collection} slug={doc.slug} body={content.body} canWrite={canWrite} threads={threads} onChanged={() => void loadComments(doc.slug)} getSelection={() => (caretRef.current && bodyRef.current ? [bodyRef.current.selectionStart, bodyRef.current.selectionEnd] : caretRef.current)} onGo={showInBody} onClose={onClose} />\n ) : null;\n // Drawn behind the text: what open comments are attached to, and where the others are.\n const marks = [\n ...openThreads.map((th) => placeOf(content.body, th)).filter((x): x is NonNullable<typeof x> => !!x && x.end > x.start),\n ...others\n .filter((o) => o.cursor && o.selection)\n .map((o) => {\n const a = offsetOf(content.body, o.cursor!.line, o.cursor!.ch);\n const b = offsetOf(content.body, o.selection!.line, o.selection!.ch);\n return { start: Math.min(a, b), end: Math.max(a, b), tone: \"select\" as const };\n }),\n ];\n const cursors: BodyCursor[] = others\n .filter((o) => o.cursor)\n .map((o) => ({ id: o.actorId, at: offsetOf(content.body, o.cursor!.line, o.cursor!.ch), label: o.agent ?? o.label, color: personColor(o.actorId, o.kind !== \"user\" || !!o.agent) }));\n\n const agentBanner = changes.length ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-950\">\n <Bot aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>\n {new Set(changes.map((c) => `${c.author}|${c.version}`)).size === 1\n ? t(\"agent_banner\", { who: changes[0].author, version: changes[0].version, n: changes.length, done: changes.length - pending.length, total: changes.length })\n : t(\"agent_banner_many\", { n: changes.length, done: changes.length - pending.length, total: changes.length })}\n </span>\n <span className=\"flex-1\" />\n {pending.length && canWrite ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={() => void accept(pending.map((c) => c.id))}>\n {t(\"accept_all\")}\n </Button>\n ) : null}\n </div>\n ) : null;\n\n const restoreBanner = restoreOffer ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-950\">\n <Cloud aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"restore_title\", { time: relativeTime(restoreOffer.at, t, locale), who: restoreOffer.by ?? \"\" })}</span>\n <span className=\"flex-1\" />\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => void discard()}>\n {t(\"discard\")}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={restore}>\n {t(\"restore\")}\n </Button>\n </div>\n ) : null;\n\n const blocks = changes.length ? (\n <ul aria-label={t(\"agent_changes\")} className=\"flex flex-col gap-2 border-b p-2\">\n {changes.map((ch) => {\n const r = reviewed[ch.id];\n const line = lineOf(content.body, ch);\n return (\n <li key={ch.id} className={cn(\"overflow-hidden rounded-lg border\", r ? \"border-border\" : \"border-blue-200\")}>\n <div className={cn(\"flex items-center gap-1.5 px-2 py-1 text-xs\", r ? \"bg-muted/50 text-muted-foreground\" : \"bg-blue-50 text-blue-950\")}>\n {r ? <Check aria-hidden className=\"h-3.5 w-3.5\" /> : <Bot aria-hidden className=\"h-3.5 w-3.5\" />}\n <span>{r ? t(r.action === \"accepted\" ? \"accepted_by\" : \"reverted_by\", { who: ch.author }) : ch.author}</span>\n {line !== null ? <span className=\"text-muted-foreground\">{t(\"change_at_line\", { n: line })}</span> : null}\n <span className=\"flex-1\" />\n {!r && canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-6 bg-background px-2 text-xs\" aria-label={`${t(\"revert\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => revert(ch)}>\n {t(\"revert\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-6 px-2 text-xs\" aria-label={`${t(\"accept\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => void accept([ch.id])}>\n {t(\"accept\")}\n </Button>\n </>\n ) : null}\n </div>\n {r?.action === \"accepted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.added.join(\"\\n\")}</pre>\n ) : r?.action === \"reverted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.removed.join(\"\\n\")}</pre>\n ) : (\n <div className=\"font-mono text-xs\">\n {ch.removed.map((l, i) => (\n <div key={`r${i}`} className=\"whitespace-pre-wrap bg-red-50 px-2 text-red-800 line-through decoration-red-300\">\n <span className=\"sr-only\">- </span>\n {l || \" \"}\n </div>\n ))}\n {ch.added.map((l, i) => (\n <div key={`a${i}`} className=\"whitespace-pre-wrap bg-green-50 px-2 text-green-900\">\n <span className=\"sr-only\">+ </span>\n {l || \" \"}\n </div>\n ))}\n </div>\n )}\n </li>\n );\n })}\n </ul>\n ) : null;\n\n const bodyId = \"cms-editor-body\";\n /** Put a file at the cursor: media on a line of its own, other files as a link. */\n const insertAsset = (a: Parameters<typeof assetMarkdown>[0]) => {\n const el = bodyRef.current;\n const [at, end] = caretRef.current ?? [content.body.length, content.body.length];\n const before = content.body.slice(0, at);\n const after = content.body.slice(end);\n const md = assetMarkdown(a);\n const block = md.startsWith(\"!\");\n const lead = !block || !before || before.endsWith(\"\\n\\n\") ? \"\" : before.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const tail = !block || after.startsWith(\"\\n\\n\") ? \"\" : after.startsWith(\"\\n\") || !after ? \"\\n\" : \"\\n\\n\";\n setContent({ ...content, body: `${before}${lead}${md}${tail}${after}` });\n const caret = before.length + lead.length + (block ? 2 : md.length);\n requestAnimationFrame(() => {\n el?.focus();\n // An image without alt text: leave the cursor between the brackets.\n el?.setSelectionRange(block && !a.alt ? caret : before.length + lead.length + md.length, block && !a.alt ? caret : before.length + lead.length + md.length);\n });\n };\n const bodyErr = byField.body;\n const bodyInvalid = bodyErr?.some((e) => e.severity === \"error\");\n const bodyPane = (\n <section className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-3 py-2 text-xs text-muted-foreground\">\n <FileText aria-hidden className=\"h-3.5 w-3.5\" />\n <Label htmlFor={bodyId} className=\"text-xs font-medium text-muted-foreground\">\n {t(\"field_body\")}\n </Label>\n <span className=\"flex-1\" />\n {me?.media && canWrite ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"-my-1 h-7 gap-1.5 px-2 text-xs text-foreground\" onClick={() => setPicking(true)}>\n <ImagePlus aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_insert_button\")}\n </Button>\n ) : null}\n <span>{t(\"chars\", { n: content.body.length.toLocaleString(locale) })}</span>\n </div>\n <CmsMediaPicker open={picking} onOpenChange={setPicking} onPick={insertAsset} />\n {blocks}\n <div className=\"relative flex min-h-[360px] flex-1 flex-col\">\n {marks.length || cursors.length ? <BodyBackdrop box={bodyRef} text={content.body} marks={marks} cursors={cursors} /> : null}\n <Textarea\n ref={bodyRef}\n id={bodyId}\n onSelect={(e) => (caretRef.current = [e.currentTarget.selectionStart, e.currentTarget.selectionEnd])}\n value={content.body}\n readOnly={!canWrite}\n spellCheck={false}\n aria-invalid={bodyInvalid || undefined}\n aria-describedby={bodyErr?.length ? `${bodyId}-err` : undefined}\n className=\"relative min-h-[360px] flex-1 resize-none rounded-none border-0 bg-transparent font-mono text-[13px] leading-6 shadow-none focus-visible:ring-0 dark:bg-transparent\"\n onChange={(e) => setContent({ ...content, body: e.target.value })}\n onPaste={(e) => {\n if (!canWrite) return;\n const r = pasteAsMarkdown({ html: e.clipboardData.getData(\"text/html\"), plain: e.clipboardData.getData(\"text/plain\") });\n if (!r) return; // nothing to tidy: the browser pastes as usual\n e.preventDefault();\n const el = e.currentTarget;\n const [a, b] = [el.selectionStart, el.selectionEnd];\n // insertText keeps the browser's undo history; where it is missing, set the text directly.\n if (!(typeof document.execCommand === \"function\" && document.execCommand(\"insertText\", false, r.text))) {\n setContent({ ...content, body: content.body.slice(0, a) + r.text + content.body.slice(b) });\n requestAnimationFrame(() => el.setSelectionRange(a + r.text.length, a + r.text.length));\n }\n if (r.dropped) setStatus({ text: t(\"paste_dropped\"), tone: \"muted\" });\n }}\n />\n </div>\n {bodyErr?.length ? (\n <p id={`${bodyId}-err`} className=\"border-t px-3 py-1.5 text-xs text-destructive\">\n {bodyErr.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </section>\n );\n\n const previewPane = (withHead: boolean) => (\n <section aria-label={t(\"preview\")} className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n {withHead ? (\n <div className=\"flex items-center gap-1.5 border-b px-3 py-1 text-xs text-muted-foreground\">\n <Eye aria-hidden className=\"h-3.5 w-3.5\" />\n <span className=\"font-medium\">{t(\"preview\")}</span>\n <span className=\"flex-1\" />\n <Segmented\n label={t(\"preview_width\")}\n value={width}\n onChange={setWidth}\n options={[\n { value: \"375\", label: \"375\" },\n { value: \"768\", label: \"768\" },\n { value: \"full\", label: t(\"width_full\") },\n ]}\n itemClassName=\"h-6 px-2 text-xs\"\n />\n </div>\n ) : null}\n <div className=\"flex-1 overflow-auto\">\n <MarkdownPreview title={content.title} summary={content.summary} body={content.body} className={cn(\"mx-auto px-5 py-4\", width === \"375\" ? \"max-w-[375px]\" : width === \"768\" ? \"max-w-[768px]\" : \"max-w-none\")} />\n </div>\n </section>\n );\n\n const form = (\n <CmsFieldForm schema={schema} value={content} onChange={setContent} problems={byField} slugLocked={!!doc && doc.publishedVersion !== null} slugPrefix={slugPrefix} idPrefix=\"cms-editor\" />\n );\n\n const autosaveText =\n auto.state === \"saving\" ? t(\"autosaving\") : auto.state === \"saved\" && auto.at ? t(\"autosaved_at\", { time: formatTime(auto.at, locale) }) : auto.state === \"failed\" ? t(\"autosave_failed\") : dirty ? t(\"unsaved\") : \"\";\n\n const problemsFoot = (\n <div className=\"flex flex-col\">\n <div className=\"flex flex-wrap items-center gap-3 border-t px-4 py-1.5 text-xs text-muted-foreground md:px-6\">\n {problems.length ? (\n <button type=\"button\" className=\"inline-flex items-center gap-1.5 text-destructive hover:underline\" aria-expanded={showProblems} aria-controls=\"cms-editor-problems\" onClick={() => setShowProblems((v) => !v)}>\n <CircleAlert aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_n\", { n: problems.length })}\n <ChevronDown aria-hidden className={cn(\"h-3 w-3 transition-transform\", showProblems && \"rotate-180\")} />\n </button>\n ) : (\n <span className=\"inline-flex items-center gap-1.5\">\n <CircleCheck aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_none\")}\n </span>\n )}\n <span className=\"flex-1\" />\n <span role=\"status\" className={cn(status?.tone === \"error\" && \"text-destructive\", status?.tone === \"ok\" && \"text-green-700\")}>\n {status?.text ?? \"\"}\n </span>\n <span role=\"status\" className=\"inline-flex items-center gap-1.5\">\n {autosaveText ? <Cloud aria-hidden className=\"h-3.5 w-3.5\" /> : null}\n {autosaveText}\n </span>\n </div>\n {problems.length && showProblems ? (\n <ul id=\"cms-editor-problems\" aria-label={t(\"problems_list\")} className=\"border-t px-4 py-2 text-xs md:px-6\">\n {problems.map((p, i) => (\n <li key={i} className={cn(\"py-0.5\", p.severity === \"error\" ? \"text-destructive\" : \"text-amber-700\")}>\n <span className=\"font-mono\">{p.path}</span>: {p.message}\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n\n const previewDialog = (\n <>\n {previewAllowed && doc ? <CmsPreviewLinkDialog open={previewOpen} onOpenChange={setPreviewOpen} collection={collection} slug={doc.slug} version={doc.version} /> : null}\n {doc ? (\n <AddToReleaseDialog\n open={releaseOpen}\n onOpenChange={setReleaseOpen}\n collection={collection}\n slug={doc.slug}\n published={published}\n onAdded={(r) => {\n setRelease({ id: r.id, name: r.name, state: \"open\", publishAt: null });\n setStatus({ text: t(\"release_added\", { name: r.name }), tone: \"ok\" });\n }}\n />\n ) : null}\n </>\n );\n const canRelease = !!doc && canWrite && !release;\n\n if (mobile)\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader\n title={title}\n back={\n onBack ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8\" aria-label={t(\"back\")} onClick={onBack}>\n <ChevronLeft aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : undefined\n }\n >\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"versions\")} onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null}\n <People people={others} max={2} />\n {publicUrl || previewAllowed || canRelease ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\", className: \"h-8 w-8\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {publicUrl ? <DropdownMenuItem onClick={() => window.open(publicUrl, \"_blank\", \"noopener,noreferrer\")}>{t(\"public_page\")}</DropdownMenuItem> : null}\n {previewAllowed ? <DropdownMenuItem onClick={() => setPreviewOpen(true)}>{t(\"preview_link\")}</DropdownMenuItem> : null}\n {canRelease ? <DropdownMenuItem onClick={() => setReleaseOpen(true)}>{t(\"release_add_to\")}</DropdownMenuItem> : null}\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n </PageHeader>\n {strips}\n <Tabs value={mobileTab} onValueChange={(v) => setMobileTab(String(v))} className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-4 py-2\">\n {stateBits}\n <span className=\"flex-1\" />\n <TabsList className=\"h-8\">\n <TabsTrigger value=\"edit\" className=\"h-6 text-xs\">\n {t(\"edit\")}\n </TabsTrigger>\n <TabsTrigger value=\"preview\" className=\"h-6 text-xs\">\n {t(\"preview\")}\n </TabsTrigger>\n {doc && canWrite ? (\n <TabsTrigger value=\"comments\" className=\"h-6 text-xs\">\n {openThreads.length ? t(\"comments_n\", { n: openThreads.length }) : t(\"comments\")}\n </TabsTrigger>\n ) : null}\n </TabsList>\n </div>\n <TabsContent value=\"edit\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-4 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-4 py-3\">\n <button type=\"button\" className=\"flex w-full items-center gap-2 text-left\" aria-expanded={infoOpen} aria-controls=\"cms-editor-info\" onClick={() => setInfoOpen((v) => !v)}>\n <span className=\"text-xs font-medium\">{t(\"doc_info\")}</span>\n <span className=\"truncate text-xs text-muted-foreground\">{t(\"doc_info_summary\", { n: fieldCount })}</span>\n <span className=\"flex-1\" />\n <ChevronDown aria-hidden className={cn(\"h-4 w-4 transition-transform\", infoOpen && \"rotate-180\")} />\n </button>\n <div id=\"cms-editor-info\" hidden={!infoOpen} className=\"pt-3\">\n {form}\n </div>\n </div>\n {bodyPane}\n </TabsContent>\n <TabsContent value=\"preview\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {previewPane(false)}\n </TabsContent>\n <TabsContent value=\"comments\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {comments()}\n </TabsContent>\n </Tabs>\n {problemsFoot}\n <div className=\"sticky bottom-0 z-10 flex gap-2 border-t bg-background p-2\">{saveButtons(\"flex-1\", true)}</div>\n {previewDialog}\n </div>\n );\n\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={title} crumbs={[schema.label]} after={stateBits}>\n <People people={others} className=\"mr-1\" />\n {doc && canWrite ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" aria-pressed={commentsOpen} onClick={() => setCommentsOpen((v) => !v)}>\n <MessageSquare aria-hidden className=\"h-4 w-4\" />\n {openThreads.length ? t(\"comments_n\", { n: openThreads.length }) : t(\"comments\")}\n </Button>\n ) : null}\n {publicUrl ? (\n <a href={publicUrl} target=\"_blank\" rel=\"noreferrer\" className=\"inline-flex h-9 items-center gap-1.5 px-2 text-sm underline-offset-2 hover:underline\">\n <ExternalLink aria-hidden className=\"h-4 w-4\" />\n {t(\"public_page\")}\n </a>\n ) : null}\n {previewAllowed ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => setPreviewOpen(true)}>\n <LinkIcon aria-hidden className=\"h-4 w-4\" />\n {t(\"preview_link\")}\n </Button>\n ) : null}\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n {t(\"versions\")}\n </Button>\n ) : null}\n {canRelease ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuItem onClick={() => setReleaseOpen(true)}>{t(\"release_add_to\")}</DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n {saveButtons()}\n </PageHeader>\n {strips}\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-6 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-6 py-3.5\">{form}</div>\n <div className=\"flex min-h-0 flex-1 divide-x\">\n {bodyPane}\n {previewPane(true)}\n {commentsOpen ? comments(() => setCommentsOpen(false)) : null}\n </div>\n {problemsFoot}\n {previewDialog}\n </div>\n );\n}\n\n// ── preview link ─────────────────────────────────────────────────────────────\n\nexport interface CmsPreviewLinkDialogProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n collection: string;\n slug: string;\n /** The version the link shows (the current draft). */\n version: number;\n /** Default \"24h\". */\n defaultTtl?: PreviewTtl;\n}\n\n/** Makes a signed link to the current draft; anyone with it can read it until it expires. */\nexport function CmsPreviewLinkDialog({ open, onOpenChange, collection, slug, version, defaultTtl = \"24h\" }: CmsPreviewLinkDialogProps) {\n const { client, t, locale, appUrl } = useCms();\n const [ttl, setTtl] = React.useState<PreviewTtl>(defaultTtl);\n const [comments, setComments] = React.useState(false);\n const [link, setLink] = React.useState<{ url: string; expiresAt: string; version: number } | null>(null);\n const [error, setError] = React.useState<string | null>(null);\n const [loading, setLoading] = React.useState(false);\n\n React.useEffect(() => {\n if (!open) return;\n let live = true;\n setLoading(true);\n setError(null);\n client.previewLink(collection, slug, ttl, { comments }).then(\n (l) => {\n if (!live) return;\n setLink(l);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLink(null);\n setError(errorMessage(e, t));\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [open, ttl, comments, client, collection, slug, t]);\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[500px]\">\n <DialogHeader>\n <DialogTitle>{t(\"preview_link\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"pl_current\", { version })}</DialogDescription>\n </DialogHeader>\n <div className=\"flex flex-col gap-3.5\">\n <div className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_version\")}</span>\n <span className=\"text-sm\">{t(\"pl_current\", { version: link?.version ?? version })}</span>\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <span id=\"cms-pl-ttl\" className=\"text-xs font-medium text-muted-foreground\">\n {t(\"pl_expiry\")}\n </span>\n <Segmented\n labelledBy=\"cms-pl-ttl\"\n value={ttl}\n onChange={setTtl}\n options={[\n { value: \"1h\", label: t(\"ttl_1h\") },\n { value: \"24h\", label: t(\"ttl_24h\") },\n { value: \"7d\", label: t(\"ttl_7d\") },\n ]}\n />\n </div>\n <label className=\"flex items-center gap-2 text-sm\">\n <input type=\"checkbox\" className=\"h-4 w-4 accent-primary\" checked={comments} onChange={(e) => setComments(e.target.checked)} />\n {t(\"pl_comments\")}\n </label>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_link\")}</span>\n {link ? <CodeBox value={/^\\//.test(link.url) ? `${appUrl}${link.url}` : link.url} label={t(\"pl_link\")} /> : null}\n <StatusText className=\"text-xs\" tone={error ? \"error\" : \"muted\"}>\n {error ?? (loading ? t(\"pl_making\") : link ? t(\"pl_until\", { time: formatUntil(link.expiresAt, locale) }) : \"\")}\n </StatusText>\n </div>\n </div>\n <DialogFooter>\n <Button type=\"button\" onClick={() => onOpenChange(false)}>\n {t(\"close\")}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n\nexport type { CollectionSchema };\n"
29
+ "content": "// agent-cms registry: cms-doc-editor (0.10.1). Copied into your app by `npx agent-cms add`; edit freely.\n//\n// One document: the info form (from `_schema`), the markdown body with a\n// live preview, autosave, problems from `diagnose()`, agents' changes to\n// accept or revert, save / publish (now or at a set time), review requests,\n// comments, who else has it open, preview links, and a merge screen when\n// someone saved first and the two edits overlap.\n\"use client\";\n\nimport * as React from \"react\";\nimport { Bot, Check, ChevronDown, ChevronLeft, CircleAlert, CircleCheck, Cloud, ExternalLink, FileText, History, Eye, ImagePlus, Layers, Link as LinkIcon, MessageSquare, MoreHorizontal } from \"lucide-react\";\nimport { isCmsRemoteError, type CollectionSchema, type CommentThread, type DocRelease } from \"@mainsoft/agent-cms/client\";\nimport { mergeDocs, resolveDocMerge, splitLines } from \"@mainsoft/agent-cms/diff\";\nimport { docState, type CmsDoc, type AutosaveState, type Presence } from \"@mainsoft/agent-cms/types\";\nimport { Button, buttonVariants } from \"@/components/ui/button\";\nimport { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from \"@/components/ui/dialog\";\nimport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from \"@/components/ui/dropdown-menu\";\nimport { Label } from \"@/components/ui/label\";\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from \"@/components/ui/tabs\";\nimport { Textarea } from \"@/components/ui/textarea\";\nimport { cn } from \"@/lib/utils\";\nimport { errorMessage } from \"./cms-messages\";\nimport { CmsFieldForm, problemKey, type FieldProblem } from \"./cms-field-form\";\nimport { AddToReleaseDialog, BodyBackdrop, CommentsPanel, offsetOf, placeOf, PublishButton, ReviewStrip, ScheduleStrip, type BodyCursor } from \"./cms-flow\";\nimport { assetMarkdown, CmsMediaPicker } from \"./cms-media-picker\";\nimport { pasteAsMarkdown } from \"./cms-paste\";\nimport { CmsMerge } from \"./cms-merge\";\nimport { CodeBox, MarkdownPreview, ModifiedMark, PageHeader, People, Segmented, StateBadge, StatusText } from \"./cms-parts\";\nimport { contentOf, formatTime, formatUntil, formatZoned as formatZonedTime, personColor, relativeTime, sameContent, toInput, useAsync, useCms, useDebounced, useIsMobile, type DocContent } from \"./use-cms\";\n\ntype AgentChange = Awaited<ReturnType<import(\"@mainsoft/agent-cms/client\").RestClient[\"changes\"]>>[number];\ntype PreviewTtl = NonNullable<Parameters<import(\"@mainsoft/agent-cms/client\").RestClient[\"previewLink\"]>[2]>;\ntype Diagnostic = FieldProblem & { code: string };\n\nexport interface CmsDocEditorProps {\n collection: string;\n /** The document to edit; leave out for a new document. */\n slug?: string | null;\n /** Back to the list (mobile header, after delete). */\n onBack?: () => void;\n /** A new document was created (navigate to its editor). */\n onCreated?: (collection: string, slug: string) => void;\n /** After every save or publish. */\n onSaved?: (doc: CmsDoc) => void;\n /** Open the version history. */\n onOpenVersions?: (collection: string, slug: string) => void;\n /** The public page of a published document (shown as \"Public page\" when the collection has a URL). */\n publicUrlFor?: (collection: string, slug: string) => string;\n /** Text before the slug field, e.g. \"/guide/\". */\n slugPrefix?: string;\n /** Milliseconds of quiet before an autosave. Default 1500. */\n autosaveDelay?: number;\n /** Open a release (the \"in the release ...\" strip). */\n onOpenRelease?: (id: string) => void;\n /** How often this screen says \"I am here\" and looks for other people's saves, in ms. Default 15000 (3000 while someone else is here); 0 turns it off. */\n presenceMs?: number;\n className?: string;\n}\n\nconst EMPTY: DocContent = { slug: \"\", title: \"\", summary: \"\", body: \"\", category: null, keywords: [], fields: {} };\n\n/**\n * Undo one agent change in `body`: the added lines go, the removed lines\n * come back (after the line that preceded them). Null when the change can no\n * longer be found.\n */\nexport function revertChange(body: string, ch: Pick<AgentChange, \"added\" | \"removed\" | \"before\">): string | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) {\n if (ch.added.every((l, k) => lines[i + k] === l)) {\n lines.splice(i, ch.added.length, ...ch.removed);\n return lines.join(\"\\n\");\n }\n }\n return null;\n }\n if (ch.before === null) {\n lines.splice(0, 0, ...ch.removed);\n return lines.join(\"\\n\");\n }\n const at = lines.indexOf(ch.before);\n if (at < 0) return null;\n lines.splice(at + 1, 0, ...ch.removed);\n return lines.join(\"\\n\");\n}\n\n/** 1-based line where an agent change sits in `body` (null if gone). */\nfunction lineOf(body: string, ch: AgentChange): number | null {\n const lines = splitLines(body);\n if (ch.added.length) {\n for (let i = 0; i + ch.added.length <= lines.length; i++) if (ch.added.every((l, k) => lines[i + k] === l)) return i + 1;\n return null;\n }\n if (ch.before === null) return 1;\n const at = lines.indexOf(ch.before);\n return at < 0 ? null : at + 2;\n}\n\ntype Mode = { kind: \"edit\" } | { kind: \"merge\"; base: DocContent; baseVersion: number; mine: DocContent; theirs: CmsDoc };\n\n/**\n * \"Saved v1\" for a new document has to outlive the editor that made it: most apps\n * answer `onCreated` by moving to the document's own address, which mounts a new\n * editor. The line waits in sessionStorage for that editor, for a few seconds.\n */\nconst KEPT_STATUS_MS = 15000;\nconst keptStatusKey = (collection: string, slug: string) => `agent-cms:saved:${collection}/${slug}`;\n\nfunction keepStatus(collection: string, slug: string, text: string) {\n try {\n window.sessionStorage.setItem(keptStatusKey(collection, slug), JSON.stringify({ text, at: Date.now() }));\n } catch {\n /* no storage: the line is simply not carried over */\n }\n}\n\nfunction takeStatus(collection: string, slug: string): string | null {\n try {\n const key = keptStatusKey(collection, slug);\n const raw = window.sessionStorage.getItem(key);\n if (!raw) return null;\n window.sessionStorage.removeItem(key);\n const v = JSON.parse(raw) as { text?: unknown; at?: unknown };\n return typeof v.text === \"string\" && typeof v.at === \"number\" && Date.now() - v.at < KEPT_STATUS_MS ? v.text : null;\n } catch {\n return null;\n }\n}\n\nexport function CmsDocEditor({ collection, slug, onBack, onCreated, onSaved, onOpenVersions, publicUrlFor, slugPrefix, autosaveDelay = 1500, onOpenRelease, presenceMs = 15000, className }: CmsDocEditorProps) {\n const { client, t, locale, me } = useCms();\n const bodyRef = React.useRef<HTMLTextAreaElement>(null);\n /** Where the cursor last was in the body (null: the person never put it there). */\n const caretRef = React.useRef<[number, number] | null>(null);\n const [picking, setPicking] = React.useState(false);\n const mobile = useIsMobile();\n const schemaQ = useAsync(() => client.schema(collection), [client, collection]);\n const schema = schemaQ.data;\n\n const [doc, setDoc] = React.useState<CmsDoc | null>(null);\n const [loadError, setLoadError] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(!!slug);\n const [content, setContentRaw] = React.useState<DocContent>(EMPTY);\n const [saved, setSaved] = React.useState<DocContent>(EMPTY);\n const [baseVersion, setBaseVersion] = React.useState(0);\n const [restoreOffer, setRestoreOffer] = React.useState<AutosaveState | null>(null);\n const [changes, setChanges] = React.useState<AgentChange[]>([]);\n const [reviewed, setReviewed] = React.useState<Record<string, { action: \"accepted\" | \"reverted\"; by: string }>>({});\n const [problems, setProblems] = React.useState<Diagnostic[]>([]);\n const [auto, setAuto] = React.useState<{ state: \"idle\" | \"saving\" | \"saved\" | \"failed\"; at?: string }>({ state: \"idle\" });\n const [status, setStatus] = React.useState<{ text: string; tone: \"muted\" | \"error\" | \"ok\" } | null>(null);\n const [busy, setBusy] = React.useState(false);\n const [mode, setMode] = React.useState<Mode>({ kind: \"edit\" });\n const [previewOpen, setPreviewOpen] = React.useState(false);\n const [infoOpen, setInfoOpen] = React.useState(false);\n const [mobileTab, setMobileTab] = React.useState(\"edit\");\n const [width, setWidth] = React.useState<\"375\" | \"768\" | \"full\">(\"full\");\n const [showProblems, setShowProblems] = React.useState(false);\n const edited = React.useRef(false);\n const [release, setRelease] = React.useState<DocRelease | null>(null);\n const [threads, setThreads] = React.useState<CommentThread[]>([]);\n const [commentsOpen, setCommentsOpen] = React.useState(false);\n const [releaseOpen, setReleaseOpen] = React.useState(false);\n const [others, setOthers] = React.useState<Presence[]>([]);\n\n const isNew = !slug;\n const currentSlug = doc?.slug ?? slug ?? \"\";\n const myLabel = me?.actor.label ?? \"\";\n\n const applyDoc = React.useCallback((d: CmsDoc) => {\n const c = contentOf(d);\n setDoc(d);\n setContentRaw(c);\n setSaved(c);\n setBaseVersion(d.version);\n edited.current = false;\n }, []);\n\n const loadChanges = React.useCallback(\n async (s: string) => {\n try {\n setChanges(await client.changes(collection, s));\n } catch {\n setChanges([]);\n }\n },\n [client, collection]\n );\n\n const loadComments = React.useCallback(\n async (s: string) => {\n try {\n setThreads(await client.comments(collection, s));\n } catch {\n /* readers do not see comments */\n }\n },\n [client, collection]\n );\n\n React.useEffect(() => {\n if (!slug) {\n setDoc(null);\n setContentRaw(EMPTY);\n setSaved(EMPTY);\n setLoading(false);\n return;\n }\n let live = true;\n setLoading(true);\n Promise.all([client.getWithRelease(collection, slug), client.changes(collection, slug).catch(() => [] as AgentChange[]), client.comments(collection, slug).catch(() => [] as CommentThread[])]).then(\n ([r, ch, cm]) => {\n if (!live) return;\n const d = r.doc;\n applyDoc(d);\n setRelease(r.release ?? null);\n setThreads(cm);\n setChanges(ch);\n setReviewed({});\n setRestoreOffer(d.autosave && !sameContent(d.autosave.content, d) ? d.autosave : null);\n setLoadError(null);\n setLoading(false);\n const kept = takeStatus(collection, slug);\n if (kept) setStatus({ text: kept, tone: \"ok\" });\n },\n (e) => {\n if (!live) return;\n setLoadError(e);\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [client, collection, slug, applyDoc]);\n\n // ── diagnose and autosave ──\n const diagnose = useDebounced(async (c: DocContent) => {\n try {\n const d = await client.diagnose(collection, toInput(c, doc?.fields), doc?.slug);\n setProblems(d as Diagnostic[]);\n } catch {\n /* the save will tell */\n }\n }, 400);\n\n const autosave = useDebounced(async (c: DocContent, base: number, s: string) => {\n setAuto({ state: \"saving\" });\n try {\n const a = await client.autosave(collection, s, toInput(c, doc?.fields), base);\n setAuto({ state: \"saved\", at: a.at });\n } catch {\n setAuto({ state: \"failed\" });\n }\n }, autosaveDelay);\n\n const setContent = (next: DocContent) => {\n edited.current = true;\n setContentRaw(next);\n };\n\n React.useEffect(() => {\n if (!schema?.canWrite) return;\n if (loading) return;\n void diagnose(content);\n if (edited.current && doc && !sameContent(content, saved)) autosave(content, baseVersion, doc.slug);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [content, schema?.canWrite, loading]);\n\n React.useEffect(() => () => autosave.cancel(), [autosave]);\n\n const byField = React.useMemo(() => {\n const out: Record<string, FieldProblem[]> = {};\n for (const p of problems) (out[problemKey(p.path)] ??= []).push(p);\n return out;\n }, [problems]);\n\n // ── agent changes ──\n const pending = changes.filter((c) => !reviewed[c.id]);\n const revertedIds = Object.entries(reviewed)\n .filter(([, r]) => r.action === \"reverted\")\n .map(([id]) => id);\n\n const accept = async (ids: string[]) => {\n if (!doc || !ids.length) return;\n try {\n await client.review(collection, doc.slug, ids, \"accepted\");\n setReviewed((r) => ({ ...r, ...Object.fromEntries(ids.map((id) => [id, { action: \"accepted\" as const, by: myLabel }])) }));\n } catch (e) {\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n }\n };\n\n const revert = (ch: AgentChange) => {\n const next = revertChange(content.body, ch);\n if (next === null) return;\n setContent({ ...content, body: next });\n setReviewed((r) => ({ ...r, [ch.id]: { action: \"reverted\", by: myLabel } }));\n };\n\n // ── save ──\n const dirty = !sameContent(content, saved) || revertedIds.length > 0;\n\n const save = async (publish: boolean): Promise<CmsDoc | null> => {\n setBusy(true);\n setStatus(null);\n autosave.cancel();\n try {\n let d: CmsDoc;\n if (isNew && !doc) {\n d = await client.create(collection, toInput(content), { publish });\n applyDoc(d);\n const text = publish ? t(\"published_v\", { version: d.version }) : t(\"saved\", { version: d.version });\n setStatus({ text, tone: \"ok\" });\n onSaved?.(d);\n if (onCreated) keepStatus(collection, d.slug, text);\n onCreated?.(collection, d.slug);\n return d;\n }\n if (!doc) return null;\n if (revertedIds.length) await client.review(collection, doc.slug, revertedIds, \"reverted\").catch(() => undefined);\n if (!sameContent(content, saved) || !publish) d = await client.update(collection, doc.slug, toInput(content, doc.fields), { expectedVersion: baseVersion, publish });\n else d = await client.publish(collection, doc.slug, { expectedVersion: baseVersion });\n applyDoc(d);\n setRestoreOffer(null);\n setAuto({ state: \"idle\" });\n setReviewed((r) => Object.fromEntries(Object.entries(r).filter(([, x]) => x.action === \"accepted\")));\n await loadChanges(d.slug);\n setStatus({ text: publish ? t(\"published_v\", { version: d.publishedVersion ?? d.version }) : t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n return d;\n } catch (e) {\n if (isCmsRemoteError(e) && e.code === \"conflict_version\" && doc) {\n if (!e.current) {\n setStatus({ text: t(\"merge_no_current\"), tone: \"error\" });\n return null;\n }\n try {\n const base = baseVersion === doc.version ? contentOf(doc) : (await client.version(collection, doc.slug, baseVersion)).snapshot;\n setMode({ kind: \"merge\", base, baseVersion, mine: content, theirs: e.current as CmsDoc });\n } catch (e2) {\n setStatus({ text: errorMessage(e2, t), tone: \"error\" });\n }\n return null;\n }\n if (isCmsRemoteError(e) && e.diagnostics?.length) setProblems(e.diagnostics as Diagnostic[]);\n setStatus({ text: errorMessage(e, t), tone: \"error\" });\n return null;\n } finally {\n setBusy(false);\n }\n };\n\n // ── schedule and review ──\n /** The saved document these actions apply to: unsaved edits are saved first. */\n const savedDoc = async (): Promise<CmsDoc> => {\n const d = dirty ? await save(false) : doc;\n if (!d) throw new Error(\"not saved\");\n return d;\n };\n const flow = async (fn: (d: CmsDoc) => Promise<CmsDoc>, done: (d: CmsDoc) => string, rethrow = false) => {\n setBusy(true);\n setStatus(null);\n try {\n const d = await fn(await savedDoc());\n applyDoc(d);\n setStatus({ text: done(d), tone: \"ok\" });\n onSaved?.(d);\n } catch (e) {\n if (isCmsRemoteError(e)) setStatus({ text: errorMessage(e, t), tone: \"error\" });\n if (rethrow) throw e;\n } finally {\n setBusy(false);\n }\n };\n const zone = me?.timeZone;\n const scheduleAt = (when: { publishAt: string | null; unpublishAt: string | null }) =>\n flow(\n (d) => client.schedule(collection, d.slug, { ...when, expectedVersion: d.version }),\n (d) => (d.schedule?.publishAt ? t(\"sched_done\", { version: d.schedule.version, time: formatZonedTime(d.schedule.publishAt, locale, zone) }) : t(\"sched_go\")),\n true\n );\n const unschedule = () => flow((d) => client.unschedule(collection, d.slug), () => t(\"sched_cleared\"), true);\n const requestReview = () => flow((d) => client.requestReview(collection, d.slug), () => t(\"review_requested_done\"));\n const approve = () => flow((d) => client.approveReview(collection, d.slug, { publish: true }), (d) => t(\"published_v\", { version: d.publishedVersion ?? d.version }));\n const reject = (note: string) => flow((d) => client.rejectReview(collection, d.slug, note || null), () => t(\"review_rejected_done\"), true);\n\n const restore = () => {\n if (!restoreOffer) return;\n setContent(contentOf(restoreOffer.content));\n setBaseVersion(restoreOffer.baseVersion);\n setRestoreOffer(null);\n };\n const discard = async () => {\n setRestoreOffer(null);\n if (doc) await client.discardAutosave(collection, doc.slug).catch(() => undefined);\n };\n\n // ── who else is here, and their saves ──\n const live = React.useRef({ content, saved, baseVersion, dirty, others: 0 });\n live.current = { content, saved, baseVersion, dirty, others: others.length };\n const slugNow = doc?.slug;\n React.useEffect(() => {\n if (!slugNow || !presenceMs || mode.kind !== \"edit\") return;\n let stop = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const point = (at: number) => {\n const before = live.current.content.body.slice(0, at).split(\"\\n\");\n return { line: before.length, ch: before[before.length - 1].length };\n };\n /** Someone else saved: take it when nothing is unsaved here, merge when the two edits do not overlap. */\n const catchUp = async () => {\n const latest = await client.get(collection, slugNow, { draft: true });\n const now = live.current;\n if (stop || latest.version <= now.baseVersion) return;\n const who = latest.updatedByAgent ?? latest.updatedBy ?? \"\";\n if (!now.dirty) {\n applyDoc(latest);\n void loadChanges(slugNow);\n setStatus({ text: t(\"other_saved\", { who, version: latest.version }), tone: \"muted\" });\n return;\n }\n const m = mergeDocs(now.saved, now.content, contentOf(latest));\n if (m.body.conflicts.length || m.fieldConflicts.length) return; // saving opens the merge screen\n autosave.cancel();\n const merged = contentOf(resolveDocMerge(m, {}));\n // Keep the cursor where it was: text that arrived above it pushes it down.\n const el = bodyRef.current;\n const sel = caretRef.current;\n let same = 0;\n while (same < merged.body.length && merged.body[same] === now.content.body[same]) same++;\n const shift = (at: number) => (at <= same ? at : Math.max(same, at + merged.body.length - now.content.body.length));\n setDoc(latest);\n setSaved(contentOf(latest));\n setBaseVersion(latest.version);\n setContentRaw(merged);\n if (el && sel && document.activeElement === el)\n requestAnimationFrame(() => {\n el.setSelectionRange(shift(sel[0]), shift(sel[1]));\n caretRef.current = [shift(sel[0]), shift(sel[1])];\n });\n setStatus({ text: t(\"other_merged\", { who, version: latest.version }), tone: \"muted\" });\n };\n const beat = async () => {\n try {\n if (document.visibilityState !== \"hidden\") {\n const sel = caretRef.current;\n const r = await client.presence(collection, slugNow, { cursor: sel ? point(sel[1]) : null, selection: sel && sel[0] !== sel[1] ? point(sel[0]) : null });\n if (stop) return;\n setOthers(r.others);\n if (r.version > live.current.baseVersion) await catchUp();\n }\n } catch {\n /* a reader, or offline: nobody is shown */\n }\n if (!stop) timer = setTimeout(() => void beat(), live.current.others ? Math.min(presenceMs, 3000) : presenceMs);\n };\n void beat();\n return () => {\n stop = true;\n if (timer) clearTimeout(timer);\n setOthers([]);\n void client.leave(collection, slugNow).catch(() => undefined);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, collection, slugNow, presenceMs, mode.kind]);\n\n // ── render ──\n if (mode.kind === \"merge\" && doc)\n return (\n <CmsMerge\n collection={collection}\n slug={doc.slug}\n base={mode.base}\n baseVersion={mode.baseVersion}\n mine={mode.mine}\n theirs={mode.theirs}\n crumbs={[schema?.label ?? collection, content.title || doc.slug]}\n className={className}\n onCancel={() => setMode({ kind: \"edit\" })}\n onSaved={(d) => {\n setMode({ kind: \"edit\" });\n setReviewed({});\n applyDoc(d);\n void loadChanges(d.slug);\n setStatus({ text: t(\"saved\", { version: d.version }), tone: \"ok\" });\n onSaved?.(d);\n }}\n />\n );\n\n if (loadError)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText tone=\"error\">{errorMessage(loadError, t)}</StatusText>\n </div>\n );\n if (loading || !schema)\n return (\n <div className={cn(\"p-6\", className)}>\n <StatusText>{t(\"loading\")}</StatusText>\n </div>\n );\n\n const st = doc ? docState(doc) : null;\n const canWrite = schema.canWrite;\n const canPublish = schema.canPublish;\n const published = !!doc && doc.publishedVersion !== null && doc.status !== \"archived\";\n const publicUrl = published && schema.hasUrl && publicUrlFor && doc ? publicUrlFor(collection, doc.slug) : null;\n const previewAllowed = !!doc && !!me?.previewLinks && schema.hasUrl;\n const title = content.title || (isNew ? t(\"new_doc_title\") : currentSlug);\n const fieldCount = Object.keys(((schema.fields ?? {}) as { properties?: object }).properties ?? {}).length;\n\n const stateBits = st ? (\n <>\n <StateBadge state={doc?.review ? (doc.review.state === \"requested\" ? \"review\" : \"changes\") : st.state} />\n {doc?.schedule?.publishAt ? <StateBadge state=\"scheduled\" /> : null}\n {st.modifiedSincePublish ? <ModifiedMark /> : null}\n </>\n ) : null;\n const mustReview = !!schema.needsReview;\n const openThreads = threads.filter((x) => !x.resolvedAt);\n /** Answering a request is for people who may publish, and never for the one who asked when everyone needs a review. */\n const mayAnswer = canPublish && me?.actor.kind === \"user\" && !(schema.review?.everyone === \"required\" && doc?.review?.byKind === \"user\" && !doc.review.byAgent && doc.review.byId === me.actor.id);\n const quiet = (p: Promise<unknown>) => void p.catch(() => undefined);\n\n const saveButtons = (cls?: string, up?: boolean) =>\n canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" className={cls} disabled={busy || (!dirty && !isNew)} onClick={() => void save(false)}>\n {t(\"save\")}\n </Button>\n {canPublish && !mustReview ? (\n <PublishButton\n className={cls}\n up={up}\n busy={busy}\n disabled={!dirty && !!st && st.state === \"published\" && !st.modifiedSincePublish}\n canSchedule={!!doc}\n schedule={doc?.schedule ?? null}\n onPublish={() => void save(true)}\n onSchedule={scheduleAt}\n onUnschedule={unschedule}\n />\n ) : doc && doc.review?.state !== \"requested\" ? (\n <Button type=\"button\" className={cls} disabled={busy} title={mustReview ? t(\"review_needed\") : undefined} onClick={() => void requestReview()}>\n {t(\"review_request\")}\n </Button>\n ) : null}\n </>\n ) : null;\n\n const strips = doc ? (\n <>\n <ReviewStrip doc={doc} canAnswer={!!mayAnswer} canWrite={canWrite} busy={busy} onApprove={() => void approve()} onReject={reject} onRequest={() => void requestReview()} />\n <ScheduleStrip\n doc={doc}\n canPublish={canPublish}\n busy={busy}\n onAgain={() => doc.schedule && quiet(scheduleAt({ publishAt: doc.schedule.publishAt, unpublishAt: doc.schedule.unpublishAt }))}\n onUnschedule={() => quiet(unschedule())}\n />\n {release ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2.5 border-b bg-muted/50 px-4 py-2 text-[13.5px] md:px-6\">\n <Layers aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"release_in\", { name: release.name })}</span>\n {release.publishAt ? <span className=\"text-xs tabular-nums text-muted-foreground\">{formatZonedTime(release.publishAt, locale, zone)}</span> : null}\n <span className=\"flex-1\" />\n {onOpenRelease ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => onOpenRelease(release.id)}>\n {t(\"open\")}\n </Button>\n ) : null}\n </div>\n ) : null}\n </>\n ) : null;\n\n /** Select a part of the body and bring it into view (a comment was pressed). */\n const showInBody = (start: number, end: number) => {\n setMobileTab(\"edit\");\n requestAnimationFrame(() => {\n const el = bodyRef.current;\n if (!el) return;\n el.focus();\n el.setSelectionRange(start, end);\n caretRef.current = [start, end];\n const line = content.body.slice(0, start).split(\"\\n\").length - 1;\n el.scrollTop = Math.max(0, line * (parseFloat(getComputedStyle(el).lineHeight) || 24) - el.clientHeight / 3);\n });\n };\n const comments = (onClose?: () => void) =>\n doc ? (\n <CommentsPanel collection={collection} slug={doc.slug} body={content.body} canWrite={canWrite} threads={threads} onChanged={() => void loadComments(doc.slug)} getSelection={() => (caretRef.current && bodyRef.current ? [bodyRef.current.selectionStart, bodyRef.current.selectionEnd] : caretRef.current)} onGo={showInBody} onClose={onClose} />\n ) : null;\n // Drawn behind the text: what open comments are attached to, and where the others are.\n const marks = [\n ...openThreads.map((th) => placeOf(content.body, th)).filter((x): x is NonNullable<typeof x> => !!x && x.end > x.start),\n ...others\n .filter((o) => o.cursor && o.selection)\n .map((o) => {\n const a = offsetOf(content.body, o.cursor!.line, o.cursor!.ch);\n const b = offsetOf(content.body, o.selection!.line, o.selection!.ch);\n return { start: Math.min(a, b), end: Math.max(a, b), tone: \"select\" as const };\n }),\n ];\n const cursors: BodyCursor[] = others\n .filter((o) => o.cursor)\n .map((o) => ({ id: o.actorId, at: offsetOf(content.body, o.cursor!.line, o.cursor!.ch), label: o.agent ?? o.label, color: personColor(o.actorId, o.kind !== \"user\" || !!o.agent) }));\n\n const agentBanner = changes.length ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-blue-200 bg-blue-50 px-3 py-2 text-sm text-blue-950\">\n <Bot aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>\n {new Set(changes.map((c) => `${c.author}|${c.version}`)).size === 1\n ? t(\"agent_banner\", { who: changes[0].author, version: changes[0].version, n: changes.length, done: changes.length - pending.length, total: changes.length })\n : t(\"agent_banner_many\", { n: changes.length, done: changes.length - pending.length, total: changes.length })}\n </span>\n <span className=\"flex-1\" />\n {pending.length && canWrite ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={() => void accept(pending.map((c) => c.id))}>\n {t(\"accept_all\")}\n </Button>\n ) : null}\n </div>\n ) : null;\n\n const restoreBanner = restoreOffer ? (\n <div role=\"status\" className=\"flex flex-wrap items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-950\">\n <Cloud aria-hidden className=\"h-4 w-4 shrink-0\" />\n <span>{t(\"restore_title\", { time: relativeTime(restoreOffer.at, t, locale), who: restoreOffer.by ?? \"\" })}</span>\n <span className=\"flex-1\" />\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-7\" onClick={() => void discard()}>\n {t(\"discard\")}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-7 bg-background\" onClick={restore}>\n {t(\"restore\")}\n </Button>\n </div>\n ) : null;\n\n const blocks = changes.length ? (\n <ul aria-label={t(\"agent_changes\")} className=\"flex flex-col gap-2 border-b p-2\">\n {changes.map((ch) => {\n const r = reviewed[ch.id];\n const line = lineOf(content.body, ch);\n return (\n <li key={ch.id} className={cn(\"overflow-hidden rounded-lg border\", r ? \"border-border\" : \"border-blue-200\")}>\n <div className={cn(\"flex items-center gap-1.5 px-2 py-1 text-xs\", r ? \"bg-muted/50 text-muted-foreground\" : \"bg-blue-50 text-blue-950\")}>\n {r ? <Check aria-hidden className=\"h-3.5 w-3.5\" /> : <Bot aria-hidden className=\"h-3.5 w-3.5\" />}\n <span>{r ? t(r.action === \"accepted\" ? \"accepted_by\" : \"reverted_by\", { who: ch.author }) : ch.author}</span>\n {line !== null ? <span className=\"text-muted-foreground\">{t(\"change_at_line\", { n: line })}</span> : null}\n <span className=\"flex-1\" />\n {!r && canWrite ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"h-6 bg-background px-2 text-xs\" aria-label={`${t(\"revert\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => revert(ch)}>\n {t(\"revert\")}\n </Button>\n <Button type=\"button\" size=\"sm\" className=\"h-6 px-2 text-xs\" aria-label={`${t(\"accept\")}: ${t(\"change_at_line\", { n: line ?? \"?\" })}`} onClick={() => void accept([ch.id])}>\n {t(\"accept\")}\n </Button>\n </>\n ) : null}\n </div>\n {r?.action === \"accepted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.added.join(\"\\n\")}</pre>\n ) : r?.action === \"reverted\" ? (\n <pre className=\"whitespace-pre-wrap px-2 py-1 font-mono text-xs\">{ch.removed.join(\"\\n\")}</pre>\n ) : (\n <div className=\"font-mono text-xs\">\n {ch.removed.map((l, i) => (\n <div key={`r${i}`} className=\"whitespace-pre-wrap bg-red-50 px-2 text-red-800 line-through decoration-red-300\">\n <span className=\"sr-only\">- </span>\n {l || \" \"}\n </div>\n ))}\n {ch.added.map((l, i) => (\n <div key={`a${i}`} className=\"whitespace-pre-wrap bg-green-50 px-2 text-green-900\">\n <span className=\"sr-only\">+ </span>\n {l || \" \"}\n </div>\n ))}\n </div>\n )}\n </li>\n );\n })}\n </ul>\n ) : null;\n\n const bodyId = \"cms-editor-body\";\n /** Put a file at the cursor: media on a line of its own, other files as a link. */\n const insertAsset = (a: Parameters<typeof assetMarkdown>[0]) => {\n const el = bodyRef.current;\n const [at, end] = caretRef.current ?? [content.body.length, content.body.length];\n const before = content.body.slice(0, at);\n const after = content.body.slice(end);\n const md = assetMarkdown(a);\n const block = md.startsWith(\"!\");\n const lead = !block || !before || before.endsWith(\"\\n\\n\") ? \"\" : before.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const tail = !block || after.startsWith(\"\\n\\n\") ? \"\" : after.startsWith(\"\\n\") || !after ? \"\\n\" : \"\\n\\n\";\n setContent({ ...content, body: `${before}${lead}${md}${tail}${after}` });\n const caret = before.length + lead.length + (block ? 2 : md.length);\n requestAnimationFrame(() => {\n el?.focus();\n // An image without alt text: leave the cursor between the brackets.\n el?.setSelectionRange(block && !a.alt ? caret : before.length + lead.length + md.length, block && !a.alt ? caret : before.length + lead.length + md.length);\n });\n };\n const bodyErr = byField.body;\n const bodyInvalid = bodyErr?.some((e) => e.severity === \"error\");\n const bodyPane = (\n <section className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-3 py-2 text-xs text-muted-foreground\">\n <FileText aria-hidden className=\"h-3.5 w-3.5\" />\n <Label htmlFor={bodyId} className=\"text-xs font-medium text-muted-foreground\">\n {t(\"field_body\")}\n </Label>\n <span className=\"flex-1\" />\n {me?.media && canWrite ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"-my-1 h-7 gap-1.5 px-2 text-xs text-foreground\" onClick={() => setPicking(true)}>\n <ImagePlus aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"media_insert_button\")}\n </Button>\n ) : null}\n <span>{t(\"chars\", { n: content.body.length.toLocaleString(locale) })}</span>\n </div>\n <CmsMediaPicker open={picking} onOpenChange={setPicking} onPick={insertAsset} />\n {blocks}\n <div className=\"relative flex min-h-[360px] flex-1 flex-col\">\n {marks.length || cursors.length ? <BodyBackdrop box={bodyRef} text={content.body} marks={marks} cursors={cursors} /> : null}\n <Textarea\n ref={bodyRef}\n id={bodyId}\n onSelect={(e) => (caretRef.current = [e.currentTarget.selectionStart, e.currentTarget.selectionEnd])}\n value={content.body}\n readOnly={!canWrite}\n spellCheck={false}\n aria-invalid={bodyInvalid || undefined}\n aria-describedby={bodyErr?.length ? `${bodyId}-err` : undefined}\n className=\"relative min-h-[360px] flex-1 resize-none rounded-none border-0 bg-transparent font-mono text-[13px] leading-6 shadow-none focus-visible:ring-0 dark:bg-transparent\"\n onChange={(e) => setContent({ ...content, body: e.target.value })}\n onPaste={(e) => {\n if (!canWrite) return;\n const r = pasteAsMarkdown({ html: e.clipboardData.getData(\"text/html\"), plain: e.clipboardData.getData(\"text/plain\") });\n if (!r) return; // nothing to tidy: the browser pastes as usual\n e.preventDefault();\n const el = e.currentTarget;\n const [a, b] = [el.selectionStart, el.selectionEnd];\n // insertText keeps the browser's undo history; where it is missing, set the text directly.\n if (!(typeof document.execCommand === \"function\" && document.execCommand(\"insertText\", false, r.text))) {\n setContent({ ...content, body: content.body.slice(0, a) + r.text + content.body.slice(b) });\n requestAnimationFrame(() => el.setSelectionRange(a + r.text.length, a + r.text.length));\n }\n if (r.dropped) setStatus({ text: t(\"paste_dropped\"), tone: \"muted\" });\n }}\n />\n </div>\n {bodyErr?.length ? (\n <p id={`${bodyId}-err`} className=\"border-t px-3 py-1.5 text-xs text-destructive\">\n {bodyErr.map((e) => e.message).join(\" \")}\n </p>\n ) : null}\n </section>\n );\n\n const previewPane = (withHead: boolean) => (\n <section aria-label={t(\"preview\")} className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n {withHead ? (\n <div className=\"flex items-center gap-1.5 border-b px-3 py-1 text-xs text-muted-foreground\">\n <Eye aria-hidden className=\"h-3.5 w-3.5\" />\n <span className=\"font-medium\">{t(\"preview\")}</span>\n <span className=\"flex-1\" />\n <Segmented\n label={t(\"preview_width\")}\n value={width}\n onChange={setWidth}\n options={[\n { value: \"375\", label: \"375\" },\n { value: \"768\", label: \"768\" },\n { value: \"full\", label: t(\"width_full\") },\n ]}\n itemClassName=\"h-6 px-2 text-xs\"\n />\n </div>\n ) : null}\n <div className=\"flex-1 overflow-auto\">\n <MarkdownPreview title={content.title} summary={content.summary} body={content.body} className={cn(\"mx-auto px-5 py-4\", width === \"375\" ? \"max-w-[375px]\" : width === \"768\" ? \"max-w-[768px]\" : \"max-w-none\")} />\n </div>\n </section>\n );\n\n const form = (\n <CmsFieldForm schema={schema} value={content} onChange={setContent} problems={byField} slugLocked={!!doc && doc.publishedVersion !== null} slugPrefix={slugPrefix} idPrefix=\"cms-editor\" />\n );\n\n const autosaveText =\n auto.state === \"saving\" ? t(\"autosaving\") : auto.state === \"saved\" && auto.at ? t(\"autosaved_at\", { time: formatTime(auto.at, locale) }) : auto.state === \"failed\" ? t(\"autosave_failed\") : dirty ? t(\"unsaved\") : \"\";\n\n const problemsFoot = (\n <div className=\"flex flex-col\">\n <div className=\"flex flex-wrap items-center gap-3 border-t px-4 py-1.5 text-xs text-muted-foreground md:px-6\">\n {problems.length ? (\n <button type=\"button\" className=\"inline-flex items-center gap-1.5 text-destructive hover:underline\" aria-expanded={showProblems} aria-controls=\"cms-editor-problems\" onClick={() => setShowProblems((v) => !v)}>\n <CircleAlert aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_n\", { n: problems.length })}\n <ChevronDown aria-hidden className={cn(\"h-3 w-3 transition-transform\", showProblems && \"rotate-180\")} />\n </button>\n ) : (\n <span className=\"inline-flex items-center gap-1.5\">\n <CircleCheck aria-hidden className=\"h-3.5 w-3.5\" />\n {t(\"problems_none\")}\n </span>\n )}\n <span className=\"flex-1\" />\n <span role=\"status\" className={cn(status?.tone === \"error\" && \"text-destructive\", status?.tone === \"ok\" && \"text-green-700\")}>\n {status?.text ?? \"\"}\n </span>\n <span role=\"status\" className=\"inline-flex items-center gap-1.5\">\n {autosaveText ? <Cloud aria-hidden className=\"h-3.5 w-3.5\" /> : null}\n {autosaveText}\n </span>\n </div>\n {problems.length && showProblems ? (\n <ul id=\"cms-editor-problems\" aria-label={t(\"problems_list\")} className=\"border-t px-4 py-2 text-xs md:px-6\">\n {problems.map((p, i) => (\n <li key={i} className={cn(\"py-0.5\", p.severity === \"error\" ? \"text-destructive\" : \"text-amber-700\")}>\n <span className=\"font-mono\">{p.path}</span>: {p.message}\n </li>\n ))}\n </ul>\n ) : null}\n </div>\n );\n\n const previewDialog = (\n <>\n {previewAllowed && doc ? <CmsPreviewLinkDialog open={previewOpen} onOpenChange={setPreviewOpen} collection={collection} slug={doc.slug} version={doc.version} /> : null}\n {doc ? (\n <AddToReleaseDialog\n open={releaseOpen}\n onOpenChange={setReleaseOpen}\n collection={collection}\n slug={doc.slug}\n published={published}\n onAdded={(r) => {\n setRelease({ id: r.id, name: r.name, state: \"open\", publishAt: null });\n setStatus({ text: t(\"release_added\", { name: r.name }), tone: \"ok\" });\n }}\n />\n ) : null}\n </>\n );\n const canRelease = !!doc && canWrite && !release;\n\n if (mobile)\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader\n title={title}\n back={\n onBack ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"-ml-2 h-8 w-8\" aria-label={t(\"back\")} onClick={onBack}>\n <ChevronLeft aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : undefined\n }\n >\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" size=\"icon\" className=\"h-8 w-8\" aria-label={t(\"versions\")} onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n </Button>\n ) : null}\n <People people={others} max={2} />\n {publicUrl || previewAllowed || canRelease ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\", className: \"h-8 w-8\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {publicUrl ? <DropdownMenuItem onClick={() => window.open(publicUrl, \"_blank\", \"noopener,noreferrer\")}>{t(\"public_page\")}</DropdownMenuItem> : null}\n {previewAllowed ? <DropdownMenuItem onClick={() => setPreviewOpen(true)}>{t(\"preview_link\")}</DropdownMenuItem> : null}\n {canRelease ? <DropdownMenuItem onClick={() => setReleaseOpen(true)}>{t(\"release_add_to\")}</DropdownMenuItem> : null}\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n </PageHeader>\n {strips}\n <Tabs value={mobileTab} onValueChange={(v) => setMobileTab(String(v))} className=\"flex min-h-0 flex-1 flex-col\">\n <div className=\"flex items-center gap-1.5 border-b px-4 py-2\">\n {stateBits}\n <span className=\"flex-1\" />\n <TabsList className=\"h-8\">\n <TabsTrigger value=\"edit\" className=\"h-6 text-xs\">\n {t(\"edit\")}\n </TabsTrigger>\n <TabsTrigger value=\"preview\" className=\"h-6 text-xs\">\n {t(\"preview\")}\n </TabsTrigger>\n {doc && canWrite ? (\n <TabsTrigger value=\"comments\" className=\"h-6 text-xs\">\n {openThreads.length ? t(\"comments_n\", { n: openThreads.length }) : t(\"comments\")}\n </TabsTrigger>\n ) : null}\n </TabsList>\n </div>\n <TabsContent value=\"edit\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-4 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-4 py-3\">\n <button type=\"button\" className=\"flex w-full items-center gap-2 text-left\" aria-expanded={infoOpen} aria-controls=\"cms-editor-info\" onClick={() => setInfoOpen((v) => !v)}>\n <span className=\"text-xs font-medium\">{t(\"doc_info\")}</span>\n <span className=\"truncate text-xs text-muted-foreground\">{t(\"doc_info_summary\", { n: fieldCount })}</span>\n <span className=\"flex-1\" />\n <ChevronDown aria-hidden className={cn(\"h-4 w-4 transition-transform\", infoOpen && \"rotate-180\")} />\n </button>\n <div id=\"cms-editor-info\" hidden={!infoOpen} className=\"pt-3\">\n {form}\n </div>\n </div>\n {bodyPane}\n </TabsContent>\n <TabsContent value=\"preview\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {previewPane(false)}\n </TabsContent>\n <TabsContent value=\"comments\" className=\"mt-0 flex min-h-0 flex-1 flex-col\">\n {comments()}\n </TabsContent>\n </Tabs>\n {problemsFoot}\n <div className=\"sticky bottom-0 z-10 flex gap-2 border-t bg-background p-2\">{saveButtons(\"flex-1\", true)}</div>\n {previewDialog}\n </div>\n );\n\n return (\n <div className={cn(\"flex min-h-0 flex-1 flex-col\", className)}>\n <PageHeader title={title} crumbs={[schema.label]} after={stateBits}>\n <People people={others} className=\"mr-1\" />\n {doc && canWrite ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" aria-pressed={commentsOpen} onClick={() => setCommentsOpen((v) => !v)}>\n <MessageSquare aria-hidden className=\"h-4 w-4\" />\n {openThreads.length ? t(\"comments_n\", { n: openThreads.length }) : t(\"comments\")}\n </Button>\n ) : null}\n {publicUrl ? (\n <a href={publicUrl} target=\"_blank\" rel=\"noreferrer\" className=\"inline-flex h-9 items-center gap-1.5 px-2 text-sm underline-offset-2 hover:underline\">\n <ExternalLink aria-hidden className=\"h-4 w-4\" />\n {t(\"public_page\")}\n </a>\n ) : null}\n {previewAllowed ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => setPreviewOpen(true)}>\n <LinkIcon aria-hidden className=\"h-4 w-4\" />\n {t(\"preview_link\")}\n </Button>\n ) : null}\n {doc && onOpenVersions ? (\n <Button type=\"button\" variant=\"ghost\" className=\"gap-1.5\" onClick={() => onOpenVersions(collection, doc.slug)}>\n <History aria-hidden className=\"h-4 w-4\" />\n {t(\"versions\")}\n </Button>\n ) : null}\n {canRelease ? (\n <DropdownMenu>\n <DropdownMenuTrigger className={buttonVariants({ variant: \"ghost\", size: \"icon\" })} aria-label={t(\"more\")}>\n <MoreHorizontal aria-hidden className=\"h-4 w-4\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuItem onClick={() => setReleaseOpen(true)}>{t(\"release_add_to\")}</DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n {saveButtons()}\n </PageHeader>\n {strips}\n {agentBanner || restoreBanner ? (\n <div className=\"flex flex-col gap-2 px-6 pt-2.5\">\n {restoreBanner}\n {agentBanner}\n </div>\n ) : null}\n <div className=\"border-b px-6 py-3.5\">{form}</div>\n <div className=\"flex min-h-0 flex-1 divide-x\">\n {bodyPane}\n {previewPane(true)}\n {commentsOpen ? comments(() => setCommentsOpen(false)) : null}\n </div>\n {problemsFoot}\n {previewDialog}\n </div>\n );\n}\n\n// ── preview link ─────────────────────────────────────────────────────────────\n\nexport interface CmsPreviewLinkDialogProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n collection: string;\n slug: string;\n /** The version the link shows (the current draft). */\n version: number;\n /** Default \"24h\". */\n defaultTtl?: PreviewTtl;\n}\n\n/** Makes a signed link to the current draft; anyone with it can read it until it expires. */\nexport function CmsPreviewLinkDialog({ open, onOpenChange, collection, slug, version, defaultTtl = \"24h\" }: CmsPreviewLinkDialogProps) {\n const { client, t, locale, appUrl } = useCms();\n const [ttl, setTtl] = React.useState<PreviewTtl>(defaultTtl);\n const [comments, setComments] = React.useState(false);\n const [link, setLink] = React.useState<{ url: string; expiresAt: string; version: number } | null>(null);\n const [error, setError] = React.useState<string | null>(null);\n const [loading, setLoading] = React.useState(false);\n\n React.useEffect(() => {\n if (!open) return;\n let live = true;\n setLoading(true);\n setError(null);\n client.previewLink(collection, slug, ttl, { comments }).then(\n (l) => {\n if (!live) return;\n setLink(l);\n setLoading(false);\n },\n (e) => {\n if (!live) return;\n setLink(null);\n setError(errorMessage(e, t));\n setLoading(false);\n }\n );\n return () => {\n live = false;\n };\n }, [open, ttl, comments, client, collection, slug, t]);\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-[500px]\">\n <DialogHeader>\n <DialogTitle>{t(\"preview_link\")}</DialogTitle>\n <DialogDescription className=\"sr-only\">{t(\"pl_current\", { version })}</DialogDescription>\n </DialogHeader>\n <div className=\"flex flex-col gap-3.5\">\n <div className=\"flex flex-col gap-1\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_version\")}</span>\n <span className=\"text-sm\">{t(\"pl_current\", { version: link?.version ?? version })}</span>\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <span id=\"cms-pl-ttl\" className=\"text-xs font-medium text-muted-foreground\">\n {t(\"pl_expiry\")}\n </span>\n <Segmented\n labelledBy=\"cms-pl-ttl\"\n value={ttl}\n onChange={setTtl}\n options={[\n { value: \"1h\", label: t(\"ttl_1h\") },\n { value: \"24h\", label: t(\"ttl_24h\") },\n { value: \"7d\", label: t(\"ttl_7d\") },\n ]}\n />\n </div>\n <label className=\"flex items-center gap-2 text-sm\">\n <input type=\"checkbox\" className=\"h-4 w-4 accent-primary\" checked={comments} onChange={(e) => setComments(e.target.checked)} />\n {t(\"pl_comments\")}\n </label>\n <div className=\"flex flex-col gap-1.5\">\n <span className=\"text-xs font-medium text-muted-foreground\">{t(\"pl_link\")}</span>\n {link ? <CodeBox value={/^\\//.test(link.url) ? `${appUrl}${link.url}` : link.url} label={t(\"pl_link\")} /> : null}\n <StatusText className=\"text-xs\" tone={error ? \"error\" : \"muted\"}>\n {error ?? (loading ? t(\"pl_making\") : link ? t(\"pl_until\", { time: formatUntil(link.expiresAt, locale) }) : \"\")}\n </StatusText>\n </div>\n </div>\n <DialogFooter>\n <Button type=\"button\" onClick={() => onOpenChange(false)}>\n {t(\"close\")}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n\nexport type { CollectionSchema };\n"
30
30
  },
31
31
  {
32
32
  "path": "registry/cms/cms-field-form.tsx",
package/dist/tables.d.cts CHANGED
@@ -887,7 +887,7 @@ declare function cmsTables(o?: CmsTablesOptions): {
887
887
  tableName: string;
888
888
  dataType: "json";
889
889
  columnType: "PgJsonb";
890
- data: ("read" | "write" | "publish" | "admin")[];
890
+ data: ("write" | "publish" | "read" | "admin")[];
891
891
  driverParam: unknown;
892
892
  notNull: true;
893
893
  hasDefault: false;
@@ -899,7 +899,7 @@ declare function cmsTables(o?: CmsTablesOptions): {
899
899
  identity: undefined;
900
900
  generated: undefined;
901
901
  }, {}, {
902
- $type: ("read" | "write" | "publish" | "admin")[];
902
+ $type: ("write" | "publish" | "read" | "admin")[];
903
903
  }>;
904
904
  collections: drizzle_orm_pg_core.PgColumn<{
905
905
  name: "collections";
@@ -3473,7 +3473,7 @@ declare const defaultTables: {
3473
3473
  tableName: string;
3474
3474
  dataType: "json";
3475
3475
  columnType: "PgJsonb";
3476
- data: ("read" | "write" | "publish" | "admin")[];
3476
+ data: ("write" | "publish" | "read" | "admin")[];
3477
3477
  driverParam: unknown;
3478
3478
  notNull: true;
3479
3479
  hasDefault: false;
@@ -3485,7 +3485,7 @@ declare const defaultTables: {
3485
3485
  identity: undefined;
3486
3486
  generated: undefined;
3487
3487
  }, {}, {
3488
- $type: ("read" | "write" | "publish" | "admin")[];
3488
+ $type: ("write" | "publish" | "read" | "admin")[];
3489
3489
  }>;
3490
3490
  collections: drizzle_orm_pg_core.PgColumn<{
3491
3491
  name: "collections";
@@ -6056,7 +6056,7 @@ declare const cmsApiKeys: drizzle_orm_pg_core.PgTableWithColumns<{
6056
6056
  tableName: string;
6057
6057
  dataType: "json";
6058
6058
  columnType: "PgJsonb";
6059
- data: ("read" | "write" | "publish" | "admin")[];
6059
+ data: ("write" | "publish" | "read" | "admin")[];
6060
6060
  driverParam: unknown;
6061
6061
  notNull: true;
6062
6062
  hasDefault: false;
@@ -6068,7 +6068,7 @@ declare const cmsApiKeys: drizzle_orm_pg_core.PgTableWithColumns<{
6068
6068
  identity: undefined;
6069
6069
  generated: undefined;
6070
6070
  }, {}, {
6071
- $type: ("read" | "write" | "publish" | "admin")[];
6071
+ $type: ("write" | "publish" | "read" | "admin")[];
6072
6072
  }>;
6073
6073
  collections: drizzle_orm_pg_core.PgColumn<{
6074
6074
  name: "collections";
package/dist/tables.d.ts CHANGED
@@ -887,7 +887,7 @@ declare function cmsTables(o?: CmsTablesOptions): {
887
887
  tableName: string;
888
888
  dataType: "json";
889
889
  columnType: "PgJsonb";
890
- data: ("read" | "write" | "publish" | "admin")[];
890
+ data: ("write" | "publish" | "read" | "admin")[];
891
891
  driverParam: unknown;
892
892
  notNull: true;
893
893
  hasDefault: false;
@@ -899,7 +899,7 @@ declare function cmsTables(o?: CmsTablesOptions): {
899
899
  identity: undefined;
900
900
  generated: undefined;
901
901
  }, {}, {
902
- $type: ("read" | "write" | "publish" | "admin")[];
902
+ $type: ("write" | "publish" | "read" | "admin")[];
903
903
  }>;
904
904
  collections: drizzle_orm_pg_core.PgColumn<{
905
905
  name: "collections";
@@ -3473,7 +3473,7 @@ declare const defaultTables: {
3473
3473
  tableName: string;
3474
3474
  dataType: "json";
3475
3475
  columnType: "PgJsonb";
3476
- data: ("read" | "write" | "publish" | "admin")[];
3476
+ data: ("write" | "publish" | "read" | "admin")[];
3477
3477
  driverParam: unknown;
3478
3478
  notNull: true;
3479
3479
  hasDefault: false;
@@ -3485,7 +3485,7 @@ declare const defaultTables: {
3485
3485
  identity: undefined;
3486
3486
  generated: undefined;
3487
3487
  }, {}, {
3488
- $type: ("read" | "write" | "publish" | "admin")[];
3488
+ $type: ("write" | "publish" | "read" | "admin")[];
3489
3489
  }>;
3490
3490
  collections: drizzle_orm_pg_core.PgColumn<{
3491
3491
  name: "collections";
@@ -6056,7 +6056,7 @@ declare const cmsApiKeys: drizzle_orm_pg_core.PgTableWithColumns<{
6056
6056
  tableName: string;
6057
6057
  dataType: "json";
6058
6058
  columnType: "PgJsonb";
6059
- data: ("read" | "write" | "publish" | "admin")[];
6059
+ data: ("write" | "publish" | "read" | "admin")[];
6060
6060
  driverParam: unknown;
6061
6061
  notNull: true;
6062
6062
  hasDefault: false;
@@ -6068,7 +6068,7 @@ declare const cmsApiKeys: drizzle_orm_pg_core.PgTableWithColumns<{
6068
6068
  identity: undefined;
6069
6069
  generated: undefined;
6070
6070
  }, {}, {
6071
- $type: ("read" | "write" | "publish" | "admin")[];
6071
+ $type: ("write" | "publish" | "read" | "admin")[];
6072
6072
  }>;
6073
6073
  collections: drizzle_orm_pg_core.PgColumn<{
6074
6074
  name: "collections";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mainsoft/agent-cms",
3
- "version": "0.10.0",
3
+ "version": "0.10.2",
4
4
  "description": "An add-on CMS that runs inside your web app, edited by people (admin UI) and AI agents (MCP, REST, CLI) together.",
5
5
  "license": "MIT",
6
6
  "type": "module",