@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.
- package/CHANGELOG.md +49 -0
- package/LICENSE +21 -0
- package/README.md +347 -2
- package/TODO.md +178 -0
- package/UPGRADE-0.6.md +236 -0
- package/dist/agent.cjs +250 -0
- package/dist/agent.d.cts +88 -0
- package/dist/agent.d.ts +88 -0
- package/dist/agent.js +24 -0
- package/dist/ai.cjs +555 -0
- package/dist/ai.d.cts +48 -0
- package/dist/ai.d.ts +48 -0
- package/dist/ai.js +73 -0
- package/dist/bin.js +1556 -0
- package/dist/chunk-2NTK7H4W.js +10 -0
- package/dist/chunk-52NUUZC7.js +1446 -0
- package/dist/chunk-6K5ZTGHQ.js +30 -0
- package/dist/chunk-AKN7SUXU.js +281 -0
- package/dist/chunk-BTO42652.js +249 -0
- package/dist/chunk-CRDW6Q72.js +188 -0
- package/dist/chunk-DD56PTZ4.js +78 -0
- package/dist/chunk-DOADAH4L.js +52 -0
- package/dist/chunk-IGL2V6US.js +324 -0
- package/dist/chunk-IW3D4I7Q.js +317 -0
- package/dist/chunk-OQ55GEF3.js +6 -0
- package/dist/chunk-QC2M4NZY.js +158 -0
- package/dist/chunk-QIUXAUQ6.js +6 -0
- package/dist/chunk-QQV6VLYJ.js +204 -0
- package/dist/chunk-T66ZKBHF.js +25 -0
- package/dist/chunk-VICZ76TR.js +118 -0
- package/dist/cli.cjs +1596 -0
- package/dist/cli.d.cts +89 -0
- package/dist/cli.d.ts +89 -0
- package/dist/cli.js +534 -0
- package/dist/client.cjs +185 -0
- package/dist/client.d.cts +228 -0
- package/dist/client.d.ts +228 -0
- package/dist/client.js +13 -0
- package/dist/cms-BPp01z-8.d.ts +411 -0
- package/dist/cms-D6D89-qZ.d.cts +411 -0
- package/dist/config.cjs +61 -0
- package/dist/config.d.cts +36 -0
- package/dist/config.d.ts +36 -0
- package/dist/config.js +11 -0
- package/dist/diff.cjs +316 -0
- package/dist/diff.d.cts +122 -0
- package/dist/diff.d.ts +122 -0
- package/dist/diff.js +29 -0
- package/dist/drizzle-repo-B1rt7r4j.d.ts +90 -0
- package/dist/drizzle-repo-Cn-kL2FK.d.cts +90 -0
- package/dist/errors.cjs +193 -0
- package/dist/errors.d.cts +109 -0
- package/dist/errors.d.ts +109 -0
- package/dist/errors.js +16 -0
- package/dist/frontmatter.cjs +103 -0
- package/dist/frontmatter.d.cts +32 -0
- package/dist/frontmatter.d.ts +32 -0
- package/dist/frontmatter.js +9 -0
- package/dist/http.cjs +1104 -0
- package/dist/http.d.cts +67 -0
- package/dist/http.d.ts +67 -0
- package/dist/http.js +321 -0
- package/dist/index.cjs +3066 -0
- package/dist/index.d.cts +19 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +263 -0
- package/dist/markdown.cjs +220 -0
- package/dist/markdown.d.cts +88 -0
- package/dist/markdown.d.ts +88 -0
- package/dist/markdown.js +23 -0
- package/dist/mcp.cjs +649 -0
- package/dist/mcp.d.cts +33 -0
- package/dist/mcp.d.ts +33 -0
- package/dist/mcp.js +24 -0
- package/dist/messages/en.cjs +76 -0
- package/dist/messages/en.d.cts +7 -0
- package/dist/messages/en.d.ts +7 -0
- package/dist/messages/en.js +7 -0
- package/dist/messages/ko.cjs +76 -0
- package/dist/messages/ko.d.cts +7 -0
- package/dist/messages/ko.d.ts +7 -0
- package/dist/messages/ko.js +53 -0
- package/dist/registry/cms-audit.json +25 -0
- package/dist/registry/cms-command.json +23 -0
- package/dist/registry/cms-doc-editor.json +36 -0
- package/dist/registry/cms-doc-list.json +29 -0
- package/dist/registry/cms-empty.json +22 -0
- package/dist/registry/cms-keys.json +29 -0
- package/dist/registry/cms-lib.json +33 -0
- package/dist/registry/cms-merge.json +26 -0
- package/dist/registry/cms-shell.json +22 -0
- package/dist/registry/cms-versions.json +26 -0
- package/dist/registry/registry.json +255 -0
- package/dist/repo-BWI2Pkrv.d.ts +162 -0
- package/dist/repo-CeDxUxO6.d.cts +162 -0
- package/dist/tables.cjs +356 -0
- package/dist/tables.d.cts +3515 -0
- package/dist/tables.d.ts +3515 -0
- package/dist/tables.js +35 -0
- package/dist/tools.cjs +420 -0
- package/dist/tools.d.cts +27 -0
- package/dist/tools.d.ts +27 -0
- package/dist/tools.js +18 -0
- package/dist/types.cjs +226 -0
- package/dist/types.d.cts +286 -0
- package/dist/types.d.ts +286 -0
- package/dist/types.js +28 -0
- package/package.json +277 -4
package/dist/bin.js
ADDED
|
@@ -0,0 +1,1556 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { spawnSync } from "child_process";
|
|
5
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
6
|
+
import { basename as basename2, dirname as dirname2, join as join2 } from "path";
|
|
7
|
+
|
|
8
|
+
// src/client.ts
|
|
9
|
+
var CmsRemoteError = class extends Error {
|
|
10
|
+
constructor(message, code, extra = {}) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.extra = extra;
|
|
14
|
+
this.name = "CmsRemoteError";
|
|
15
|
+
}
|
|
16
|
+
code;
|
|
17
|
+
extra;
|
|
18
|
+
isCmsRemoteError = true;
|
|
19
|
+
get kind() {
|
|
20
|
+
return this.extra.kind;
|
|
21
|
+
}
|
|
22
|
+
get status() {
|
|
23
|
+
return this.extra.status;
|
|
24
|
+
}
|
|
25
|
+
get params() {
|
|
26
|
+
return this.extra.params;
|
|
27
|
+
}
|
|
28
|
+
get diagnostics() {
|
|
29
|
+
return this.extra.diagnostics;
|
|
30
|
+
}
|
|
31
|
+
/** On `conflict_version`: the working copy someone else saved (for a merge). */
|
|
32
|
+
get current() {
|
|
33
|
+
return this.extra.current;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
function isCmsRemoteError(e) {
|
|
37
|
+
return !!e && typeof e === "object" && e.isCmsRemoteError === true;
|
|
38
|
+
}
|
|
39
|
+
function createCmsClient(opts) {
|
|
40
|
+
const base = opts.url.replace(/\/+$/, "");
|
|
41
|
+
const doFetch = opts.fetch ?? fetch;
|
|
42
|
+
let seq = 0;
|
|
43
|
+
async function rpc(method, params) {
|
|
44
|
+
const res = await doFetch(`${base}/mcp`, {
|
|
45
|
+
method: "POST",
|
|
46
|
+
headers: {
|
|
47
|
+
"content-type": "application/json",
|
|
48
|
+
accept: "application/json, text/event-stream",
|
|
49
|
+
authorization: `Bearer ${opts.key}`,
|
|
50
|
+
...opts.clientName ? { "x-agent-cms-client": opts.clientName } : {}
|
|
51
|
+
},
|
|
52
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: ++seq, method, params })
|
|
53
|
+
});
|
|
54
|
+
const text2 = await res.text();
|
|
55
|
+
let msg = null;
|
|
56
|
+
try {
|
|
57
|
+
msg = JSON.parse(text2);
|
|
58
|
+
} catch {
|
|
59
|
+
}
|
|
60
|
+
if (!res.ok || !msg) {
|
|
61
|
+
const rest = msg;
|
|
62
|
+
if (rest && typeof rest.error === "string") throw new CmsRemoteError(rest.message ?? rest.error, rest.error, { status: res.status });
|
|
63
|
+
throw new CmsRemoteError(msg?.error?.message ?? `HTTP ${res.status}: ${text2.slice(0, 200)}`, "http", { status: res.status });
|
|
64
|
+
}
|
|
65
|
+
if (msg.error) throw new CmsRemoteError(msg.error.message ?? "RPC error", "rpc");
|
|
66
|
+
return msg.result;
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
/** Tools this key can use. */
|
|
70
|
+
async listTools() {
|
|
71
|
+
const r = await rpc("tools/list", {});
|
|
72
|
+
return r.tools;
|
|
73
|
+
},
|
|
74
|
+
/** Call one tool (see `CMS_TOOL_NAMES`). Throws CmsRemoteError on failure. */
|
|
75
|
+
async call(name, args = {}) {
|
|
76
|
+
const r = await rpc("tools/call", { name, arguments: args });
|
|
77
|
+
const text2 = r.content?.find((c) => c.type === "text")?.text ?? "";
|
|
78
|
+
if (r.isError) {
|
|
79
|
+
const s = r.structuredContent;
|
|
80
|
+
if (s?.error) throw new CmsRemoteError(s.message ?? text2, s.error, { kind: s.kind, params: s.params, diagnostics: s.diagnostics, current: s.current });
|
|
81
|
+
const m = /^([a-z_]+): ([\s\S]*)$/.exec(text2);
|
|
82
|
+
throw new CmsRemoteError(m ? m[2] : text2, m ? m[1] : "tool");
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
return JSON.parse(text2);
|
|
86
|
+
} catch {
|
|
87
|
+
return r.structuredContent;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// src/config.ts
|
|
94
|
+
var CONFIG_FILES = ["agent-cms.config.ts", "agent-cms.config.mts", "agent-cms.config.js", "agent-cms.config.mjs"];
|
|
95
|
+
async function loadConfig(cwd) {
|
|
96
|
+
const { existsSync: existsSync3 } = await import("fs");
|
|
97
|
+
const { join: join3 } = await import("path");
|
|
98
|
+
for (const f of CONFIG_FILES) {
|
|
99
|
+
const path = join3(cwd, f);
|
|
100
|
+
if (!existsSync3(path)) continue;
|
|
101
|
+
const { createJiti } = await import("jiti");
|
|
102
|
+
const jiti = createJiti(join3(cwd, "_"), { interopDefault: true });
|
|
103
|
+
const mod = await jiti.import(path);
|
|
104
|
+
const config = mod && "default" in mod ? mod.default : mod;
|
|
105
|
+
return { path, config: config ?? {} };
|
|
106
|
+
}
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// src/drizzle-repo.ts
|
|
111
|
+
import { and, desc, eq, gte, inArray, isNotNull, lt, ne, or, sql } from "drizzle-orm";
|
|
112
|
+
|
|
113
|
+
// src/messages/en.ts
|
|
114
|
+
var en = {
|
|
115
|
+
not_found: "Document not found",
|
|
116
|
+
version_not_found: "Version v{version} not found",
|
|
117
|
+
key_not_found: "API key not found",
|
|
118
|
+
route_not_found: "No such route",
|
|
119
|
+
unknown_collection: "Unknown collection: {collection}",
|
|
120
|
+
unauthorized: "Sign in or use an API key",
|
|
121
|
+
invalid_key: "The API key is wrong or revoked",
|
|
122
|
+
key_expired: "The API key expired on {expiresAt}",
|
|
123
|
+
preview_invalid: "This preview link is not valid",
|
|
124
|
+
preview_expired: "This preview link expired",
|
|
125
|
+
forbidden: "Not allowed",
|
|
126
|
+
forbidden_read: "No read access to {collection}",
|
|
127
|
+
forbidden_write: "No edit access to {collection}",
|
|
128
|
+
forbidden_publish: "No publish access to {collection}",
|
|
129
|
+
forbidden_keys: "No access to API keys",
|
|
130
|
+
forbidden_audit: "No access to the audit log",
|
|
131
|
+
key_too_wide: "A key can only create keys narrower than itself",
|
|
132
|
+
cross_site: "Cross-site request refused",
|
|
133
|
+
invalid: "Invalid input",
|
|
134
|
+
invalid_slug: "The slug may use lowercase letters, digits and hyphens (max {max})",
|
|
135
|
+
invalid_title: "The title must be 1 to {max} characters",
|
|
136
|
+
summary_too_long: "The summary must be at most {max} characters",
|
|
137
|
+
body_too_long: "The body is too long (max {max} characters)",
|
|
138
|
+
invalid_keywords: "At most {max} keywords of {maxLength} characters each",
|
|
139
|
+
forbidden_char: "The character \u201C{char}\u201D is not allowed",
|
|
140
|
+
invalid_category: "The category must be one of: {allowed}",
|
|
141
|
+
invalid_field: "{path}: {issue}",
|
|
142
|
+
unknown_link: "Unknown screen link: {keys}",
|
|
143
|
+
slug_locked: "A published document's slug cannot change",
|
|
144
|
+
not_published: "Only a published document can be hidden",
|
|
145
|
+
invalid_key_name: "The key name must be 1 to 60 characters",
|
|
146
|
+
scopes_required: "Choose at least one scope",
|
|
147
|
+
invalid_expiry: "The expiry date must be in the future",
|
|
148
|
+
invalid_anchor: "No section \u201C{anchor}\u201D. Sections: {valid}",
|
|
149
|
+
invalid_version: "Invalid version number",
|
|
150
|
+
invalid_request: "Invalid request: {issues}",
|
|
151
|
+
invalid_json: "The request body is not valid JSON",
|
|
152
|
+
body_too_large: "The request is too large",
|
|
153
|
+
preview_disabled: "Preview links are off (set previewSecret)",
|
|
154
|
+
no_public_url: "This collection has no public URL (set url)",
|
|
155
|
+
schema_outdated: "The database schema is v{found}, this version needs v{expected}. Run: {command}",
|
|
156
|
+
conflict_version: "Someone else saved v{current} since you read v{expected}. Reload or merge, then save",
|
|
157
|
+
slug_taken: "The slug {slug} is already used",
|
|
158
|
+
precondition_required: "Send If-Match (or expectedVersion) to change this document",
|
|
159
|
+
internal: "Something went wrong"
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
// src/errors.ts
|
|
163
|
+
var ERROR_CODES = {
|
|
164
|
+
// not found
|
|
165
|
+
not_found: "not_found",
|
|
166
|
+
version_not_found: "not_found",
|
|
167
|
+
key_not_found: "not_found",
|
|
168
|
+
route_not_found: "not_found",
|
|
169
|
+
unknown_collection: "unknown_collection",
|
|
170
|
+
// access
|
|
171
|
+
unauthorized: "unauthorized",
|
|
172
|
+
invalid_key: "unauthorized",
|
|
173
|
+
key_expired: "unauthorized",
|
|
174
|
+
preview_invalid: "unauthorized",
|
|
175
|
+
preview_expired: "unauthorized",
|
|
176
|
+
forbidden: "forbidden",
|
|
177
|
+
forbidden_read: "forbidden",
|
|
178
|
+
forbidden_write: "forbidden",
|
|
179
|
+
forbidden_publish: "forbidden",
|
|
180
|
+
forbidden_keys: "forbidden",
|
|
181
|
+
forbidden_audit: "forbidden",
|
|
182
|
+
key_too_wide: "forbidden",
|
|
183
|
+
cross_site: "forbidden",
|
|
184
|
+
// validation
|
|
185
|
+
invalid: "invalid",
|
|
186
|
+
invalid_slug: "invalid",
|
|
187
|
+
invalid_title: "invalid",
|
|
188
|
+
summary_too_long: "invalid",
|
|
189
|
+
body_too_long: "invalid",
|
|
190
|
+
invalid_keywords: "invalid",
|
|
191
|
+
forbidden_char: "invalid",
|
|
192
|
+
invalid_category: "invalid",
|
|
193
|
+
invalid_field: "invalid",
|
|
194
|
+
unknown_link: "invalid",
|
|
195
|
+
slug_locked: "invalid",
|
|
196
|
+
not_published: "invalid",
|
|
197
|
+
invalid_key_name: "invalid",
|
|
198
|
+
scopes_required: "invalid",
|
|
199
|
+
invalid_expiry: "invalid",
|
|
200
|
+
invalid_anchor: "invalid",
|
|
201
|
+
invalid_version: "invalid",
|
|
202
|
+
invalid_request: "invalid",
|
|
203
|
+
invalid_json: "invalid",
|
|
204
|
+
body_too_large: "invalid",
|
|
205
|
+
preview_disabled: "invalid",
|
|
206
|
+
no_public_url: "invalid",
|
|
207
|
+
schema_outdated: "invalid",
|
|
208
|
+
// concurrency
|
|
209
|
+
conflict_version: "conflict",
|
|
210
|
+
slug_taken: "conflict",
|
|
211
|
+
precondition_required: "precondition",
|
|
212
|
+
// anything else
|
|
213
|
+
internal: "internal"
|
|
214
|
+
};
|
|
215
|
+
var STATUS = {
|
|
216
|
+
not_found: 404,
|
|
217
|
+
unknown_collection: 404,
|
|
218
|
+
unauthorized: 401,
|
|
219
|
+
forbidden: 403,
|
|
220
|
+
invalid: 422,
|
|
221
|
+
conflict: 409,
|
|
222
|
+
precondition: 428,
|
|
223
|
+
internal: 500
|
|
224
|
+
};
|
|
225
|
+
function formatMessage(messages, code, params = {}) {
|
|
226
|
+
const t = messages?.[code] ?? en[code] ?? code;
|
|
227
|
+
if (typeof t === "function") return t(params);
|
|
228
|
+
return t.replace(/\{(\w+)\}/g, (_, k) => {
|
|
229
|
+
const v = params[k];
|
|
230
|
+
return v == null ? "" : Array.isArray(v) ? v.join(", ") : String(v);
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
var CmsError = class extends Error {
|
|
234
|
+
constructor(code, params = {}, o = {}) {
|
|
235
|
+
super(o.message ?? formatMessage(o.messages, code, params));
|
|
236
|
+
this.code = code;
|
|
237
|
+
this.name = "CmsError";
|
|
238
|
+
this.kind = ERROR_CODES[code] ?? "internal";
|
|
239
|
+
this.status = o.status ?? STATUS[this.kind];
|
|
240
|
+
this.params = params;
|
|
241
|
+
this.diagnostics = o.diagnostics;
|
|
242
|
+
this.current = o.current;
|
|
243
|
+
}
|
|
244
|
+
code;
|
|
245
|
+
kind;
|
|
246
|
+
status;
|
|
247
|
+
params;
|
|
248
|
+
diagnostics;
|
|
249
|
+
current;
|
|
250
|
+
/** Marks CmsErrors so `isCmsError` works across bundle copies of this class. */
|
|
251
|
+
isCmsError = true;
|
|
252
|
+
/** The wire shape (REST body, MCP error text, AI tool result). */
|
|
253
|
+
toJSON() {
|
|
254
|
+
return {
|
|
255
|
+
error: this.code,
|
|
256
|
+
kind: this.kind,
|
|
257
|
+
message: this.message,
|
|
258
|
+
params: this.params,
|
|
259
|
+
...this.diagnostics ? { diagnostics: this.diagnostics } : {},
|
|
260
|
+
...this.current !== void 0 ? { current: this.current } : {}
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
// src/schema-version.ts
|
|
266
|
+
var SCHEMA_VERSION = 2;
|
|
267
|
+
|
|
268
|
+
// src/tables.ts
|
|
269
|
+
import { date, index, integer, jsonb, pgSchema, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
|
|
270
|
+
var NAME_RE = /^[a-z_][a-z0-9_]*$/;
|
|
271
|
+
function cmsTables(o = {}) {
|
|
272
|
+
const prefix = o.prefix ?? "cms_";
|
|
273
|
+
if (!NAME_RE.test(prefix)) throw new Error(`[agent-cms] table prefix must match ${NAME_RE}: ${prefix}`);
|
|
274
|
+
if (o.schema && !NAME_RE.test(o.schema)) throw new Error(`[agent-cms] schema name must match ${NAME_RE}: ${o.schema}`);
|
|
275
|
+
const table = o.schema ? pgSchema(o.schema).table : pgTable;
|
|
276
|
+
const n = (s) => `${prefix}${s}`;
|
|
277
|
+
const documents = table(
|
|
278
|
+
n("documents"),
|
|
279
|
+
{
|
|
280
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
281
|
+
collection: text("collection").notNull(),
|
|
282
|
+
slug: text("slug").notNull(),
|
|
283
|
+
status: text("status").notNull().default("draft"),
|
|
284
|
+
title: text("title").notNull(),
|
|
285
|
+
summary: text("summary").notNull().default(""),
|
|
286
|
+
body: text("body").notNull().default(""),
|
|
287
|
+
category: text("category"),
|
|
288
|
+
keywords: jsonb("keywords").$type().notNull().default([]),
|
|
289
|
+
fields: jsonb("fields").$type().notNull().default({}),
|
|
290
|
+
version: integer("version").notNull().default(1),
|
|
291
|
+
publishedVersion: integer("published_version"),
|
|
292
|
+
published: jsonb("published").$type(),
|
|
293
|
+
updatedBy: text("updated_by"),
|
|
294
|
+
updatedByKind: text("updated_by_kind"),
|
|
295
|
+
publishedAt: timestamp("published_at", { withTimezone: true }),
|
|
296
|
+
republishedAt: timestamp("republished_at", { withTimezone: true }),
|
|
297
|
+
autosave: jsonb("autosave").$type(),
|
|
298
|
+
autosaveAt: timestamp("autosave_at", { withTimezone: true }),
|
|
299
|
+
autosaveBy: text("autosave_by"),
|
|
300
|
+
autosaveBaseVersion: integer("autosave_base_version"),
|
|
301
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
302
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
|
|
303
|
+
},
|
|
304
|
+
(t) => ({
|
|
305
|
+
slugIdx: uniqueIndex(n("documents_collection_slug_idx")).on(t.collection, t.slug),
|
|
306
|
+
statusIdx: index(n("documents_collection_status_idx")).on(t.collection, t.status)
|
|
307
|
+
})
|
|
308
|
+
);
|
|
309
|
+
const versions = table(
|
|
310
|
+
n("versions"),
|
|
311
|
+
{
|
|
312
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
313
|
+
documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
|
|
314
|
+
version: integer("version").notNull(),
|
|
315
|
+
snapshot: jsonb("snapshot").$type().notNull(),
|
|
316
|
+
authorKind: text("author_kind").notNull(),
|
|
317
|
+
authorId: text("author_id"),
|
|
318
|
+
authorLabel: text("author_label").notNull(),
|
|
319
|
+
note: text("note"),
|
|
320
|
+
changed: jsonb("changed").$type(),
|
|
321
|
+
reviewed: jsonb("reviewed").$type().notNull().default([]),
|
|
322
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
|
|
323
|
+
},
|
|
324
|
+
(t) => ({
|
|
325
|
+
docVersionIdx: uniqueIndex(n("versions_doc_version_idx")).on(t.documentId, t.version)
|
|
326
|
+
})
|
|
327
|
+
);
|
|
328
|
+
const apiKeys = table(n("api_keys"), {
|
|
329
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
330
|
+
name: text("name").notNull(),
|
|
331
|
+
prefix: text("prefix").notNull(),
|
|
332
|
+
hash: text("hash").notNull().unique(),
|
|
333
|
+
scopes: jsonb("scopes").$type().notNull(),
|
|
334
|
+
collections: jsonb("collections").$type(),
|
|
335
|
+
createdBy: text("created_by"),
|
|
336
|
+
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
|
|
337
|
+
revokedAt: timestamp("revoked_at", { withTimezone: true }),
|
|
338
|
+
expiresAt: timestamp("expires_at", { withTimezone: true }),
|
|
339
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
|
|
340
|
+
});
|
|
341
|
+
const hits = table(
|
|
342
|
+
n("hits"),
|
|
343
|
+
{
|
|
344
|
+
documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
|
|
345
|
+
day: date("day").notNull(),
|
|
346
|
+
source: text("source").notNull().default("rest"),
|
|
347
|
+
count: integer("count").notNull().default(0)
|
|
348
|
+
},
|
|
349
|
+
(t) => ({ pk: primaryKey({ columns: [t.documentId, t.day, t.source] }), dayIdx: index(n("hits_day_idx")).on(t.day) })
|
|
350
|
+
);
|
|
351
|
+
const meta = table(n("meta"), {
|
|
352
|
+
key: text("key").primaryKey(),
|
|
353
|
+
value: jsonb("value"),
|
|
354
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
|
|
355
|
+
});
|
|
356
|
+
const audit = table(
|
|
357
|
+
n("audit"),
|
|
358
|
+
{
|
|
359
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
360
|
+
at: timestamp("at", { withTimezone: true }).notNull().defaultNow(),
|
|
361
|
+
actorKind: text("actor_kind").notNull(),
|
|
362
|
+
actorId: text("actor_id"),
|
|
363
|
+
actorLabel: text("actor_label").notNull(),
|
|
364
|
+
action: text("action").notNull(),
|
|
365
|
+
collection: text("collection"),
|
|
366
|
+
slug: text("slug"),
|
|
367
|
+
version: integer("version"),
|
|
368
|
+
outcome: text("outcome").notNull(),
|
|
369
|
+
via: text("via"),
|
|
370
|
+
detail: jsonb("detail").$type().notNull().default({})
|
|
371
|
+
},
|
|
372
|
+
(t) => ({ atIdx: index(n("audit_at_idx")).on(t.at), actionIdx: index(n("audit_action_idx")).on(t.action, t.at) })
|
|
373
|
+
);
|
|
374
|
+
return { documents, versions, apiKeys, hits, meta, audit, options: { prefix, schema: o.schema ?? null } };
|
|
375
|
+
}
|
|
376
|
+
var defaultTables = cmsTables();
|
|
377
|
+
var cmsDocuments = defaultTables.documents;
|
|
378
|
+
var cmsVersions = defaultTables.versions;
|
|
379
|
+
var cmsApiKeys = defaultTables.apiKeys;
|
|
380
|
+
var cmsHits = defaultTables.hits;
|
|
381
|
+
var cmsMeta = defaultTables.meta;
|
|
382
|
+
var cmsAudit = defaultTables.audit;
|
|
383
|
+
function names(t) {
|
|
384
|
+
const o = t && "options" in t ? t.options : t ?? {};
|
|
385
|
+
const prefix = o.prefix ?? "cms_";
|
|
386
|
+
const schema = o.schema ?? null;
|
|
387
|
+
const q = (s) => `"${s}"`;
|
|
388
|
+
const tbl = (s) => schema ? `${q(schema)}.${q(prefix + s)}` : q(prefix + s);
|
|
389
|
+
const idx = (s) => q(prefix + s);
|
|
390
|
+
return { prefix, schema, tbl, idx, q };
|
|
391
|
+
}
|
|
392
|
+
function upgradeSteps(t) {
|
|
393
|
+
const { tbl, idx } = names(t);
|
|
394
|
+
return [
|
|
395
|
+
{
|
|
396
|
+
version: 2,
|
|
397
|
+
name: "agent-cms 0.6.0: autosave, republished_at, version changes and reviews, key expiry, hit source, audit log",
|
|
398
|
+
sql: `
|
|
399
|
+
ALTER TABLE ${tbl("documents")} ADD COLUMN IF NOT EXISTS "republished_at" timestamptz;
|
|
400
|
+
ALTER TABLE ${tbl("documents")} ADD COLUMN IF NOT EXISTS "autosave" jsonb;
|
|
401
|
+
ALTER TABLE ${tbl("documents")} ADD COLUMN IF NOT EXISTS "autosave_at" timestamptz;
|
|
402
|
+
ALTER TABLE ${tbl("documents")} ADD COLUMN IF NOT EXISTS "autosave_by" text;
|
|
403
|
+
ALTER TABLE ${tbl("documents")} ADD COLUMN IF NOT EXISTS "autosave_base_version" integer;
|
|
404
|
+
ALTER TABLE ${tbl("versions")} ADD COLUMN IF NOT EXISTS "changed" jsonb;
|
|
405
|
+
ALTER TABLE ${tbl("versions")} ADD COLUMN IF NOT EXISTS "reviewed" jsonb NOT NULL DEFAULT '[]'::jsonb;
|
|
406
|
+
ALTER TABLE ${tbl("api_keys")} ADD COLUMN IF NOT EXISTS "expires_at" timestamptz;
|
|
407
|
+
ALTER TABLE ${tbl("hits")} ADD COLUMN IF NOT EXISTS "source" text NOT NULL DEFAULT 'rest';
|
|
408
|
+
DO $$ BEGIN
|
|
409
|
+
IF EXISTS (
|
|
410
|
+
SELECT 1 FROM pg_constraint c
|
|
411
|
+
WHERE c.conrelid = '${tbl("hits").replace(/'/g, "''")}'::regclass AND c.contype = 'p' AND array_length(c.conkey, 1) = 2
|
|
412
|
+
) THEN
|
|
413
|
+
EXECUTE (SELECT 'ALTER TABLE ${tbl("hits").replace(/'/g, "''")} DROP CONSTRAINT ' || quote_ident(conname) FROM pg_constraint WHERE conrelid = '${tbl("hits").replace(/'/g, "''")}'::regclass AND contype = 'p');
|
|
414
|
+
ALTER TABLE ${tbl("hits")} ADD PRIMARY KEY ("document_id", "day", "source");
|
|
415
|
+
END IF;
|
|
416
|
+
END $$;
|
|
417
|
+
CREATE INDEX IF NOT EXISTS ${idx("hits_day_idx")} ON ${tbl("hits")} ("day");
|
|
418
|
+
CREATE TABLE IF NOT EXISTS ${tbl("audit")} (
|
|
419
|
+
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
420
|
+
"at" timestamptz NOT NULL DEFAULT now(),
|
|
421
|
+
"actor_kind" text NOT NULL,
|
|
422
|
+
"actor_id" text,
|
|
423
|
+
"actor_label" text NOT NULL,
|
|
424
|
+
"action" text NOT NULL,
|
|
425
|
+
"collection" text,
|
|
426
|
+
"slug" text,
|
|
427
|
+
"version" integer,
|
|
428
|
+
"outcome" text NOT NULL,
|
|
429
|
+
"via" text,
|
|
430
|
+
"detail" jsonb NOT NULL DEFAULT '{}'::jsonb
|
|
431
|
+
);
|
|
432
|
+
CREATE INDEX IF NOT EXISTS ${idx("audit_at_idx")} ON ${tbl("audit")} ("at");
|
|
433
|
+
CREATE INDEX IF NOT EXISTS ${idx("audit_action_idx")} ON ${tbl("audit")} ("action", "at");`.trim()
|
|
434
|
+
}
|
|
435
|
+
];
|
|
436
|
+
}
|
|
437
|
+
function schemaVersionSql(t, version = SCHEMA_VERSION) {
|
|
438
|
+
const { tbl } = names(t);
|
|
439
|
+
return `INSERT INTO ${tbl("meta")} ("key", "value") VALUES ('schema_version', '${version}'::jsonb) ON CONFLICT ("key") DO UPDATE SET "value" = EXCLUDED."value", "updated_at" = now();`;
|
|
440
|
+
}
|
|
441
|
+
function cmsDdl(t) {
|
|
442
|
+
const { tbl, idx, schema, q } = names(t);
|
|
443
|
+
const create = `
|
|
444
|
+
${schema ? `CREATE SCHEMA IF NOT EXISTS ${q(schema)};
|
|
445
|
+
` : ""}CREATE TABLE IF NOT EXISTS ${tbl("documents")} (
|
|
446
|
+
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
447
|
+
"collection" text NOT NULL,
|
|
448
|
+
"slug" text NOT NULL,
|
|
449
|
+
"status" text NOT NULL DEFAULT 'draft',
|
|
450
|
+
"title" text NOT NULL,
|
|
451
|
+
"summary" text NOT NULL DEFAULT '',
|
|
452
|
+
"body" text NOT NULL DEFAULT '',
|
|
453
|
+
"category" text,
|
|
454
|
+
"keywords" jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
455
|
+
"fields" jsonb NOT NULL DEFAULT '{}'::jsonb,
|
|
456
|
+
"version" integer NOT NULL DEFAULT 1,
|
|
457
|
+
"published_version" integer,
|
|
458
|
+
"published" jsonb,
|
|
459
|
+
"updated_by" text,
|
|
460
|
+
"updated_by_kind" text,
|
|
461
|
+
"published_at" timestamptz,
|
|
462
|
+
"created_at" timestamptz NOT NULL DEFAULT now(),
|
|
463
|
+
"updated_at" timestamptz NOT NULL DEFAULT now()
|
|
464
|
+
);
|
|
465
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${idx("documents_collection_slug_idx")} ON ${tbl("documents")} ("collection", "slug");
|
|
466
|
+
CREATE INDEX IF NOT EXISTS ${idx("documents_collection_status_idx")} ON ${tbl("documents")} ("collection", "status");
|
|
467
|
+
|
|
468
|
+
CREATE TABLE IF NOT EXISTS ${tbl("versions")} (
|
|
469
|
+
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
470
|
+
"document_id" uuid NOT NULL REFERENCES ${tbl("documents")}("id") ON DELETE CASCADE,
|
|
471
|
+
"version" integer NOT NULL,
|
|
472
|
+
"snapshot" jsonb NOT NULL,
|
|
473
|
+
"author_kind" text NOT NULL,
|
|
474
|
+
"author_id" text,
|
|
475
|
+
"author_label" text NOT NULL,
|
|
476
|
+
"note" text,
|
|
477
|
+
"created_at" timestamptz NOT NULL DEFAULT now()
|
|
478
|
+
);
|
|
479
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${idx("versions_doc_version_idx")} ON ${tbl("versions")} ("document_id", "version");
|
|
480
|
+
|
|
481
|
+
CREATE TABLE IF NOT EXISTS ${tbl("api_keys")} (
|
|
482
|
+
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
483
|
+
"name" text NOT NULL,
|
|
484
|
+
"prefix" text NOT NULL,
|
|
485
|
+
"hash" text NOT NULL UNIQUE,
|
|
486
|
+
"scopes" jsonb NOT NULL,
|
|
487
|
+
"collections" jsonb,
|
|
488
|
+
"created_by" text,
|
|
489
|
+
"last_used_at" timestamptz,
|
|
490
|
+
"revoked_at" timestamptz,
|
|
491
|
+
"created_at" timestamptz NOT NULL DEFAULT now()
|
|
492
|
+
);
|
|
493
|
+
|
|
494
|
+
CREATE TABLE IF NOT EXISTS ${tbl("hits")} (
|
|
495
|
+
"document_id" uuid NOT NULL REFERENCES ${tbl("documents")}("id") ON DELETE CASCADE,
|
|
496
|
+
"day" date NOT NULL,
|
|
497
|
+
"source" text NOT NULL DEFAULT 'rest',
|
|
498
|
+
"count" integer NOT NULL DEFAULT 0,
|
|
499
|
+
PRIMARY KEY ("document_id", "day", "source")
|
|
500
|
+
);
|
|
501
|
+
|
|
502
|
+
CREATE TABLE IF NOT EXISTS ${tbl("meta")} (
|
|
503
|
+
"key" text PRIMARY KEY,
|
|
504
|
+
"value" jsonb,
|
|
505
|
+
"updated_at" timestamptz NOT NULL DEFAULT now()
|
|
506
|
+
);`.trim();
|
|
507
|
+
return [create, ...upgradeSteps(t).map((s) => s.sql), schemaVersionSql(t)].join("\n\n");
|
|
508
|
+
}
|
|
509
|
+
function splitSql(text2) {
|
|
510
|
+
const out = [];
|
|
511
|
+
let cur = "";
|
|
512
|
+
let i = 0;
|
|
513
|
+
let dollar = null;
|
|
514
|
+
let quote = false;
|
|
515
|
+
while (i < text2.length) {
|
|
516
|
+
const c = text2[i];
|
|
517
|
+
if (dollar) {
|
|
518
|
+
if (text2.startsWith(dollar, i)) {
|
|
519
|
+
cur += dollar;
|
|
520
|
+
i += dollar.length;
|
|
521
|
+
dollar = null;
|
|
522
|
+
} else cur += text2[i++];
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
if (quote) {
|
|
526
|
+
cur += c;
|
|
527
|
+
i++;
|
|
528
|
+
if (c === "'") quote = false;
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
if (c === "-" && text2[i + 1] === "-") {
|
|
532
|
+
const nl = text2.indexOf("\n", i);
|
|
533
|
+
i = nl < 0 ? text2.length : nl + 1;
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
if (c === "'") quote = true;
|
|
537
|
+
if (c === "$") {
|
|
538
|
+
const m = /^\$[a-zA-Z_]*\$/.exec(text2.slice(i));
|
|
539
|
+
if (m) {
|
|
540
|
+
dollar = m[0];
|
|
541
|
+
cur += m[0];
|
|
542
|
+
i += m[0].length;
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (c === ";") {
|
|
547
|
+
if (cur.trim()) out.push(cur.trim());
|
|
548
|
+
cur = "";
|
|
549
|
+
i++;
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
cur += c;
|
|
553
|
+
i++;
|
|
554
|
+
}
|
|
555
|
+
if (cur.trim()) out.push(cur.trim());
|
|
556
|
+
return out;
|
|
557
|
+
}
|
|
558
|
+
var LEGACY_COLUMNS = [
|
|
559
|
+
{ table: "documents", column: "covers" },
|
|
560
|
+
{ table: "documents", column: "needs_review" },
|
|
561
|
+
{ table: "documents", column: "review_reason" },
|
|
562
|
+
{ table: "documents", column: "pending_pr" },
|
|
563
|
+
{ table: "versions", column: "pr" }
|
|
564
|
+
];
|
|
565
|
+
|
|
566
|
+
// src/drizzle-repo.ts
|
|
567
|
+
var iso = (d) => d == null ? null : typeof d === "string" ? new Date(d).toISOString() : d.toISOString();
|
|
568
|
+
var date2 = (s) => s == null ? null : new Date(s);
|
|
569
|
+
async function uniq(p, slug) {
|
|
570
|
+
try {
|
|
571
|
+
return await p;
|
|
572
|
+
} catch (e) {
|
|
573
|
+
const err = e;
|
|
574
|
+
if (err?.code === "23505" || err?.cause?.code === "23505") throw new CmsError("slug_taken", { slug: slug ?? "" });
|
|
575
|
+
throw e;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
var DrizzleRepo = class _DrizzleRepo {
|
|
579
|
+
constructor(db, o = {}) {
|
|
580
|
+
this.db = db;
|
|
581
|
+
this.t = o.tables ?? defaultTables;
|
|
582
|
+
}
|
|
583
|
+
db;
|
|
584
|
+
t;
|
|
585
|
+
toDoc(r) {
|
|
586
|
+
return {
|
|
587
|
+
id: r.id,
|
|
588
|
+
collection: r.collection,
|
|
589
|
+
slug: r.slug,
|
|
590
|
+
status: r.status,
|
|
591
|
+
title: r.title,
|
|
592
|
+
summary: r.summary,
|
|
593
|
+
body: r.body,
|
|
594
|
+
category: r.category,
|
|
595
|
+
keywords: r.keywords ?? [],
|
|
596
|
+
fields: r.fields ?? {},
|
|
597
|
+
version: r.version,
|
|
598
|
+
publishedVersion: r.publishedVersion,
|
|
599
|
+
published: r.published ?? null,
|
|
600
|
+
publishedAt: iso(r.publishedAt),
|
|
601
|
+
republishedAt: iso(r.republishedAt),
|
|
602
|
+
createdAt: iso(r.createdAt),
|
|
603
|
+
updatedAt: iso(r.updatedAt),
|
|
604
|
+
updatedBy: r.updatedBy,
|
|
605
|
+
updatedByKind: r.updatedByKind ?? null,
|
|
606
|
+
autosave: r.autosave ? { content: r.autosave, at: iso(r.autosaveAt), by: r.autosaveBy, baseVersion: r.autosaveBaseVersion ?? r.version } : null
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
patchRow(p) {
|
|
610
|
+
const out = {};
|
|
611
|
+
for (const [k, v] of Object.entries(p)) {
|
|
612
|
+
if (v === void 0) continue;
|
|
613
|
+
if (k === "publishedAt" || k === "updatedAt" || k === "republishedAt") out[k] = date2(v);
|
|
614
|
+
else if (k === "autosave") {
|
|
615
|
+
const a = v;
|
|
616
|
+
out.autosave = a?.content ?? null;
|
|
617
|
+
out.autosaveAt = a ? new Date(a.at) : null;
|
|
618
|
+
out.autosaveBy = a?.by ?? null;
|
|
619
|
+
out.autosaveBaseVersion = a?.baseVersion ?? null;
|
|
620
|
+
} else out[k] = v;
|
|
621
|
+
}
|
|
622
|
+
return out;
|
|
623
|
+
}
|
|
624
|
+
toVersion(r) {
|
|
625
|
+
return {
|
|
626
|
+
id: r.id,
|
|
627
|
+
documentId: r.documentId,
|
|
628
|
+
version: r.version,
|
|
629
|
+
snapshot: r.snapshot,
|
|
630
|
+
authorKind: r.authorKind,
|
|
631
|
+
authorId: r.authorId,
|
|
632
|
+
authorLabel: r.authorLabel,
|
|
633
|
+
note: r.note,
|
|
634
|
+
changed: r.changed ?? null,
|
|
635
|
+
reviewed: r.reviewed ?? [],
|
|
636
|
+
createdAt: iso(r.createdAt)
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
toKey(r) {
|
|
640
|
+
return {
|
|
641
|
+
id: r.id,
|
|
642
|
+
name: r.name,
|
|
643
|
+
prefix: r.prefix,
|
|
644
|
+
hash: r.hash,
|
|
645
|
+
scopes: r.scopes,
|
|
646
|
+
collections: r.collections ?? null,
|
|
647
|
+
createdBy: r.createdBy,
|
|
648
|
+
lastUsedAt: iso(r.lastUsedAt),
|
|
649
|
+
revokedAt: iso(r.revokedAt),
|
|
650
|
+
expiresAt: iso(r.expiresAt),
|
|
651
|
+
createdAt: iso(r.createdAt)
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
tx(fn) {
|
|
655
|
+
return this.db.transaction((t) => fn(new _DrizzleRepo(t, { tables: this.t })));
|
|
656
|
+
}
|
|
657
|
+
async findDoc(collection, slug) {
|
|
658
|
+
const D = this.t.documents;
|
|
659
|
+
const [r] = await this.db.select().from(D).where(and(eq(D.collection, collection), eq(D.slug, slug))).limit(1);
|
|
660
|
+
return r ? this.toDoc(r) : null;
|
|
661
|
+
}
|
|
662
|
+
async findDocById(id) {
|
|
663
|
+
const D = this.t.documents;
|
|
664
|
+
const [r] = await this.db.select().from(D).where(eq(D.id, id)).limit(1);
|
|
665
|
+
return r ? this.toDoc(r) : null;
|
|
666
|
+
}
|
|
667
|
+
async listDocs(f) {
|
|
668
|
+
const D = this.t.documents;
|
|
669
|
+
const conds = [];
|
|
670
|
+
if (f.collection) conds.push(eq(D.collection, f.collection));
|
|
671
|
+
if (f.statuses) conds.push(inArray(D.status, f.statuses));
|
|
672
|
+
if (f.published === true) conds.push(isNotNull(D.publishedVersion), ne(D.status, "archived"));
|
|
673
|
+
const rows = await this.db.select().from(D).where(conds.length ? and(...conds) : void 0);
|
|
674
|
+
const docs = rows.map((r) => this.toDoc(r));
|
|
675
|
+
return f.published === false ? docs.filter((d) => d.publishedVersion === null || d.status === "archived") : docs;
|
|
676
|
+
}
|
|
677
|
+
async insertDoc(doc) {
|
|
678
|
+
const [r] = await uniq(
|
|
679
|
+
this.db.insert(this.t.documents).values({
|
|
680
|
+
...this.patchRow(doc),
|
|
681
|
+
...doc.id ? { id: doc.id } : {},
|
|
682
|
+
collection: doc.collection,
|
|
683
|
+
slug: doc.slug,
|
|
684
|
+
title: doc.title,
|
|
685
|
+
createdAt: date2(doc.createdAt ?? null) ?? void 0
|
|
686
|
+
}).returning(),
|
|
687
|
+
doc.slug
|
|
688
|
+
);
|
|
689
|
+
return this.toDoc(r);
|
|
690
|
+
}
|
|
691
|
+
async updateDoc(id, p, expectedVersion) {
|
|
692
|
+
const D = this.t.documents;
|
|
693
|
+
const where = expectedVersion === void 0 ? eq(D.id, id) : and(eq(D.id, id), eq(D.version, expectedVersion));
|
|
694
|
+
const [r] = await uniq(
|
|
695
|
+
this.db.update(D).set({ ...this.patchRow(p), updatedAt: date2(p.updatedAt ?? null) ?? /* @__PURE__ */ new Date() }).where(where).returning(),
|
|
696
|
+
p.slug
|
|
697
|
+
);
|
|
698
|
+
return r ? this.toDoc(r) : null;
|
|
699
|
+
}
|
|
700
|
+
async deleteDoc(id) {
|
|
701
|
+
await this.db.delete(this.t.documents).where(eq(this.t.documents.id, id));
|
|
702
|
+
}
|
|
703
|
+
async insertVersion(v) {
|
|
704
|
+
await uniq(
|
|
705
|
+
this.db.insert(this.t.versions).values({
|
|
706
|
+
documentId: v.documentId,
|
|
707
|
+
version: v.version,
|
|
708
|
+
snapshot: v.snapshot,
|
|
709
|
+
authorKind: v.authorKind,
|
|
710
|
+
authorId: v.authorId,
|
|
711
|
+
authorLabel: v.authorLabel,
|
|
712
|
+
note: v.note,
|
|
713
|
+
changed: v.changed ?? null,
|
|
714
|
+
createdAt: date2(v.createdAt ?? null) ?? void 0
|
|
715
|
+
})
|
|
716
|
+
);
|
|
717
|
+
}
|
|
718
|
+
async listVersions(documentId) {
|
|
719
|
+
const V = this.t.versions;
|
|
720
|
+
const rows = await this.db.select().from(V).where(eq(V.documentId, documentId)).orderBy(desc(V.version));
|
|
721
|
+
return rows.map((r) => this.toVersion(r));
|
|
722
|
+
}
|
|
723
|
+
async getVersion(documentId, version) {
|
|
724
|
+
const V = this.t.versions;
|
|
725
|
+
const [r] = await this.db.select().from(V).where(and(eq(V.documentId, documentId), eq(V.version, version))).limit(1);
|
|
726
|
+
return r ? this.toVersion(r) : null;
|
|
727
|
+
}
|
|
728
|
+
async setVersionReviewed(documentId, version, reviewed) {
|
|
729
|
+
const V = this.t.versions;
|
|
730
|
+
await this.db.update(V).set({ reviewed }).where(and(eq(V.documentId, documentId), eq(V.version, version)));
|
|
731
|
+
}
|
|
732
|
+
async pruneVersions(documentId, keep, protect) {
|
|
733
|
+
const V = this.t.versions;
|
|
734
|
+
const rows = await this.db.select({ id: V.id, version: V.version }).from(V).where(eq(V.documentId, documentId)).orderBy(desc(V.version));
|
|
735
|
+
const drop = rows.slice(keep).filter((r) => !protect.includes(r.version)).map((r) => r.id);
|
|
736
|
+
if (drop.length) await this.db.delete(V).where(inArray(V.id, drop));
|
|
737
|
+
}
|
|
738
|
+
async insertKey(k) {
|
|
739
|
+
const [r] = await this.db.insert(this.t.apiKeys).values({ ...k, expiresAt: date2(k.expiresAt) }).returning();
|
|
740
|
+
return this.toKey(r);
|
|
741
|
+
}
|
|
742
|
+
async listKeys() {
|
|
743
|
+
return (await this.db.select().from(this.t.apiKeys)).map((r) => this.toKey(r));
|
|
744
|
+
}
|
|
745
|
+
async findKeyByHash(hash) {
|
|
746
|
+
const K = this.t.apiKeys;
|
|
747
|
+
const [r] = await this.db.select().from(K).where(eq(K.hash, hash)).limit(1);
|
|
748
|
+
return r ? this.toKey(r) : null;
|
|
749
|
+
}
|
|
750
|
+
async touchKey(id, at) {
|
|
751
|
+
const K = this.t.apiKeys;
|
|
752
|
+
await this.db.update(K).set({ lastUsedAt: new Date(at) }).where(eq(K.id, id));
|
|
753
|
+
}
|
|
754
|
+
async revokeKey(id, at) {
|
|
755
|
+
const K = this.t.apiKeys;
|
|
756
|
+
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 });
|
|
757
|
+
return rows.length > 0;
|
|
758
|
+
}
|
|
759
|
+
async addHits(ids, day, source) {
|
|
760
|
+
if (!ids.length) return;
|
|
761
|
+
const H = this.t.hits;
|
|
762
|
+
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` } });
|
|
763
|
+
}
|
|
764
|
+
async hitCounts(sinceDay, collection) {
|
|
765
|
+
const H = this.t.hits;
|
|
766
|
+
const D = this.t.documents;
|
|
767
|
+
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);
|
|
768
|
+
return new Map(rows.map((r) => [r.id, Number(r.n)]));
|
|
769
|
+
}
|
|
770
|
+
async insertAudit(e) {
|
|
771
|
+
await this.db.insert(this.t.audit).values({ ...e, at: new Date(e.at) });
|
|
772
|
+
}
|
|
773
|
+
async listAudit(q) {
|
|
774
|
+
const A = this.t.audit;
|
|
775
|
+
const conds = [];
|
|
776
|
+
if (q.before) {
|
|
777
|
+
const [at, id] = q.before.split("|");
|
|
778
|
+
conds.push(or(lt(A.at, new Date(at)), and(eq(A.at, new Date(at)), lt(A.id, id))));
|
|
779
|
+
}
|
|
780
|
+
if (q.action) conds.push(eq(A.action, q.action));
|
|
781
|
+
if (q.outcome) conds.push(eq(A.outcome, q.outcome));
|
|
782
|
+
if (q.actorKind) conds.push(eq(A.actorKind, q.actorKind));
|
|
783
|
+
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);
|
|
784
|
+
return rows.map((r) => ({
|
|
785
|
+
id: r.id,
|
|
786
|
+
at: iso(r.at),
|
|
787
|
+
actorKind: r.actorKind,
|
|
788
|
+
actorId: r.actorId,
|
|
789
|
+
actorLabel: r.actorLabel,
|
|
790
|
+
action: r.action,
|
|
791
|
+
collection: r.collection,
|
|
792
|
+
slug: r.slug,
|
|
793
|
+
version: r.version,
|
|
794
|
+
outcome: r.outcome,
|
|
795
|
+
via: r.via ?? null,
|
|
796
|
+
detail: r.detail ?? {}
|
|
797
|
+
}));
|
|
798
|
+
}
|
|
799
|
+
async changeStamp() {
|
|
800
|
+
const D = this.t.documents;
|
|
801
|
+
const [r] = await this.db.select({ n: sql`count(*)::int`, max: sql`max(${D.updatedAt})::text` }).from(D);
|
|
802
|
+
return `${r?.n ?? 0}:${r?.max ?? ""}`;
|
|
803
|
+
}
|
|
804
|
+
async getMeta(key) {
|
|
805
|
+
const M = this.t.meta;
|
|
806
|
+
try {
|
|
807
|
+
const [r] = await this.db.select().from(M).where(eq(M.key, key)).limit(1);
|
|
808
|
+
return r?.value ?? null;
|
|
809
|
+
} catch (e) {
|
|
810
|
+
if (e?.code === "42P01" || e?.cause?.code === "42P01") return null;
|
|
811
|
+
throw e;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
async setMeta(key, value) {
|
|
815
|
+
const M = this.t.meta;
|
|
816
|
+
await this.db.insert(M).values({ key, value }).onConflictDoUpdate({ target: M.key, set: { value, updatedAt: /* @__PURE__ */ new Date() } });
|
|
817
|
+
}
|
|
818
|
+
// ── doctor ────────────────────────────────────────────────────────────────
|
|
819
|
+
/** Raw rows of a SQL query, across drivers (node-postgres returns `{ rows }`, pglite too, postgres.js an array). */
|
|
820
|
+
async rows(q) {
|
|
821
|
+
const r = await this.db.execute(q);
|
|
822
|
+
return Array.isArray(r) ? r : r.rows ?? [];
|
|
823
|
+
}
|
|
824
|
+
/** What `agent-cms doctor` checks. Read-only. */
|
|
825
|
+
async inspect() {
|
|
826
|
+
const { prefix, schema } = this.t.options;
|
|
827
|
+
const sch = schema ?? null;
|
|
828
|
+
const cols = await this.rows(
|
|
829
|
+
sql`select table_name, column_name from information_schema.columns where table_schema = coalesce(${sch}, current_schema()) and table_name like ${prefix.replace(/_/g, "\\_") + "%"}`
|
|
830
|
+
);
|
|
831
|
+
const have = /* @__PURE__ */ new Map();
|
|
832
|
+
for (const c of cols) {
|
|
833
|
+
if (!have.has(c.table_name)) have.set(c.table_name, /* @__PURE__ */ new Set());
|
|
834
|
+
have.get(c.table_name).add(c.column_name);
|
|
835
|
+
}
|
|
836
|
+
const expected = {};
|
|
837
|
+
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 })) {
|
|
838
|
+
expected[prefix + key] = Object.values(tbl).filter((c) => c && typeof c === "object" && "name" in c && "columnType" in c).map((c) => c.name);
|
|
839
|
+
}
|
|
840
|
+
const missingTables = Object.keys(expected).filter((t) => !have.has(t));
|
|
841
|
+
const missingColumns = Object.entries(expected).flatMap(([t, cs]) => have.has(t) ? cs.filter((c) => !have.get(t).has(c)).map((c) => `${t}.${c}`) : []);
|
|
842
|
+
const legacyColumns = LEGACY_COLUMNS.filter((l) => have.get(prefix + l.table)?.has(l.column)).map((l) => `${prefix}${l.table}.${l.column}`);
|
|
843
|
+
const gapsTable = have.has(`${prefix}gaps`);
|
|
844
|
+
let gapsRows = null;
|
|
845
|
+
if (gapsTable) {
|
|
846
|
+
const tbl = sch ? `"${sch}"."${prefix}gaps"` : `"${prefix}gaps"`;
|
|
847
|
+
const [r] = await this.rows(sql.raw(`select count(*)::int as n from ${tbl}`));
|
|
848
|
+
gapsRows = Number(r?.n ?? 0);
|
|
849
|
+
}
|
|
850
|
+
const found = missingTables.includes(`${prefix}meta`) ? null : await this.getMeta("schema_version");
|
|
851
|
+
let badPublished = 0;
|
|
852
|
+
let orphanVersions = 0;
|
|
853
|
+
if (!missingTables.length) {
|
|
854
|
+
const D = this.t.documents;
|
|
855
|
+
const V = this.t.versions;
|
|
856
|
+
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)`);
|
|
857
|
+
badPublished = Number(bp?.n ?? 0);
|
|
858
|
+
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})`);
|
|
859
|
+
orphanVersions = Number(ov?.n ?? 0);
|
|
860
|
+
}
|
|
861
|
+
return {
|
|
862
|
+
schemaVersion: typeof found === "number" ? found : found == null ? null : Number(found),
|
|
863
|
+
expectedSchemaVersion: SCHEMA_VERSION,
|
|
864
|
+
missingTables,
|
|
865
|
+
missingColumns,
|
|
866
|
+
legacyColumns,
|
|
867
|
+
gapsTable,
|
|
868
|
+
gapsRows,
|
|
869
|
+
badPublished,
|
|
870
|
+
orphanVersions
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
};
|
|
874
|
+
|
|
875
|
+
// src/frontmatter.ts
|
|
876
|
+
var DOC_KEYS = /* @__PURE__ */ new Set(["slug", "title", "summary", "category", "keywords"]);
|
|
877
|
+
function scalar(raw) {
|
|
878
|
+
const v = raw.trim();
|
|
879
|
+
if (v === "") return "";
|
|
880
|
+
if (v === "true") return true;
|
|
881
|
+
if (v === "false") return false;
|
|
882
|
+
if (v === "null" || v === "~") return null;
|
|
883
|
+
if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v);
|
|
884
|
+
if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) return v.slice(1, -1);
|
|
885
|
+
if (v.startsWith("[") && v.endsWith("]")) {
|
|
886
|
+
const inner = v.slice(1, -1).trim();
|
|
887
|
+
return inner ? splitOutsideQuotes(inner, ",").map((x) => scalar(x)) : [];
|
|
888
|
+
}
|
|
889
|
+
return v;
|
|
890
|
+
}
|
|
891
|
+
function splitOutsideQuotes(s, sep) {
|
|
892
|
+
const out = [];
|
|
893
|
+
let cur = "";
|
|
894
|
+
let q = null;
|
|
895
|
+
for (const ch of s) {
|
|
896
|
+
if (q) {
|
|
897
|
+
if (ch === q) q = null;
|
|
898
|
+
} else if (ch === '"' || ch === "'") q = ch;
|
|
899
|
+
else if (ch === sep) {
|
|
900
|
+
out.push(cur);
|
|
901
|
+
cur = "";
|
|
902
|
+
continue;
|
|
903
|
+
}
|
|
904
|
+
cur += ch;
|
|
905
|
+
}
|
|
906
|
+
out.push(cur);
|
|
907
|
+
return out;
|
|
908
|
+
}
|
|
909
|
+
function stripComment(line) {
|
|
910
|
+
let q = null;
|
|
911
|
+
for (let i = 0; i < line.length; i++) {
|
|
912
|
+
const ch = line[i];
|
|
913
|
+
if (q) {
|
|
914
|
+
if (ch === q) q = null;
|
|
915
|
+
} else if (ch === '"' || ch === "'") q = ch;
|
|
916
|
+
else if (ch === "#" && (i === 0 || /\s/.test(line[i - 1]))) return line.slice(0, i).trimEnd();
|
|
917
|
+
}
|
|
918
|
+
return line;
|
|
919
|
+
}
|
|
920
|
+
function parseFrontmatter(text2) {
|
|
921
|
+
const src = text2.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
|
|
922
|
+
const m = /^---\n([\s\S]*?)\n---\n?/.exec(src);
|
|
923
|
+
if (!m) return { data: {}, body: src.trim() };
|
|
924
|
+
const data = {};
|
|
925
|
+
for (const line of m[1].split("\n")) {
|
|
926
|
+
const t = stripComment(line);
|
|
927
|
+
if (!t.trim()) continue;
|
|
928
|
+
const i = t.indexOf(":");
|
|
929
|
+
if (i < 1) throw new Error(`frontmatter: cannot read line "${line}"`);
|
|
930
|
+
data[t.slice(0, i).trim()] = scalar(t.slice(i + 1));
|
|
931
|
+
}
|
|
932
|
+
return { data, body: src.slice(m[0].length).trim() };
|
|
933
|
+
}
|
|
934
|
+
function docFromMarkdown(text2, fallbackSlug) {
|
|
935
|
+
const { data, body } = parseFrontmatter(text2);
|
|
936
|
+
const fields = {};
|
|
937
|
+
for (const [k, v] of Object.entries(data)) if (!DOC_KEYS.has(k)) fields[k] = v;
|
|
938
|
+
const doc = { body };
|
|
939
|
+
const slug = data.slug ?? fallbackSlug;
|
|
940
|
+
if (slug) doc.slug = String(slug);
|
|
941
|
+
if (data.title !== void 0) doc.title = String(data.title);
|
|
942
|
+
if (data.summary !== void 0) doc.summary = String(data.summary);
|
|
943
|
+
if (data.category !== void 0) doc.category = data.category === null ? null : String(data.category);
|
|
944
|
+
if (Array.isArray(data.keywords)) doc.keywords = data.keywords.map(String);
|
|
945
|
+
if (Object.keys(fields).length) doc.fields = fields;
|
|
946
|
+
return doc;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// src/registry.ts
|
|
950
|
+
import { createHash } from "crypto";
|
|
951
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
952
|
+
import { basename, dirname, join, relative, resolve } from "path";
|
|
953
|
+
import { fileURLToPath } from "url";
|
|
954
|
+
|
|
955
|
+
// src/diff.ts
|
|
956
|
+
function diffSeq(a, b, eq2 = Object.is) {
|
|
957
|
+
let start = 0;
|
|
958
|
+
while (start < a.length && start < b.length && eq2(a[start], b[start])) start++;
|
|
959
|
+
let endA = a.length;
|
|
960
|
+
let endB = b.length;
|
|
961
|
+
while (endA > start && endB > start && eq2(a[endA - 1], b[endB - 1])) {
|
|
962
|
+
endA--;
|
|
963
|
+
endB--;
|
|
964
|
+
}
|
|
965
|
+
const A = a.slice(start, endA);
|
|
966
|
+
const B = b.slice(start, endB);
|
|
967
|
+
const n = A.length;
|
|
968
|
+
const m = B.length;
|
|
969
|
+
const max = n + m;
|
|
970
|
+
const v = /* @__PURE__ */ new Map([[1, 0]]);
|
|
971
|
+
const trace = [];
|
|
972
|
+
outer: for (let d = 0; d <= max; d++) {
|
|
973
|
+
trace.push(new Map(v));
|
|
974
|
+
for (let k = -d; k <= d; k += 2) {
|
|
975
|
+
let x2 = k === -d || k !== d && (v.get(k - 1) ?? -1) < (v.get(k + 1) ?? -1) ? v.get(k + 1) ?? 0 : (v.get(k - 1) ?? 0) + 1;
|
|
976
|
+
let y2 = x2 - k;
|
|
977
|
+
while (x2 < n && y2 < m && eq2(A[x2], B[y2])) {
|
|
978
|
+
x2++;
|
|
979
|
+
y2++;
|
|
980
|
+
}
|
|
981
|
+
v.set(k, x2);
|
|
982
|
+
if (x2 >= n && y2 >= m) break outer;
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
const mid = [];
|
|
986
|
+
let x = n;
|
|
987
|
+
let y = m;
|
|
988
|
+
for (let d = trace.length - 1; d >= 0 && (x > 0 || y > 0); d--) {
|
|
989
|
+
const vd = trace[d];
|
|
990
|
+
const k = x - y;
|
|
991
|
+
const prevK = k === -d || k !== d && (vd.get(k - 1) ?? -1) < (vd.get(k + 1) ?? -1) ? k + 1 : k - 1;
|
|
992
|
+
const prevX = vd.get(prevK) ?? 0;
|
|
993
|
+
const prevY = prevX - prevK;
|
|
994
|
+
while (x > prevX && y > prevY) {
|
|
995
|
+
x--;
|
|
996
|
+
y--;
|
|
997
|
+
mid.push({ t: "eq", a: x, b: y, v: A[x] });
|
|
998
|
+
}
|
|
999
|
+
if (d > 0) {
|
|
1000
|
+
if (x === prevX) {
|
|
1001
|
+
y--;
|
|
1002
|
+
mid.push({ t: "ins", a: x, b: y, v: B[y] });
|
|
1003
|
+
} else {
|
|
1004
|
+
x--;
|
|
1005
|
+
mid.push({ t: "del", a: x, b: y, v: A[x] });
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
mid.reverse();
|
|
1010
|
+
const out = [];
|
|
1011
|
+
for (let i = 0; i < start; i++) out.push({ t: "eq", a: i, b: i, v: a[i] });
|
|
1012
|
+
for (const o of mid) out.push({ ...o, a: o.a + start, b: o.b + start });
|
|
1013
|
+
for (let i = 0; i < a.length - endA; i++) out.push({ t: "eq", a: endA + i, b: endB + i, v: a[endA + i] });
|
|
1014
|
+
return out;
|
|
1015
|
+
}
|
|
1016
|
+
var splitLines = (s) => s === "" ? [] : s.replace(/\r\n?/g, "\n").split("\n");
|
|
1017
|
+
function diffLines(a, b) {
|
|
1018
|
+
return diffSeq(splitLines(a), splitLines(b));
|
|
1019
|
+
}
|
|
1020
|
+
function hunks(a, b, context = 3) {
|
|
1021
|
+
const ops = diffLines(a, b);
|
|
1022
|
+
const changed = ops.map((o, i) => o.t === "eq" ? -1 : i).filter((i) => i >= 0);
|
|
1023
|
+
if (!changed.length) return [];
|
|
1024
|
+
const groups = [];
|
|
1025
|
+
for (const i of changed) {
|
|
1026
|
+
const last = groups[groups.length - 1];
|
|
1027
|
+
if (last && i - last[1] <= context * 2 + 1) last[1] = i;
|
|
1028
|
+
else groups.push([i, i]);
|
|
1029
|
+
}
|
|
1030
|
+
return groups.map(([from, to]) => {
|
|
1031
|
+
const s = Math.max(0, from - context);
|
|
1032
|
+
const e = Math.min(ops.length - 1, to + context);
|
|
1033
|
+
const lines = [];
|
|
1034
|
+
const removed = [];
|
|
1035
|
+
const added = [];
|
|
1036
|
+
for (let i = s; i <= e; i++) {
|
|
1037
|
+
const o = ops[i];
|
|
1038
|
+
if (o.t === "eq") lines.push({ t: " ", v: o.v, a: o.a + 1, b: o.b + 1 });
|
|
1039
|
+
else if (o.t === "del") {
|
|
1040
|
+
lines.push({ t: "-", v: o.v, a: o.a + 1 });
|
|
1041
|
+
removed.push(o.v);
|
|
1042
|
+
} else {
|
|
1043
|
+
lines.push({ t: "+", v: o.v, b: o.b + 1 });
|
|
1044
|
+
added.push(o.v);
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
const first = ops[s];
|
|
1048
|
+
const aLines = lines.filter((l) => l.t !== "+").length;
|
|
1049
|
+
const bLines = lines.filter((l) => l.t !== "-").length;
|
|
1050
|
+
return { aStart: aLines ? first.a + 1 : first.a, aLines, bStart: bLines ? first.b + 1 : first.b, bLines, lines, removed, added };
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
function unifiedDiff(a, b, o = {}) {
|
|
1054
|
+
const hs = hunks(a, b, o.context ?? 3);
|
|
1055
|
+
if (!hs.length) return "";
|
|
1056
|
+
const out = [`--- ${o.from ?? "a"}`, `+++ ${o.to ?? "b"}`];
|
|
1057
|
+
for (const h of hs) {
|
|
1058
|
+
out.push(`@@ -${h.aStart},${h.aLines} +${h.bStart},${h.bLines} @@`);
|
|
1059
|
+
for (const l of h.lines) out.push(l.t + l.v);
|
|
1060
|
+
}
|
|
1061
|
+
return out.join("\n");
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// src/version.ts
|
|
1065
|
+
var VERSION = "0.6.1";
|
|
1066
|
+
|
|
1067
|
+
// src/registry.ts
|
|
1068
|
+
var sha = (s) => createHash("sha256").update(s).digest("hex");
|
|
1069
|
+
function findRegistryDir() {
|
|
1070
|
+
const here = typeof __dirname === "string" ? __dirname : dirname(fileURLToPath(import.meta.url));
|
|
1071
|
+
const candidates = [
|
|
1072
|
+
[join(here, "registry"), true],
|
|
1073
|
+
[join(here, "..", "dist", "registry"), true],
|
|
1074
|
+
[join(here, "..", "registry"), false]
|
|
1075
|
+
];
|
|
1076
|
+
for (const [dir, built] of candidates) if (existsSync(join(dir, "registry.json"))) return { dir, built };
|
|
1077
|
+
throw new Error("[agent-cms] registry not found (is the package built?)");
|
|
1078
|
+
}
|
|
1079
|
+
function loadRegistry(loc = findRegistryDir()) {
|
|
1080
|
+
const index2 = JSON.parse(readFileSync(join(loc.dir, "registry.json"), "utf8"));
|
|
1081
|
+
const root = loc.built ? loc.dir : resolve(loc.dir, "..");
|
|
1082
|
+
const items = index2.items.map((it) => {
|
|
1083
|
+
if (loc.built) {
|
|
1084
|
+
const full = JSON.parse(readFileSync(join(loc.dir, `${it.name}.json`), "utf8"));
|
|
1085
|
+
return full;
|
|
1086
|
+
}
|
|
1087
|
+
return { ...it, files: it.files.map((f) => ({ ...f, content: readFileSync(join(root, f.path), "utf8") })) };
|
|
1088
|
+
});
|
|
1089
|
+
return { ...index2, items };
|
|
1090
|
+
}
|
|
1091
|
+
function resolveItems(reg, names2) {
|
|
1092
|
+
const byName = new Map(reg.items.map((i) => [i.name, i]));
|
|
1093
|
+
const out = [];
|
|
1094
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1095
|
+
const visit = (n, from) => {
|
|
1096
|
+
const it = byName.get(n);
|
|
1097
|
+
if (!it) throw new Error(`[agent-cms] unknown item "${n}"${from ? ` (needed by ${from})` : ""}. Items: ${reg.items.map((i) => i.name).join(", ")}`);
|
|
1098
|
+
if (seen.has(n)) return;
|
|
1099
|
+
seen.add(n);
|
|
1100
|
+
for (const d of it.registryDependencies ?? []) if (byName.has(d)) visit(d, n);
|
|
1101
|
+
out.push(it);
|
|
1102
|
+
};
|
|
1103
|
+
for (const n of names2) visit(n);
|
|
1104
|
+
return out;
|
|
1105
|
+
}
|
|
1106
|
+
function shadcnParts(reg, items) {
|
|
1107
|
+
const own = new Set(reg.items.map((i) => i.name));
|
|
1108
|
+
return [...new Set(items.flatMap((i) => i.registryDependencies ?? []).filter((d) => !own.has(d)))].sort();
|
|
1109
|
+
}
|
|
1110
|
+
function aliasToDir(cwd, alias) {
|
|
1111
|
+
let base = ".";
|
|
1112
|
+
for (const f of ["tsconfig.json", "jsconfig.json"]) {
|
|
1113
|
+
const p = join(cwd, f);
|
|
1114
|
+
if (!existsSync(p)) continue;
|
|
1115
|
+
try {
|
|
1116
|
+
const text2 = readFileSync(p, "utf8").replace(/\/\*[\s\S]*?\*\/|(^|[^:])\/\/.*$/gm, "$1").replace(/,(\s*[}\]])/g, "$1");
|
|
1117
|
+
const paths = JSON.parse(text2).compilerOptions?.paths ?? {};
|
|
1118
|
+
const target = paths["@/*"]?.[0];
|
|
1119
|
+
if (target) base = target.replace(/\/\*$/, "");
|
|
1120
|
+
} catch {
|
|
1121
|
+
}
|
|
1122
|
+
break;
|
|
1123
|
+
}
|
|
1124
|
+
return alias.startsWith("@/") ? resolve(cwd, base, alias.slice(2)) : resolve(cwd, alias);
|
|
1125
|
+
}
|
|
1126
|
+
function appLayout(cwd, o = {}) {
|
|
1127
|
+
const cj = join(cwd, "components.json");
|
|
1128
|
+
if (!existsSync(cj)) throw new Error("[agent-cms] components.json not found. The admin screens use your shadcn/ui parts: run `npx shadcn@latest init` first.");
|
|
1129
|
+
const aliases = JSON.parse(readFileSync(cj, "utf8")).aliases ?? {};
|
|
1130
|
+
const components = aliases.components ?? "@/components";
|
|
1131
|
+
const ui = aliases.ui ?? `${components}/ui`;
|
|
1132
|
+
const utils = aliases.utils ?? "@/lib/utils";
|
|
1133
|
+
return { dir: o.dir ? resolve(cwd, o.dir) : join(aliasToDir(cwd, components), "cms"), uiDir: aliasToDir(cwd, ui), aliases: { ui, utils } };
|
|
1134
|
+
}
|
|
1135
|
+
function rewriteImports(content, aliases) {
|
|
1136
|
+
return content.replace(/(["'])@\/components\/ui\//g, `$1${aliases.ui}/`).replace(/(["'])@\/lib\/utils(["'])/g, `$1${aliases.utils}$2`);
|
|
1137
|
+
}
|
|
1138
|
+
var LOCK_FILE = "agent-cms.json";
|
|
1139
|
+
function readLock(cwd) {
|
|
1140
|
+
const p = join(cwd, LOCK_FILE);
|
|
1141
|
+
if (!existsSync(p)) return { version: VERSION, files: {} };
|
|
1142
|
+
return JSON.parse(readFileSync(p, "utf8"));
|
|
1143
|
+
}
|
|
1144
|
+
function addItems(o) {
|
|
1145
|
+
const reg = o.registry ?? loadRegistry();
|
|
1146
|
+
const layout = appLayout(o.cwd, { dir: o.dir });
|
|
1147
|
+
const lock = readLock(o.cwd);
|
|
1148
|
+
const names2 = o.items.length ? o.items : o.mode === "add" ? [] : [...new Set(Object.values(lock.files).map((f) => f.item))];
|
|
1149
|
+
if (!names2.length) throw new Error(`[agent-cms] name the items to add: ${reg.items.map((i) => i.name).join(", ")}`);
|
|
1150
|
+
const items = resolveItems(reg, names2);
|
|
1151
|
+
const res = { written: [], skipped: [], updated: [], conflicts: [], unchanged: [], missingParts: [], diff: "" };
|
|
1152
|
+
const diffs = [];
|
|
1153
|
+
for (const it of items) {
|
|
1154
|
+
for (const f of it.files) {
|
|
1155
|
+
const target = join(layout.dir, basename(f.path));
|
|
1156
|
+
const rel = relative(o.cwd, target).split("\\").join("/");
|
|
1157
|
+
const next = rewriteImports(f.content ?? "", layout.aliases);
|
|
1158
|
+
const exists = existsSync(target);
|
|
1159
|
+
const cur = exists ? readFileSync(target, "utf8") : null;
|
|
1160
|
+
const locked = lock.files[rel];
|
|
1161
|
+
if (o.mode === "diff") {
|
|
1162
|
+
if (cur === null) diffs.push(`+++ ${rel} (not installed)`);
|
|
1163
|
+
else if (cur !== next) diffs.push(unifiedDiff(cur, next, { from: `${rel} (yours)`, to: `${rel} (${VERSION})` }));
|
|
1164
|
+
continue;
|
|
1165
|
+
}
|
|
1166
|
+
const write = () => {
|
|
1167
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
1168
|
+
writeFileSync(target, next);
|
|
1169
|
+
lock.files[rel] = { item: it.name, version: VERSION, hash: sha(next) };
|
|
1170
|
+
};
|
|
1171
|
+
if (cur === next) {
|
|
1172
|
+
lock.files[rel] = { item: it.name, version: VERSION, hash: sha(next) };
|
|
1173
|
+
res.unchanged.push(rel);
|
|
1174
|
+
continue;
|
|
1175
|
+
}
|
|
1176
|
+
if (o.mode === "add") {
|
|
1177
|
+
if (exists && !o.overwrite) {
|
|
1178
|
+
res.skipped.push({ file: rel, reason: locked ? "already installed (use --diff / --update)" : "a file with this name exists (use --overwrite)" });
|
|
1179
|
+
continue;
|
|
1180
|
+
}
|
|
1181
|
+
write();
|
|
1182
|
+
res.written.push(rel);
|
|
1183
|
+
continue;
|
|
1184
|
+
}
|
|
1185
|
+
if (cur === null) {
|
|
1186
|
+
write();
|
|
1187
|
+
res.written.push(rel);
|
|
1188
|
+
} else if (locked && sha(cur) === locked.hash) {
|
|
1189
|
+
write();
|
|
1190
|
+
res.updated.push(rel);
|
|
1191
|
+
} else {
|
|
1192
|
+
writeFileSync(`${target}.new`, next);
|
|
1193
|
+
res.conflicts.push(rel);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
const parts = shadcnParts(reg, items);
|
|
1198
|
+
res.missingParts = parts.filter((p) => !existsSync(join(layout.uiDir, `${p}.tsx`)) && !existsSync(join(layout.uiDir, `${p}.jsx`)));
|
|
1199
|
+
res.diff = diffs.filter(Boolean).join("\n\n");
|
|
1200
|
+
if (o.mode !== "diff") writeFileSync(join(o.cwd, LOCK_FILE), JSON.stringify({ ...lock, version: VERSION }, null, 2) + "\n");
|
|
1201
|
+
return res;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
// src/cli.ts
|
|
1205
|
+
var WITH_VALUE = /* @__PURE__ */ new Set(["--env", "--note", "--collections", "--expected-version", "--dir", "--format"]);
|
|
1206
|
+
function flag(argv, name) {
|
|
1207
|
+
const i = argv.indexOf(`--${name}`);
|
|
1208
|
+
if (i >= 0) return argv[i + 1];
|
|
1209
|
+
const eq2 = argv.find((a) => a.startsWith(`--${name}=`));
|
|
1210
|
+
return eq2?.slice(name.length + 3);
|
|
1211
|
+
}
|
|
1212
|
+
function positional(argv) {
|
|
1213
|
+
const out = [];
|
|
1214
|
+
for (let i = 0; i < argv.length; i++) {
|
|
1215
|
+
const a = argv[i];
|
|
1216
|
+
if (WITH_VALUE.has(a)) {
|
|
1217
|
+
i++;
|
|
1218
|
+
continue;
|
|
1219
|
+
}
|
|
1220
|
+
if (a.startsWith("--")) continue;
|
|
1221
|
+
out.push(a);
|
|
1222
|
+
}
|
|
1223
|
+
return out;
|
|
1224
|
+
}
|
|
1225
|
+
function parseEnvFile(text2) {
|
|
1226
|
+
const out = {};
|
|
1227
|
+
for (const line of text2.split(/\r?\n/)) {
|
|
1228
|
+
const m = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*)\s*$/.exec(line);
|
|
1229
|
+
if (m) out[m[1]] = m[2].replace(/^["']|["']$/g, "");
|
|
1230
|
+
}
|
|
1231
|
+
return out;
|
|
1232
|
+
}
|
|
1233
|
+
var USAGE = `agent-cms ${VERSION}
|
|
1234
|
+
in your app: init | doctor | migrate <check|print|apply> | add <item...> [--diff|--update]
|
|
1235
|
+
with a key: tools | collections | list | get | search | put | patch | publish | call
|
|
1236
|
+
see https://github.com/mainsoft-2024/agent-cms#cli`;
|
|
1237
|
+
var LOCAL = /* @__PURE__ */ new Set(["init", "doctor", "migrate", "add"]);
|
|
1238
|
+
async function runCli(argv, io = {}) {
|
|
1239
|
+
const out = io.out ?? ((l) => console.log(l));
|
|
1240
|
+
const err = io.err ?? ((l) => console.error(l));
|
|
1241
|
+
const read = io.readFile ?? ((p) => readFileSync2(p, "utf8"));
|
|
1242
|
+
const cwd = io.cwd ?? process.cwd();
|
|
1243
|
+
const [cmd, ...args] = positional(argv);
|
|
1244
|
+
if (cmd === "version" || !cmd && argv.includes("--version")) {
|
|
1245
|
+
out(VERSION);
|
|
1246
|
+
return 0;
|
|
1247
|
+
}
|
|
1248
|
+
if (!cmd || cmd === "help" || argv.includes("--help")) {
|
|
1249
|
+
out(USAGE);
|
|
1250
|
+
return cmd ? 0 : 1;
|
|
1251
|
+
}
|
|
1252
|
+
try {
|
|
1253
|
+
if (LOCAL.has(cmd)) return await runLocal(cmd, args, argv, { ...io, cwd, out, err });
|
|
1254
|
+
return await runRemote(cmd, args, argv, { ...io, out, err, read });
|
|
1255
|
+
} catch (e) {
|
|
1256
|
+
err(`[agent-cms] ${isCmsRemoteError(e) ? `${e.code}: ` : ""}${e instanceof Error ? e.message : String(e)}`);
|
|
1257
|
+
return 1;
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
async function runRemote(cmd, args, argv, io) {
|
|
1261
|
+
const { out, err, read } = io;
|
|
1262
|
+
const envFile = flag(argv, "env");
|
|
1263
|
+
const env = { ...io.env ?? process.env, ...envFile ? parseEnvFile(read(envFile)) : {} };
|
|
1264
|
+
if (!env.AGENT_CMS_URL || !env.AGENT_CMS_KEY) {
|
|
1265
|
+
err("[agent-cms] set AGENT_CMS_URL and AGENT_CMS_KEY (or pass --env <file>).");
|
|
1266
|
+
return 1;
|
|
1267
|
+
}
|
|
1268
|
+
const api = createCmsClient({ url: env.AGENT_CMS_URL, key: env.AGENT_CMS_KEY, fetch: io.fetch, clientName: "cli" });
|
|
1269
|
+
const print = (v) => out(JSON.stringify(v, null, 2));
|
|
1270
|
+
const need = (n) => {
|
|
1271
|
+
if (args.length < n) throw new CmsRemoteError(`missing arguments
|
|
1272
|
+
${USAGE}`, "usage");
|
|
1273
|
+
};
|
|
1274
|
+
const expectedVersion = () => {
|
|
1275
|
+
const raw = flag(argv, "expected-version");
|
|
1276
|
+
const n = raw === void 0 ? void 0 : Number(raw);
|
|
1277
|
+
if (n !== void 0 && !(Number.isInteger(n) && n > 0)) throw new CmsRemoteError("--expected-version must be a positive integer", "usage");
|
|
1278
|
+
return n;
|
|
1279
|
+
};
|
|
1280
|
+
switch (cmd) {
|
|
1281
|
+
case "tools":
|
|
1282
|
+
print((await api.listTools()).map((t) => ({ name: t.name, description: t.description })));
|
|
1283
|
+
return 0;
|
|
1284
|
+
case "collections":
|
|
1285
|
+
print(await api.call("list_collections"));
|
|
1286
|
+
return 0;
|
|
1287
|
+
case "list":
|
|
1288
|
+
need(1);
|
|
1289
|
+
print(await api.call("list_documents", { collection: args[0], drafts: argv.includes("--drafts") }));
|
|
1290
|
+
return 0;
|
|
1291
|
+
case "get":
|
|
1292
|
+
need(2);
|
|
1293
|
+
print(await api.call("get_document", { collection: args[0], slug: args[1], draft: argv.includes("--draft") }));
|
|
1294
|
+
return 0;
|
|
1295
|
+
case "search": {
|
|
1296
|
+
need(1);
|
|
1297
|
+
const cols = flag(argv, "collections");
|
|
1298
|
+
print(await api.call("search_documents", { query: args.join(" "), collections: cols ? cols.split(",") : void 0 }));
|
|
1299
|
+
return 0;
|
|
1300
|
+
}
|
|
1301
|
+
case "publish":
|
|
1302
|
+
need(2);
|
|
1303
|
+
print(await api.call("publish_document", { collection: args[0], slug: args[1] }));
|
|
1304
|
+
return 0;
|
|
1305
|
+
case "patch": {
|
|
1306
|
+
need(3);
|
|
1307
|
+
const ops = JSON.parse(read(args[2]));
|
|
1308
|
+
print(await api.call("patch_document", { collection: args[0], slug: args[1], ops: Array.isArray(ops) ? ops : [ops], expectedVersion: expectedVersion(), dryRun: argv.includes("--dry-run") }));
|
|
1309
|
+
return 0;
|
|
1310
|
+
}
|
|
1311
|
+
case "put": {
|
|
1312
|
+
need(2);
|
|
1313
|
+
const [collection, file] = args;
|
|
1314
|
+
const doc = docFromMarkdown(read(file), basename2(file).replace(/\.(md|markdown)$/i, ""));
|
|
1315
|
+
const publish = argv.includes("--publish");
|
|
1316
|
+
const note = flag(argv, "note");
|
|
1317
|
+
const expected = expectedVersion();
|
|
1318
|
+
const current = await api.call("get_document", { collection, slug: doc.slug, draft: true }).catch((e) => {
|
|
1319
|
+
if (isCmsRemoteError(e) && e.code === "not_found") return null;
|
|
1320
|
+
throw e;
|
|
1321
|
+
});
|
|
1322
|
+
if (current && expected === void 0 && !argv.includes("--force")) {
|
|
1323
|
+
throw new CmsRemoteError(`${collection}/${doc.slug} already exists (v${current.version}). Read it (get --draft), edit, then put with --expected-version <the version you read>.`, "conflict_version");
|
|
1324
|
+
}
|
|
1325
|
+
const result = current ? await api.call("update_document", { collection, slug: doc.slug, doc, expectedVersion: expected ?? current.version, publish, note }) : await api.call("create_document", { collection, doc, publish, note });
|
|
1326
|
+
print(result);
|
|
1327
|
+
return 0;
|
|
1328
|
+
}
|
|
1329
|
+
case "call": {
|
|
1330
|
+
need(1);
|
|
1331
|
+
const parsed = args[1] ? JSON.parse(args[1]) : {};
|
|
1332
|
+
print(await api.call(args[0], parsed));
|
|
1333
|
+
return 0;
|
|
1334
|
+
}
|
|
1335
|
+
default:
|
|
1336
|
+
err(`unknown command: ${cmd}
|
|
1337
|
+
${USAGE}`);
|
|
1338
|
+
return 1;
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
async function runLocal(cmd, args, argv, io) {
|
|
1342
|
+
if (cmd === "init") return init(argv, io);
|
|
1343
|
+
if (cmd === "add") return add(args, argv, io);
|
|
1344
|
+
const loaded = await loadConfig(io.cwd);
|
|
1345
|
+
const tables = cmsTables(loaded?.config.tables);
|
|
1346
|
+
if (cmd === "migrate" && args[0] === "print") {
|
|
1347
|
+
io.out(cmsDdl(tables));
|
|
1348
|
+
return 0;
|
|
1349
|
+
}
|
|
1350
|
+
let db = io.db;
|
|
1351
|
+
if (!db && loaded?.config.db) {
|
|
1352
|
+
try {
|
|
1353
|
+
db = await loaded.config.db();
|
|
1354
|
+
} catch (e) {
|
|
1355
|
+
io.err(`[agent-cms] db() in ${loaded.path} failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
1356
|
+
return 1;
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
if (!db) {
|
|
1360
|
+
io.err("[agent-cms] no database: add `db: () => yourDrizzleDb` to agent-cms.config.ts (run `npx agent-cms init` to create it).");
|
|
1361
|
+
return 1;
|
|
1362
|
+
}
|
|
1363
|
+
const repo = new DrizzleRepo(db, { tables });
|
|
1364
|
+
if (cmd === "doctor") return doctor(await repo.inspect(), tables.options, io);
|
|
1365
|
+
if (cmd === "migrate") {
|
|
1366
|
+
const sub = args[0] ?? "check";
|
|
1367
|
+
if (sub === "apply") {
|
|
1368
|
+
const { sql: sql2 } = await import("drizzle-orm");
|
|
1369
|
+
for (const stmt of splitSql(cmsDdl(tables))) await db.execute(sql2.raw(stmt));
|
|
1370
|
+
io.out(`[agent-cms] schema is at v${SCHEMA_VERSION}.`);
|
|
1371
|
+
return 0;
|
|
1372
|
+
}
|
|
1373
|
+
if (sub === "check") {
|
|
1374
|
+
const r = await repo.inspect();
|
|
1375
|
+
const pending = migrationSql(r, tables);
|
|
1376
|
+
if (!pending) {
|
|
1377
|
+
io.out(`[agent-cms] schema is up to date (v${SCHEMA_VERSION}).`);
|
|
1378
|
+
return 0;
|
|
1379
|
+
}
|
|
1380
|
+
if (flag(argv, "format") === "step") for (const s of pending.steps) io.out(`- ${s}`);
|
|
1381
|
+
else io.out(pending.sql);
|
|
1382
|
+
io.err(`[agent-cms] the database needs a migration (v${r.schemaVersion ?? "none"} -> v${SCHEMA_VERSION}). Put the SQL above in a migration, or run \`npx agent-cms migrate apply\`.`);
|
|
1383
|
+
return 1;
|
|
1384
|
+
}
|
|
1385
|
+
io.err(`unknown: migrate ${sub} (check | print | apply)`);
|
|
1386
|
+
return 1;
|
|
1387
|
+
}
|
|
1388
|
+
return 1;
|
|
1389
|
+
}
|
|
1390
|
+
function migrationSql(r, tables) {
|
|
1391
|
+
const current = r.schemaVersion ?? 0;
|
|
1392
|
+
if (!r.missingTables.length && !r.missingColumns.length && current >= SCHEMA_VERSION) return null;
|
|
1393
|
+
if (r.missingTables.some((t) => !t.endsWith("audit") && !t.endsWith("meta"))) return { sql: cmsDdl(tables), steps: ["create the agent-cms tables"] };
|
|
1394
|
+
const steps = upgradeSteps(tables).filter((s) => s.version > current || r.missingColumns.length > 0 || r.missingTables.length > 0);
|
|
1395
|
+
const meta = r.missingTables.some((t) => t.endsWith("meta")) ? `CREATE TABLE IF NOT EXISTS ${tables.options.schema ? `"${tables.options.schema}".` : ""}"${tables.options.prefix}meta" ("key" text PRIMARY KEY, "value" jsonb, "updated_at" timestamptz NOT NULL DEFAULT now());
|
|
1396
|
+
` : "";
|
|
1397
|
+
return { sql: `${meta}${steps.map((s) => `-- ${s.name}
|
|
1398
|
+
${s.sql}`).join("\n\n")}
|
|
1399
|
+
${schemaVersionSql(tables)}`, steps: steps.map((s) => s.name) };
|
|
1400
|
+
}
|
|
1401
|
+
function doctor(r, o, io) {
|
|
1402
|
+
const lines = [];
|
|
1403
|
+
let bad = false;
|
|
1404
|
+
const ok = (m) => lines.push(`ok ${m}`);
|
|
1405
|
+
const warn = (m) => lines.push(`warn ${m}`);
|
|
1406
|
+
const fail = (m) => {
|
|
1407
|
+
bad = true;
|
|
1408
|
+
lines.push(`FAIL ${m}`);
|
|
1409
|
+
};
|
|
1410
|
+
if (r.missingTables.length) fail(`missing tables: ${r.missingTables.join(", ")} (npx agent-cms migrate check)`);
|
|
1411
|
+
else ok("all tables exist");
|
|
1412
|
+
if (r.missingColumns.length) fail(`missing columns: ${r.missingColumns.join(", ")} (npx agent-cms migrate check)`);
|
|
1413
|
+
else if (!r.missingTables.length) ok("all columns exist");
|
|
1414
|
+
if (r.schemaVersion === null || r.schemaVersion < r.expectedSchemaVersion) fail(`schema version ${r.schemaVersion ?? "unknown"}, this release needs ${r.expectedSchemaVersion} (npx agent-cms migrate check)`);
|
|
1415
|
+
else ok(`schema version ${r.schemaVersion}`);
|
|
1416
|
+
if (r.badPublished) fail(`${r.badPublished} document(s) point at a published version that is missing`);
|
|
1417
|
+
if (r.orphanVersions) warn(`${r.orphanVersions} version row(s) without a document`);
|
|
1418
|
+
if (r.legacyColumns.length) {
|
|
1419
|
+
warn(`old columns nothing reads any more: ${r.legacyColumns.join(", ")}. To drop them:`);
|
|
1420
|
+
const t = (name) => o.schema ? `"${o.schema}"."${name}"` : `"${name}"`;
|
|
1421
|
+
for (const c of r.legacyColumns) {
|
|
1422
|
+
const [table, column] = c.split(".");
|
|
1423
|
+
lines.push(` ALTER TABLE ${t(table)} DROP COLUMN IF EXISTS "${column}";`);
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
if (r.gapsTable) {
|
|
1427
|
+
warn(`${o.prefix}gaps is still here (${r.gapsRows ?? "?"} rows). agent-cms 0.6 no longer uses it. Move it to your app (UPGRADE-0.6.md), then drop it yourself.`);
|
|
1428
|
+
}
|
|
1429
|
+
for (const l of lines) io.out(l);
|
|
1430
|
+
return bad ? 1 : 0;
|
|
1431
|
+
}
|
|
1432
|
+
function init(argv, io) {
|
|
1433
|
+
const cwd = io.cwd;
|
|
1434
|
+
const appDir = existsSync2(join2(cwd, "src", "app")) ? "src/" : "";
|
|
1435
|
+
const files = [
|
|
1436
|
+
[
|
|
1437
|
+
"agent-cms.config.ts",
|
|
1438
|
+
`import { defineConfig } from "@mainsoft/agent-cms/config";
|
|
1439
|
+
|
|
1440
|
+
export default defineConfig({
|
|
1441
|
+
// Your Drizzle database (used by \`agent-cms doctor\` and \`migrate\`).
|
|
1442
|
+
db: async () => (await import("./${appDir}lib/db")).db,
|
|
1443
|
+
});
|
|
1444
|
+
`
|
|
1445
|
+
],
|
|
1446
|
+
[
|
|
1447
|
+
`${appDir}lib/cms-schema.ts`,
|
|
1448
|
+
`// Re-export the agent-cms tables from your Drizzle schema so drizzle-kit sees them.
|
|
1449
|
+
export { cmsApiKeys, cmsAudit, cmsDocuments, cmsHits, cmsMeta, cmsVersions } from "@mainsoft/agent-cms/tables";
|
|
1450
|
+
`
|
|
1451
|
+
],
|
|
1452
|
+
[
|
|
1453
|
+
`${appDir}lib/cms.ts`,
|
|
1454
|
+
`import { createCms, defineCollection, DrizzleRepo } from "@mainsoft/agent-cms";
|
|
1455
|
+
import { db } from "./db";
|
|
1456
|
+
|
|
1457
|
+
export const posts = defineCollection({
|
|
1458
|
+
slug: "posts",
|
|
1459
|
+
label: "Posts",
|
|
1460
|
+
visibility: "public",
|
|
1461
|
+
url: (d) => \`/posts/\${d.slug}\`,
|
|
1462
|
+
});
|
|
1463
|
+
|
|
1464
|
+
export const cms = createCms({
|
|
1465
|
+
repo: new DrizzleRepo(db),
|
|
1466
|
+
collections: [posts],
|
|
1467
|
+
previewSecret: process.env.CMS_PREVIEW_SECRET,
|
|
1468
|
+
// Searches that found nothing (when the caller asks): store them if you want.
|
|
1469
|
+
onSearchMiss: async (e) => {
|
|
1470
|
+
void e;
|
|
1471
|
+
},
|
|
1472
|
+
});
|
|
1473
|
+
`
|
|
1474
|
+
],
|
|
1475
|
+
[
|
|
1476
|
+
`${appDir}app/api/cms/[...path]/route.ts`,
|
|
1477
|
+
`import { createCmsHandler } from "@mainsoft/agent-cms/http";
|
|
1478
|
+
import { cms } from "@/lib/cms";
|
|
1479
|
+
|
|
1480
|
+
const handler = createCmsHandler({
|
|
1481
|
+
cms,
|
|
1482
|
+
// Return the signed-in user, or null. Admins may do everything.
|
|
1483
|
+
resolveUser: async () => null,
|
|
1484
|
+
});
|
|
1485
|
+
|
|
1486
|
+
export { handler as GET, handler as POST, handler as PUT, handler as PATCH, handler as DELETE };
|
|
1487
|
+
`
|
|
1488
|
+
]
|
|
1489
|
+
];
|
|
1490
|
+
const created = [];
|
|
1491
|
+
for (const [rel, content] of files) {
|
|
1492
|
+
const p = join2(cwd, rel);
|
|
1493
|
+
if (existsSync2(p)) {
|
|
1494
|
+
io.out(`skip ${rel} (exists)`);
|
|
1495
|
+
continue;
|
|
1496
|
+
}
|
|
1497
|
+
mkdirSync2(dirname2(p), { recursive: true });
|
|
1498
|
+
writeFileSync2(p, content);
|
|
1499
|
+
created.push(rel);
|
|
1500
|
+
io.out(`write ${rel}`);
|
|
1501
|
+
}
|
|
1502
|
+
const envPath = join2(cwd, ".env.example");
|
|
1503
|
+
const envLines = ["CMS_PREVIEW_SECRET= # 32+ random characters, for draft preview links", "AGENT_CMS_URL=http://localhost:3000/api/cms", "AGENT_CMS_KEY= # sgk_... from the API keys screen"];
|
|
1504
|
+
const env = existsSync2(envPath) ? readFileSync2(envPath, "utf8") : "";
|
|
1505
|
+
const missing = envLines.filter((l) => !env.includes(l.split("=")[0] + "="));
|
|
1506
|
+
if (missing.length) {
|
|
1507
|
+
writeFileSync2(envPath, `${env}${env && !env.endsWith("\n") ? "\n" : ""}${missing.join("\n")}
|
|
1508
|
+
`);
|
|
1509
|
+
io.out(`write .env.example (${missing.length} line(s))`);
|
|
1510
|
+
}
|
|
1511
|
+
io.out(`
|
|
1512
|
+
next:
|
|
1513
|
+
1. point ${appDir}lib/cms.ts and agent-cms.config.ts at your Drizzle db, and resolveUser at your session
|
|
1514
|
+
2. npx agent-cms migrate check (SQL for your migration, or: npx agent-cms migrate apply)
|
|
1515
|
+
3. npx agent-cms add cms-shell cms-doc-list cms-doc-editor cms-versions cms-keys cms-audit cms-command`);
|
|
1516
|
+
void argv;
|
|
1517
|
+
return 0;
|
|
1518
|
+
}
|
|
1519
|
+
function add(args, argv, io) {
|
|
1520
|
+
const registry = io.registry ?? loadRegistry();
|
|
1521
|
+
if (argv.includes("--list")) {
|
|
1522
|
+
for (const it of registry.items) io.out(`${it.name.padEnd(16)} ${it.description ?? ""}`);
|
|
1523
|
+
return 0;
|
|
1524
|
+
}
|
|
1525
|
+
const mode = argv.includes("--diff") ? "diff" : argv.includes("--update") ? "update" : "add";
|
|
1526
|
+
const r = addItems({ cwd: io.cwd, items: args, mode, dir: flag(argv, "dir"), overwrite: argv.includes("--overwrite"), registry });
|
|
1527
|
+
if (mode === "diff") {
|
|
1528
|
+
io.out(r.diff || "[agent-cms] your copies match this version.");
|
|
1529
|
+
return 0;
|
|
1530
|
+
}
|
|
1531
|
+
for (const f of r.written) io.out(`write ${f}`);
|
|
1532
|
+
for (const f of r.updated) io.out(`update ${f}`);
|
|
1533
|
+
for (const f of r.unchanged) io.out(`same ${f}`);
|
|
1534
|
+
for (const s of r.skipped) io.out(`skip ${s.file} (${s.reason})`);
|
|
1535
|
+
for (const f of r.conflicts) io.out(`keep ${f} (you changed it; the new version is in ${f}.new)`);
|
|
1536
|
+
if (r.missingParts.length) {
|
|
1537
|
+
const cmd = ["shadcn@latest", "add", ...r.missingParts];
|
|
1538
|
+
if (argv.includes("--yes")) {
|
|
1539
|
+
const code = (io.run ?? ((c, a, cwd) => spawnSync(c, a, { cwd, stdio: "inherit", shell: process.platform === "win32" }).status ?? 1))("npx", ["--yes", ...cmd], io.cwd);
|
|
1540
|
+
if (code !== 0) {
|
|
1541
|
+
io.err(`[agent-cms] \`npx ${cmd.join(" ")}\` failed`);
|
|
1542
|
+
return 1;
|
|
1543
|
+
}
|
|
1544
|
+
} else io.out(`
|
|
1545
|
+
these screens use shadcn/ui parts you do not have yet:
|
|
1546
|
+
npx ${cmd.join(" ")}
|
|
1547
|
+
(or run add again with --yes)`);
|
|
1548
|
+
}
|
|
1549
|
+
return 0;
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
// src/bin.ts
|
|
1553
|
+
runCli(process.argv.slice(2)).then((code) => process.exit(code)).catch((err) => {
|
|
1554
|
+
console.error("[agent-cms]", err instanceof Error ? err.message : err);
|
|
1555
|
+
process.exit(1);
|
|
1556
|
+
});
|