@mainsoft/agent-cms 0.0.0-stage → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/LICENSE +21 -0
  3. package/README.md +347 -2
  4. package/TODO.md +178 -0
  5. package/UPGRADE-0.6.md +236 -0
  6. package/dist/agent.cjs +250 -0
  7. package/dist/agent.d.cts +88 -0
  8. package/dist/agent.d.ts +88 -0
  9. package/dist/agent.js +24 -0
  10. package/dist/ai.cjs +555 -0
  11. package/dist/ai.d.cts +48 -0
  12. package/dist/ai.d.ts +48 -0
  13. package/dist/ai.js +73 -0
  14. package/dist/bin.js +1556 -0
  15. package/dist/chunk-2NTK7H4W.js +10 -0
  16. package/dist/chunk-52NUUZC7.js +1446 -0
  17. package/dist/chunk-6K5ZTGHQ.js +30 -0
  18. package/dist/chunk-AKN7SUXU.js +281 -0
  19. package/dist/chunk-BTO42652.js +249 -0
  20. package/dist/chunk-CRDW6Q72.js +188 -0
  21. package/dist/chunk-DD56PTZ4.js +78 -0
  22. package/dist/chunk-DOADAH4L.js +52 -0
  23. package/dist/chunk-IGL2V6US.js +324 -0
  24. package/dist/chunk-IW3D4I7Q.js +317 -0
  25. package/dist/chunk-OQ55GEF3.js +6 -0
  26. package/dist/chunk-QC2M4NZY.js +158 -0
  27. package/dist/chunk-QIUXAUQ6.js +6 -0
  28. package/dist/chunk-QQV6VLYJ.js +204 -0
  29. package/dist/chunk-T66ZKBHF.js +25 -0
  30. package/dist/chunk-VICZ76TR.js +118 -0
  31. package/dist/cli.cjs +1596 -0
  32. package/dist/cli.d.cts +89 -0
  33. package/dist/cli.d.ts +89 -0
  34. package/dist/cli.js +534 -0
  35. package/dist/client.cjs +185 -0
  36. package/dist/client.d.cts +228 -0
  37. package/dist/client.d.ts +228 -0
  38. package/dist/client.js +13 -0
  39. package/dist/cms-BPp01z-8.d.ts +411 -0
  40. package/dist/cms-D6D89-qZ.d.cts +411 -0
  41. package/dist/config.cjs +61 -0
  42. package/dist/config.d.cts +36 -0
  43. package/dist/config.d.ts +36 -0
  44. package/dist/config.js +11 -0
  45. package/dist/diff.cjs +316 -0
  46. package/dist/diff.d.cts +122 -0
  47. package/dist/diff.d.ts +122 -0
  48. package/dist/diff.js +29 -0
  49. package/dist/drizzle-repo-B1rt7r4j.d.ts +90 -0
  50. package/dist/drizzle-repo-Cn-kL2FK.d.cts +90 -0
  51. package/dist/errors.cjs +193 -0
  52. package/dist/errors.d.cts +109 -0
  53. package/dist/errors.d.ts +109 -0
  54. package/dist/errors.js +16 -0
  55. package/dist/frontmatter.cjs +103 -0
  56. package/dist/frontmatter.d.cts +32 -0
  57. package/dist/frontmatter.d.ts +32 -0
  58. package/dist/frontmatter.js +9 -0
  59. package/dist/http.cjs +1104 -0
  60. package/dist/http.d.cts +67 -0
  61. package/dist/http.d.ts +67 -0
  62. package/dist/http.js +321 -0
  63. package/dist/index.cjs +3066 -0
  64. package/dist/index.d.cts +19 -0
  65. package/dist/index.d.ts +19 -0
  66. package/dist/index.js +263 -0
  67. package/dist/markdown.cjs +220 -0
  68. package/dist/markdown.d.cts +88 -0
  69. package/dist/markdown.d.ts +88 -0
  70. package/dist/markdown.js +23 -0
  71. package/dist/mcp.cjs +649 -0
  72. package/dist/mcp.d.cts +33 -0
  73. package/dist/mcp.d.ts +33 -0
  74. package/dist/mcp.js +24 -0
  75. package/dist/messages/en.cjs +76 -0
  76. package/dist/messages/en.d.cts +7 -0
  77. package/dist/messages/en.d.ts +7 -0
  78. package/dist/messages/en.js +7 -0
  79. package/dist/messages/ko.cjs +76 -0
  80. package/dist/messages/ko.d.cts +7 -0
  81. package/dist/messages/ko.d.ts +7 -0
  82. package/dist/messages/ko.js +53 -0
  83. package/dist/registry/cms-audit.json +25 -0
  84. package/dist/registry/cms-command.json +23 -0
  85. package/dist/registry/cms-doc-editor.json +36 -0
  86. package/dist/registry/cms-doc-list.json +29 -0
  87. package/dist/registry/cms-empty.json +22 -0
  88. package/dist/registry/cms-keys.json +29 -0
  89. package/dist/registry/cms-lib.json +33 -0
  90. package/dist/registry/cms-merge.json +26 -0
  91. package/dist/registry/cms-shell.json +22 -0
  92. package/dist/registry/cms-versions.json +26 -0
  93. package/dist/registry/registry.json +255 -0
  94. package/dist/repo-BWI2Pkrv.d.ts +162 -0
  95. package/dist/repo-CeDxUxO6.d.cts +162 -0
  96. package/dist/tables.cjs +356 -0
  97. package/dist/tables.d.cts +3515 -0
  98. package/dist/tables.d.ts +3515 -0
  99. package/dist/tables.js +35 -0
  100. package/dist/tools.cjs +420 -0
  101. package/dist/tools.d.cts +27 -0
  102. package/dist/tools.d.ts +27 -0
  103. package/dist/tools.js +18 -0
  104. package/dist/types.cjs +226 -0
  105. package/dist/types.d.cts +286 -0
  106. package/dist/types.d.ts +286 -0
  107. package/dist/types.js +28 -0
  108. package/package.json +277 -4
@@ -0,0 +1,188 @@
1
+ // src/markdown.ts
2
+ var APP_LINK_RE = /\[\[link:([a-z0-9][a-z0-9._-]*)\|([^\]]+)\]\]/gi;
3
+ function anchorOf(text) {
4
+ const base = text.trim().toLowerCase().replace(/[`*_[\]()<>!?.,:;'"“”‘’/\\|]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
5
+ return base || "section";
6
+ }
7
+ function parseInline(src) {
8
+ const out = [];
9
+ const re = /(\[\[link:([a-z0-9][a-z0-9._-]*)\|([^\]]+)\]\]|\*\*([^*]+)\*\*|`([^`]+)`|\[([^\]]+)\]\(((?:[^()\s]|\([^()\s]*\))+)\))/gi;
10
+ let last = 0;
11
+ let m;
12
+ while (m = re.exec(src)) {
13
+ if (m.index > last) out.push({ t: "text", v: src.slice(last, m.index) });
14
+ if (m[2]) out.push({ t: "applink", key: m[2], v: m[3] });
15
+ else if (m[4] !== void 0) out.push({ t: "strong", v: m[4] });
16
+ else if (m[5] !== void 0) out.push({ t: "code", v: m[5] });
17
+ else if (m[6] !== void 0) {
18
+ const href = m[7];
19
+ if (/^(https?:\/\/|mailto:|\/(?!\/)|#)/i.test(href)) out.push({ t: "link", href, v: m[6] });
20
+ else out.push({ t: "text", v: m[6] });
21
+ }
22
+ last = m.index + m[0].length;
23
+ }
24
+ if (last < src.length) out.push({ t: "text", v: src.slice(last) });
25
+ return out;
26
+ }
27
+ function inlineText(inline) {
28
+ return inline.map((i) => i.v).join("");
29
+ }
30
+ function parseMarkdown(source) {
31
+ const lines = source.replace(/\r/g, "").split("\n");
32
+ const blocks = [];
33
+ const used = /* @__PURE__ */ new Map();
34
+ let para = [];
35
+ let list = null;
36
+ const uniqueId = (text) => {
37
+ const base = anchorOf(text);
38
+ const n = used.get(base) ?? 0;
39
+ used.set(base, n + 1);
40
+ return n ? `${base}-${n}` : base;
41
+ };
42
+ const flushPara = () => {
43
+ if (!para.length) return;
44
+ const text = para.join(" ").trim();
45
+ para = [];
46
+ if (!text) return;
47
+ const inline = parseInline(text);
48
+ const onlyLinks = inline.every((i) => i.t === "applink" || i.t === "text" && !i.v.trim());
49
+ if (onlyLinks && inline.some((i) => i.t === "applink")) {
50
+ blocks.push({
51
+ t: "links",
52
+ items: inline.filter((i) => i.t === "applink").map((i) => ({ key: i.key, v: i.v }))
53
+ });
54
+ } else blocks.push({ t: "p", inline });
55
+ };
56
+ const flushList = () => {
57
+ if (!list) return;
58
+ blocks.push({ t: "list", ordered: list.ordered, items: list.items.map(parseInline) });
59
+ list = null;
60
+ };
61
+ const flush = () => {
62
+ flushPara();
63
+ flushList();
64
+ };
65
+ for (let i = 0; i < lines.length; i++) {
66
+ const line = lines[i];
67
+ const fence = /^```(\S*)\s*$/.exec(line);
68
+ if (fence) {
69
+ flush();
70
+ const buf = [];
71
+ i++;
72
+ while (i < lines.length && !/^```\s*$/.test(lines[i])) buf.push(lines[i++]);
73
+ blocks.push({ t: "code", lang: fence[1] ?? "", v: buf.join("\n") });
74
+ continue;
75
+ }
76
+ const h = /^(#{2,3})\s+(.+?)\s*#*\s*$/.exec(line);
77
+ if (h) {
78
+ flush();
79
+ const text = h[2];
80
+ const inline = parseInline(text);
81
+ blocks.push({ t: "heading", level: h[1].length, id: uniqueId(inlineText(inline)), text: inlineText(inline), inline });
82
+ continue;
83
+ }
84
+ if (/^#\s+/.test(line)) {
85
+ flush();
86
+ const inline = parseInline(line.replace(/^#\s+/, ""));
87
+ blocks.push({ t: "heading", level: 2, id: uniqueId(inlineText(inline)), text: inlineText(inline), inline });
88
+ continue;
89
+ }
90
+ if (/^\s*(---|\*\*\*)\s*$/.test(line)) {
91
+ flush();
92
+ blocks.push({ t: "hr" });
93
+ continue;
94
+ }
95
+ if (/^>\s?/.test(line)) {
96
+ flush();
97
+ const buf = [];
98
+ while (i < lines.length && /^>\s?/.test(lines[i])) buf.push(lines[i++].replace(/^>\s?/, ""));
99
+ i--;
100
+ let callout = null;
101
+ const tag = /^\[!(note|tip|warning)\]\s*$/i.exec(buf[0] ?? "");
102
+ if (tag) {
103
+ callout = tag[1].toLowerCase();
104
+ buf.shift();
105
+ }
106
+ const inner = parseMarkdown(buf.join("\n")).map((b) => b.t === "heading" ? { t: "p", inline: b.inline } : b);
107
+ blocks.push({ t: "quote", callout, blocks: inner });
108
+ continue;
109
+ }
110
+ const ul = /^\s*[-*]\s+(.*)$/.exec(line);
111
+ const ol = /^\s*\d+[.)]\s+(.*)$/.exec(line);
112
+ if (ul || ol) {
113
+ flushPara();
114
+ const ordered = !!ol;
115
+ if (list && list.ordered !== ordered) flushList();
116
+ if (!list) list = { ordered, items: [] };
117
+ list.items.push((ul ?? ol)[1]);
118
+ continue;
119
+ }
120
+ if (!line.trim()) {
121
+ flush();
122
+ continue;
123
+ }
124
+ if (list && /^\s{2,}\S/.test(line)) {
125
+ list.items[list.items.length - 1] += " " + line.trim();
126
+ continue;
127
+ }
128
+ flushList();
129
+ para.push(line.trim());
130
+ }
131
+ flush();
132
+ return blocks;
133
+ }
134
+ function extractToc(blocks) {
135
+ return blocks.flatMap((b) => b.t === "heading" ? [{ id: b.id, text: b.text, level: b.level }] : []);
136
+ }
137
+ function appLinkKeys(body) {
138
+ const keys = /* @__PURE__ */ new Set();
139
+ for (const m of body.matchAll(APP_LINK_RE)) keys.add(m[1]);
140
+ return [...keys];
141
+ }
142
+ function plainText(body) {
143
+ return body.replace(/```[\s\S]*?```/g, " ").replace(APP_LINK_RE, "$2").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/^>\s?\[![a-z]+\]\s*$/gim, "").replace(/[*`>#]/g, "").replace(/^\s*(\d+[.)]|[-*])\s+/gm, "").replace(/[ \t]+/g, " ").trim();
144
+ }
145
+ function splitSections(body) {
146
+ const lines = body.replace(/\r/g, "").split("\n");
147
+ const out = [];
148
+ const used = /* @__PURE__ */ new Map();
149
+ let cur = { anchor: "", heading: "", markdown: "" };
150
+ let inFence = false;
151
+ const push = () => {
152
+ cur.markdown = cur.markdown.trim();
153
+ if (cur.markdown || cur.heading) out.push(cur);
154
+ };
155
+ for (const line of lines) {
156
+ if (/^```/.test(line)) inFence = !inFence;
157
+ const h = !inFence ? /^#{1,2}\s+(.+?)\s*#*\s*$/.exec(line) : null;
158
+ if (h) {
159
+ push();
160
+ const text = inlineText(parseInline(h[1]));
161
+ const base = anchorOf(text);
162
+ const n = used.get(base) ?? 0;
163
+ used.set(base, n + 1);
164
+ cur = { anchor: n ? `${base}-${n}` : base, heading: text, markdown: "" };
165
+ continue;
166
+ }
167
+ const h3 = !inFence ? /^###\s+(.+?)\s*#*\s*$/.exec(line) : null;
168
+ if (h3) {
169
+ const base = anchorOf(inlineText(parseInline(h3[1])));
170
+ used.set(base, (used.get(base) ?? 0) + 1);
171
+ }
172
+ cur.markdown += line + "\n";
173
+ }
174
+ push();
175
+ return out;
176
+ }
177
+
178
+ export {
179
+ APP_LINK_RE,
180
+ anchorOf,
181
+ parseInline,
182
+ inlineText,
183
+ parseMarkdown,
184
+ extractToc,
185
+ appLinkKeys,
186
+ plainText,
187
+ splitSections
188
+ };
@@ -0,0 +1,78 @@
1
+ // src/frontmatter.ts
2
+ var DOC_KEYS = /* @__PURE__ */ new Set(["slug", "title", "summary", "category", "keywords"]);
3
+ function scalar(raw) {
4
+ const v = raw.trim();
5
+ if (v === "") return "";
6
+ if (v === "true") return true;
7
+ if (v === "false") return false;
8
+ if (v === "null" || v === "~") return null;
9
+ if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v);
10
+ if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) return v.slice(1, -1);
11
+ if (v.startsWith("[") && v.endsWith("]")) {
12
+ const inner = v.slice(1, -1).trim();
13
+ return inner ? splitOutsideQuotes(inner, ",").map((x) => scalar(x)) : [];
14
+ }
15
+ return v;
16
+ }
17
+ function splitOutsideQuotes(s, sep) {
18
+ const out = [];
19
+ let cur = "";
20
+ let q = null;
21
+ for (const ch of s) {
22
+ if (q) {
23
+ if (ch === q) q = null;
24
+ } else if (ch === '"' || ch === "'") q = ch;
25
+ else if (ch === sep) {
26
+ out.push(cur);
27
+ cur = "";
28
+ continue;
29
+ }
30
+ cur += ch;
31
+ }
32
+ out.push(cur);
33
+ return out;
34
+ }
35
+ function stripComment(line) {
36
+ let q = null;
37
+ for (let i = 0; i < line.length; i++) {
38
+ const ch = line[i];
39
+ if (q) {
40
+ if (ch === q) q = null;
41
+ } else if (ch === '"' || ch === "'") q = ch;
42
+ else if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) return line.slice(0, i).trimEnd();
43
+ }
44
+ return line;
45
+ }
46
+ function parseFrontmatter(text) {
47
+ const src = text.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
48
+ const m = /^---\n([\s\S]*?)\n---\n?/.exec(src);
49
+ if (!m) return { data: {}, body: src.trim() };
50
+ const data = {};
51
+ for (const line of m[1].split("\n")) {
52
+ const t = stripComment(line);
53
+ if (!t.trim()) continue;
54
+ const i = t.indexOf(":");
55
+ if (i < 1) throw new Error(`frontmatter: cannot read line "${line}"`);
56
+ data[t.slice(0, i).trim()] = scalar(t.slice(i + 1));
57
+ }
58
+ return { data, body: src.slice(m[0].length).trim() };
59
+ }
60
+ function docFromMarkdown(text, fallbackSlug) {
61
+ const { data, body } = parseFrontmatter(text);
62
+ const fields = {};
63
+ for (const [k, v] of Object.entries(data)) if (!DOC_KEYS.has(k)) fields[k] = v;
64
+ const doc = { body };
65
+ const slug = data.slug ?? fallbackSlug;
66
+ if (slug) doc.slug = String(slug);
67
+ if (data.title !== void 0) doc.title = String(data.title);
68
+ if (data.summary !== void 0) doc.summary = String(data.summary);
69
+ if (data.category !== void 0) doc.category = data.category === null ? null : String(data.category);
70
+ if (Array.isArray(data.keywords)) doc.keywords = data.keywords.map(String);
71
+ if (Object.keys(fields).length) doc.fields = fields;
72
+ return doc;
73
+ }
74
+
75
+ export {
76
+ parseFrontmatter,
77
+ docFromMarkdown
78
+ };
@@ -0,0 +1,52 @@
1
+ // src/messages/en.ts
2
+ var en = {
3
+ not_found: "Document not found",
4
+ version_not_found: "Version v{version} not found",
5
+ key_not_found: "API key not found",
6
+ route_not_found: "No such route",
7
+ unknown_collection: "Unknown collection: {collection}",
8
+ unauthorized: "Sign in or use an API key",
9
+ invalid_key: "The API key is wrong or revoked",
10
+ key_expired: "The API key expired on {expiresAt}",
11
+ preview_invalid: "This preview link is not valid",
12
+ preview_expired: "This preview link expired",
13
+ forbidden: "Not allowed",
14
+ forbidden_read: "No read access to {collection}",
15
+ forbidden_write: "No edit access to {collection}",
16
+ forbidden_publish: "No publish access to {collection}",
17
+ forbidden_keys: "No access to API keys",
18
+ forbidden_audit: "No access to the audit log",
19
+ key_too_wide: "A key can only create keys narrower than itself",
20
+ cross_site: "Cross-site request refused",
21
+ invalid: "Invalid input",
22
+ invalid_slug: "The slug may use lowercase letters, digits and hyphens (max {max})",
23
+ invalid_title: "The title must be 1 to {max} characters",
24
+ summary_too_long: "The summary must be at most {max} characters",
25
+ body_too_long: "The body is too long (max {max} characters)",
26
+ invalid_keywords: "At most {max} keywords of {maxLength} characters each",
27
+ forbidden_char: "The character \u201C{char}\u201D is not allowed",
28
+ invalid_category: "The category must be one of: {allowed}",
29
+ invalid_field: "{path}: {issue}",
30
+ unknown_link: "Unknown screen link: {keys}",
31
+ slug_locked: "A published document's slug cannot change",
32
+ not_published: "Only a published document can be hidden",
33
+ invalid_key_name: "The key name must be 1 to 60 characters",
34
+ scopes_required: "Choose at least one scope",
35
+ invalid_expiry: "The expiry date must be in the future",
36
+ invalid_anchor: "No section \u201C{anchor}\u201D. Sections: {valid}",
37
+ invalid_version: "Invalid version number",
38
+ invalid_request: "Invalid request: {issues}",
39
+ invalid_json: "The request body is not valid JSON",
40
+ body_too_large: "The request is too large",
41
+ preview_disabled: "Preview links are off (set previewSecret)",
42
+ no_public_url: "This collection has no public URL (set url)",
43
+ schema_outdated: "The database schema is v{found}, this version needs v{expected}. Run: {command}",
44
+ conflict_version: "Someone else saved v{current} since you read v{expected}. Reload or merge, then save",
45
+ slug_taken: "The slug {slug} is already used",
46
+ precondition_required: "Send If-Match (or expectedVersion) to change this document",
47
+ internal: "Something went wrong"
48
+ };
49
+
50
+ export {
51
+ en
52
+ };
@@ -0,0 +1,324 @@
1
+ import {
2
+ LEGACY_COLUMNS,
3
+ defaultTables
4
+ } from "./chunk-IW3D4I7Q.js";
5
+ import {
6
+ SCHEMA_VERSION
7
+ } from "./chunk-OQ55GEF3.js";
8
+ import {
9
+ CmsError
10
+ } from "./chunk-VICZ76TR.js";
11
+
12
+ // src/drizzle-repo.ts
13
+ import { and, desc, eq, gte, inArray, isNotNull, lt, ne, or, sql } from "drizzle-orm";
14
+ var iso = (d) => d == null ? null : typeof d === "string" ? new Date(d).toISOString() : d.toISOString();
15
+ var date = (s) => s == null ? null : new Date(s);
16
+ async function uniq(p, slug) {
17
+ try {
18
+ return await p;
19
+ } catch (e) {
20
+ const err = e;
21
+ if (err?.code === "23505" || err?.cause?.code === "23505") throw new CmsError("slug_taken", { slug: slug ?? "" });
22
+ throw e;
23
+ }
24
+ }
25
+ var DrizzleRepo = class _DrizzleRepo {
26
+ constructor(db, o = {}) {
27
+ this.db = db;
28
+ this.t = o.tables ?? defaultTables;
29
+ }
30
+ db;
31
+ t;
32
+ toDoc(r) {
33
+ return {
34
+ id: r.id,
35
+ collection: r.collection,
36
+ slug: r.slug,
37
+ status: r.status,
38
+ title: r.title,
39
+ summary: r.summary,
40
+ body: r.body,
41
+ category: r.category,
42
+ keywords: r.keywords ?? [],
43
+ fields: r.fields ?? {},
44
+ version: r.version,
45
+ publishedVersion: r.publishedVersion,
46
+ published: r.published ?? null,
47
+ publishedAt: iso(r.publishedAt),
48
+ republishedAt: iso(r.republishedAt),
49
+ createdAt: iso(r.createdAt),
50
+ updatedAt: iso(r.updatedAt),
51
+ updatedBy: r.updatedBy,
52
+ updatedByKind: r.updatedByKind ?? null,
53
+ autosave: r.autosave ? { content: r.autosave, at: iso(r.autosaveAt), by: r.autosaveBy, baseVersion: r.autosaveBaseVersion ?? r.version } : null
54
+ };
55
+ }
56
+ patchRow(p) {
57
+ const out = {};
58
+ for (const [k, v] of Object.entries(p)) {
59
+ if (v === void 0) continue;
60
+ if (k === "publishedAt" || k === "updatedAt" || k === "republishedAt") out[k] = date(v);
61
+ else if (k === "autosave") {
62
+ const a = v;
63
+ out.autosave = a?.content ?? null;
64
+ out.autosaveAt = a ? new Date(a.at) : null;
65
+ out.autosaveBy = a?.by ?? null;
66
+ out.autosaveBaseVersion = a?.baseVersion ?? null;
67
+ } else out[k] = v;
68
+ }
69
+ return out;
70
+ }
71
+ toVersion(r) {
72
+ return {
73
+ id: r.id,
74
+ documentId: r.documentId,
75
+ version: r.version,
76
+ snapshot: r.snapshot,
77
+ authorKind: r.authorKind,
78
+ authorId: r.authorId,
79
+ authorLabel: r.authorLabel,
80
+ note: r.note,
81
+ changed: r.changed ?? null,
82
+ reviewed: r.reviewed ?? [],
83
+ createdAt: iso(r.createdAt)
84
+ };
85
+ }
86
+ toKey(r) {
87
+ return {
88
+ id: r.id,
89
+ name: r.name,
90
+ prefix: r.prefix,
91
+ hash: r.hash,
92
+ scopes: r.scopes,
93
+ collections: r.collections ?? null,
94
+ createdBy: r.createdBy,
95
+ lastUsedAt: iso(r.lastUsedAt),
96
+ revokedAt: iso(r.revokedAt),
97
+ expiresAt: iso(r.expiresAt),
98
+ createdAt: iso(r.createdAt)
99
+ };
100
+ }
101
+ tx(fn) {
102
+ return this.db.transaction((t) => fn(new _DrizzleRepo(t, { tables: this.t })));
103
+ }
104
+ async findDoc(collection, slug) {
105
+ const D = this.t.documents;
106
+ const [r] = await this.db.select().from(D).where(and(eq(D.collection, collection), eq(D.slug, slug))).limit(1);
107
+ return r ? this.toDoc(r) : null;
108
+ }
109
+ async findDocById(id) {
110
+ const D = this.t.documents;
111
+ const [r] = await this.db.select().from(D).where(eq(D.id, id)).limit(1);
112
+ return r ? this.toDoc(r) : null;
113
+ }
114
+ async listDocs(f) {
115
+ const D = this.t.documents;
116
+ const conds = [];
117
+ if (f.collection) conds.push(eq(D.collection, f.collection));
118
+ if (f.statuses) conds.push(inArray(D.status, f.statuses));
119
+ if (f.published === true) conds.push(isNotNull(D.publishedVersion), ne(D.status, "archived"));
120
+ const rows = await this.db.select().from(D).where(conds.length ? and(...conds) : void 0);
121
+ const docs = rows.map((r) => this.toDoc(r));
122
+ return f.published === false ? docs.filter((d) => d.publishedVersion === null || d.status === "archived") : docs;
123
+ }
124
+ async insertDoc(doc) {
125
+ const [r] = await uniq(
126
+ this.db.insert(this.t.documents).values({
127
+ ...this.patchRow(doc),
128
+ ...doc.id ? { id: doc.id } : {},
129
+ collection: doc.collection,
130
+ slug: doc.slug,
131
+ title: doc.title,
132
+ createdAt: date(doc.createdAt ?? null) ?? void 0
133
+ }).returning(),
134
+ doc.slug
135
+ );
136
+ return this.toDoc(r);
137
+ }
138
+ async updateDoc(id, p, expectedVersion) {
139
+ const D = this.t.documents;
140
+ const where = expectedVersion === void 0 ? eq(D.id, id) : and(eq(D.id, id), eq(D.version, expectedVersion));
141
+ const [r] = await uniq(
142
+ this.db.update(D).set({ ...this.patchRow(p), updatedAt: date(p.updatedAt ?? null) ?? /* @__PURE__ */ new Date() }).where(where).returning(),
143
+ p.slug
144
+ );
145
+ return r ? this.toDoc(r) : null;
146
+ }
147
+ async deleteDoc(id) {
148
+ await this.db.delete(this.t.documents).where(eq(this.t.documents.id, id));
149
+ }
150
+ async insertVersion(v) {
151
+ await uniq(
152
+ this.db.insert(this.t.versions).values({
153
+ documentId: v.documentId,
154
+ version: v.version,
155
+ snapshot: v.snapshot,
156
+ authorKind: v.authorKind,
157
+ authorId: v.authorId,
158
+ authorLabel: v.authorLabel,
159
+ note: v.note,
160
+ changed: v.changed ?? null,
161
+ createdAt: date(v.createdAt ?? null) ?? void 0
162
+ })
163
+ );
164
+ }
165
+ async listVersions(documentId) {
166
+ const V = this.t.versions;
167
+ const rows = await this.db.select().from(V).where(eq(V.documentId, documentId)).orderBy(desc(V.version));
168
+ return rows.map((r) => this.toVersion(r));
169
+ }
170
+ async getVersion(documentId, version) {
171
+ const V = this.t.versions;
172
+ const [r] = await this.db.select().from(V).where(and(eq(V.documentId, documentId), eq(V.version, version))).limit(1);
173
+ return r ? this.toVersion(r) : null;
174
+ }
175
+ async setVersionReviewed(documentId, version, reviewed) {
176
+ const V = this.t.versions;
177
+ await this.db.update(V).set({ reviewed }).where(and(eq(V.documentId, documentId), eq(V.version, version)));
178
+ }
179
+ async pruneVersions(documentId, keep, protect) {
180
+ const V = this.t.versions;
181
+ const rows = await this.db.select({ id: V.id, version: V.version }).from(V).where(eq(V.documentId, documentId)).orderBy(desc(V.version));
182
+ const drop = rows.slice(keep).filter((r) => !protect.includes(r.version)).map((r) => r.id);
183
+ if (drop.length) await this.db.delete(V).where(inArray(V.id, drop));
184
+ }
185
+ async insertKey(k) {
186
+ const [r] = await this.db.insert(this.t.apiKeys).values({ ...k, expiresAt: date(k.expiresAt) }).returning();
187
+ return this.toKey(r);
188
+ }
189
+ async listKeys() {
190
+ return (await this.db.select().from(this.t.apiKeys)).map((r) => this.toKey(r));
191
+ }
192
+ async findKeyByHash(hash) {
193
+ const K = this.t.apiKeys;
194
+ const [r] = await this.db.select().from(K).where(eq(K.hash, hash)).limit(1);
195
+ return r ? this.toKey(r) : null;
196
+ }
197
+ async touchKey(id, at) {
198
+ const K = this.t.apiKeys;
199
+ await this.db.update(K).set({ lastUsedAt: new Date(at) }).where(eq(K.id, id));
200
+ }
201
+ async revokeKey(id, at) {
202
+ const K = this.t.apiKeys;
203
+ const rows = await this.db.update(K).set({ revokedAt: new Date(at) }).where(and(eq(K.id, id), sql`${K.revokedAt} is null`)).returning({ id: K.id });
204
+ return rows.length > 0;
205
+ }
206
+ async addHits(ids, day, source) {
207
+ if (!ids.length) return;
208
+ const H = this.t.hits;
209
+ await this.db.insert(H).values(ids.map((documentId) => ({ documentId, day, source, count: 1 }))).onConflictDoUpdate({ target: [H.documentId, H.day, H.source], set: { count: sql`${H.count} + 1` } });
210
+ }
211
+ async hitCounts(sinceDay, collection) {
212
+ const H = this.t.hits;
213
+ const D = this.t.documents;
214
+ const rows = collection ? await this.db.select({ id: H.documentId, n: sql`sum(${H.count})::int` }).from(H).innerJoin(D, eq(D.id, H.documentId)).where(and(gte(H.day, sinceDay), eq(D.collection, collection))).groupBy(H.documentId) : await this.db.select({ id: H.documentId, n: sql`sum(${H.count})::int` }).from(H).where(gte(H.day, sinceDay)).groupBy(H.documentId);
215
+ return new Map(rows.map((r) => [r.id, Number(r.n)]));
216
+ }
217
+ async insertAudit(e) {
218
+ await this.db.insert(this.t.audit).values({ ...e, at: new Date(e.at) });
219
+ }
220
+ async listAudit(q) {
221
+ const A = this.t.audit;
222
+ const conds = [];
223
+ if (q.before) {
224
+ const [at, id] = q.before.split("|");
225
+ conds.push(or(lt(A.at, new Date(at)), and(eq(A.at, new Date(at)), lt(A.id, id))));
226
+ }
227
+ if (q.action) conds.push(eq(A.action, q.action));
228
+ if (q.outcome) conds.push(eq(A.outcome, q.outcome));
229
+ if (q.actorKind) conds.push(eq(A.actorKind, q.actorKind));
230
+ const rows = await this.db.select().from(A).where(conds.length ? and(...conds) : void 0).orderBy(desc(A.at), desc(A.id)).limit(q.limit);
231
+ return rows.map((r) => ({
232
+ id: r.id,
233
+ at: iso(r.at),
234
+ actorKind: r.actorKind,
235
+ actorId: r.actorId,
236
+ actorLabel: r.actorLabel,
237
+ action: r.action,
238
+ collection: r.collection,
239
+ slug: r.slug,
240
+ version: r.version,
241
+ outcome: r.outcome,
242
+ via: r.via ?? null,
243
+ detail: r.detail ?? {}
244
+ }));
245
+ }
246
+ async changeStamp() {
247
+ const D = this.t.documents;
248
+ const [r] = await this.db.select({ n: sql`count(*)::int`, max: sql`max(${D.updatedAt})::text` }).from(D);
249
+ return `${r?.n ?? 0}:${r?.max ?? ""}`;
250
+ }
251
+ async getMeta(key) {
252
+ const M = this.t.meta;
253
+ try {
254
+ const [r] = await this.db.select().from(M).where(eq(M.key, key)).limit(1);
255
+ return r?.value ?? null;
256
+ } catch (e) {
257
+ if (e?.code === "42P01" || e?.cause?.code === "42P01") return null;
258
+ throw e;
259
+ }
260
+ }
261
+ async setMeta(key, value) {
262
+ const M = this.t.meta;
263
+ await this.db.insert(M).values({ key, value }).onConflictDoUpdate({ target: M.key, set: { value, updatedAt: /* @__PURE__ */ new Date() } });
264
+ }
265
+ // ── doctor ────────────────────────────────────────────────────────────────
266
+ /** Raw rows of a SQL query, across drivers (node-postgres returns `{ rows }`, pglite too, postgres.js an array). */
267
+ async rows(q) {
268
+ const r = await this.db.execute(q);
269
+ return Array.isArray(r) ? r : r.rows ?? [];
270
+ }
271
+ /** What `agent-cms doctor` checks. Read-only. */
272
+ async inspect() {
273
+ const { prefix, schema } = this.t.options;
274
+ const sch = schema ?? null;
275
+ const cols = await this.rows(
276
+ sql`select table_name, column_name from information_schema.columns where table_schema = coalesce(${sch}, current_schema()) and table_name like ${prefix.replace(/_/g, "\\_") + "%"}`
277
+ );
278
+ const have = /* @__PURE__ */ new Map();
279
+ for (const c of cols) {
280
+ if (!have.has(c.table_name)) have.set(c.table_name, /* @__PURE__ */ new Set());
281
+ have.get(c.table_name).add(c.column_name);
282
+ }
283
+ const expected = {};
284
+ for (const [key, tbl] of Object.entries({ documents: this.t.documents, versions: this.t.versions, api_keys: this.t.apiKeys, hits: this.t.hits, meta: this.t.meta, audit: this.t.audit })) {
285
+ expected[prefix + key] = Object.values(tbl).filter((c) => c && typeof c === "object" && "name" in c && "columnType" in c).map((c) => c.name);
286
+ }
287
+ const missingTables = Object.keys(expected).filter((t) => !have.has(t));
288
+ const missingColumns = Object.entries(expected).flatMap(([t, cs]) => have.has(t) ? cs.filter((c) => !have.get(t).has(c)).map((c) => `${t}.${c}`) : []);
289
+ const legacyColumns = LEGACY_COLUMNS.filter((l) => have.get(prefix + l.table)?.has(l.column)).map((l) => `${prefix}${l.table}.${l.column}`);
290
+ const gapsTable = have.has(`${prefix}gaps`);
291
+ let gapsRows = null;
292
+ if (gapsTable) {
293
+ const tbl = sch ? `"${sch}"."${prefix}gaps"` : `"${prefix}gaps"`;
294
+ const [r] = await this.rows(sql.raw(`select count(*)::int as n from ${tbl}`));
295
+ gapsRows = Number(r?.n ?? 0);
296
+ }
297
+ const found = missingTables.includes(`${prefix}meta`) ? null : await this.getMeta("schema_version");
298
+ let badPublished = 0;
299
+ let orphanVersions = 0;
300
+ if (!missingTables.length) {
301
+ const D = this.t.documents;
302
+ const V = this.t.versions;
303
+ const [bp] = await this.db.select({ n: sql`count(*)::int` }).from(D).where(sql`${D.publishedVersion} is not null and (${D.publishedVersion} > ${D.version} or ${D.published} is null)`);
304
+ badPublished = Number(bp?.n ?? 0);
305
+ const [ov] = await this.db.select({ n: sql`count(*)::int` }).from(V).where(sql`not exists (select 1 from ${D} d where d.id = ${V.documentId})`);
306
+ orphanVersions = Number(ov?.n ?? 0);
307
+ }
308
+ return {
309
+ schemaVersion: typeof found === "number" ? found : found == null ? null : Number(found),
310
+ expectedSchemaVersion: SCHEMA_VERSION,
311
+ missingTables,
312
+ missingColumns,
313
+ legacyColumns,
314
+ gapsTable,
315
+ gapsRows,
316
+ badPublished,
317
+ orphanVersions
318
+ };
319
+ }
320
+ };
321
+
322
+ export {
323
+ DrizzleRepo
324
+ };